Tech Interview RoomStudy guides

Dynamic Programming

Find the length of the longest increasing subsequence.

Advanced · 2 min read · Lesson 4 of 6 in Dynamic Programming

Problem

[10, 9, 2, 5, 3, 7, 101, 18] → 4 (for example 2, 3, 7, 18). Elements need not be contiguous.

Approach

  • O(n²) DP: dp[i] = length of the LIS ending at i = 1 + max dp[j] for j < i with a[j] < a[i].
  • O(n log n) patience sorting: maintain tails[len] = the smallest possible tail of an increasing subsequence of length len + 1. For each number, binary-search the first tail ≥ it and replace it (or append if larger than all). The size of tails is the answer.
java
import java.util.Arrays;

class LongestIncreasingSubsequence {
    static int lengthQuadratic(int[] a) {
        int[] dp = new int[a.length];
        int best = 0;
        for (int i = 0; i < a.length; i++) {
            dp[i] = 1;
            for (int j = 0; j < i; j++) if (a[j] < a[i]) dp[i] = Math.max(dp[i], dp[j] + 1);
            best = Math.max(best, dp[i]);
        }
        return best;
    }

    static int length(int[] a) {
        int[] tails = new int[a.length];
        int size = 0;
        for (int x : a) {
            int pos = Arrays.binarySearch(tails, 0, size, x);
            if (pos < 0) pos = -(pos + 1);        // insertion point = first tail >= x
            tails[pos] = x;
            if (pos == size) size++;
        }
        return size;
    }

    public static void main(String[] args) {
        int[] a = {10, 9, 2, 5, 3, 7, 101, 18};
        System.out.println(lengthQuadratic(a));   // 4
        System.out.println(length(a));            // 4
    }
}

Complexity

O(n²) for the DP; O(n log n) time and O(n) space for the binary-search version.

Follow-up questions interviewers ask

Try answering each one before you open it.

Is the `tails` array itself a valid increasing subsequence?

Not necessarily: it holds the best tail for each length, possibly from different subsequences. Its length is correct, though. To reconstruct an actual subsequence, store for each element the index of its predecessor (the element at tails[pos - 1] when it was placed) and walk back from the last element placed in the final position.

Where does LIS show up in practice?

Diff algorithms (patience diff), version or dependency ordering, scheduling with non-decreasing constraints, and box or envelope nesting problems (sort by one dimension, LIS on the other).