Skip to lesson

Longest increasing subsequence

The Longest Increasing Subsequence problem highlights the transition from intuitive quadratic dynamic programming to optimal logarithmic search.

The quadratic dynamic programming approach

Longest increasing subsequence (LIS) is the longest sequence of array elements, in the original order but not necessarily next to each other, whose values strictly increase.

The longest increasing subsequence seeks the longest sequence of elements arranged in strictly ascending order. Unlike subarrays, subsequences do not require contiguous memory adjacency. Dynamic programming tracks the longest sequence ending at each specific index.

Step by step

Step 1 of 4

Array: 1, 1, 1, 1, 1, 1, 1, 1.
idx
0
maxLen
1
Array [10, 9, 2, 5, 3, 7, 101, 18]. Initialize dp array with all 1s.

Example 1 · Quadratic Longest Increasing Subsequence

LISQuadratic.javaJava
import java.util.Arrays;
public class LISQuadratic {    public static int lengthOfLIS(int[] nums) {        if (nums == null || nums.length == 0) return 0;        int n = nums.length;        int[] dp = new int[n];        Arrays.fill(dp, 1);        int maxLen = 1;
        for (int i = 1; i < n; i++) {            for (int j = 0; j < i; j++) {                if (nums[j] < nums[i]) {                    dp[i] = Math.max(dp[i], dp[j] + 1);                }            }            maxLen = Math.max(maxLen, dp[i]);        }        return maxLen;    }
    public static void main(String[] args) {        int[] arr1 = {10, 9, 2, 5, 3, 7, 101, 18};        System.out.println("LIS length 1: " + lengthOfLIS(arr1));        int[] arr2 = {0, 1, 0, 3, 2, 3};        System.out.println("LIS length 2: " + lengthOfLIS(arr2));        int[] arr3 = {7, 7, 7, 7};        System.out.println("LIS length 3: " + lengthOfLIS(arr3));    }}
Output
LIS length 1: 4
LIS length 2: 4
LIS length 3: 1

What this code does

  • State dp[i] records longest increasing subsequence length ending at index i.
  • Nested loops test all preceding elements j smaller than nums[i].
  • Arrays yield lengths 4, 4, and 1, handling duplicate values correctly.

Define dp[i] as the length of the longest increasing subsequence ending at index i. Initialize every cell to 1, because an individual element forms a valid sequence of length 1. To compute dp[i], examine all earlier indices j from 0 to i - 1. If nums[j] is strictly less than nums[i], element i can extend the sequence ending at j. The recurrence evaluates dp[i] = Math.max(dp[i], dp[j] + 1). The overall answer is the maximum value found across the entire dp array.

Optimal logarithmic patience sorting

Patience sorting improves time complexity from O(n^2) to O(n log n). Maintain a dynamic array named tails. Here tails[len - 1] stores the smallest ending tail among all increasing subsequences of length len.

Example 2 · Binary Search Patience Sorting LIS

LISBinarySearch.javaJava
import java.util.ArrayList;import java.util.Collections;import java.util.List;
public class LISBinarySearch {    public static int lengthOfLIS(int[] nums) {        if (nums == null || nums.length == 0) return 0;        List<Integer> tails = new ArrayList<>();
        for (int x : nums) {            int idx = Collections.binarySearch(tails, x);            if (idx < 0) idx = -(idx + 1);            if (idx == tails.size()) {                tails.add(x);            } else {                tails.set(idx, x);            }        }        return tails.size();    }
    public static void main(String[] args) {        int[] arr1 = {10, 9, 2, 5, 3, 7, 101, 18};        System.out.println("Binary search LIS: " + lengthOfLIS(arr1));        int[] arr2 = {4, 10, 4, 3, 8, 9};        System.out.println("Binary search LIS 2: " + lengthOfLIS(arr2));    }}
Output
Binary search LIS: 4
Binary search LIS 2: 3

What this code does

  • List tails maintains minimum tail elements for each discovered subsequence length.
  • Collections.binarySearch locates the insertion index in O(log n) time.
  • The final size of tails matches the maximum LIS length.

For each incoming number x, use binary search to locate the first entry in tails >= x. If x is greater than all existing elements in tails, append x to the end. Otherwise, overwrite the located entry with x to keep tail values as small as possible. Keeping tails minimal leaves maximum headroom for subsequent elements to extend sequences. Upon completion, the length of tails equals the length of the longest increasing subsequence. Note that tails stores optimal tail values rather than the literal subsequence elements.

Reconstructing and printing the actual sequence

Finding the length of the subsequence is often only the first part of an interview problem. To reconstruct the actual elements, augment the quadratic DP algorithm with a parent pointer array. Initialize parent[i] to negative one for all elements.

Example 3 · LIS Path Reconstruction

LISReconstruction.javaJava
import java.util.ArrayList;import java.util.Arrays;import java.util.Collections;import java.util.List;
public class LISReconstruction {    public static List<Integer> findLIS(int[] nums) {        int n = nums.length;        int[] dp = new int[n];        int[] parent = new int[n];        Arrays.fill(dp, 1);        Arrays.fill(parent, -1);        int maxLen = 1;        int bestIdx = 0;
        for (int i = 1; i < n; i++) {            for (int j = 0; j < i; j++) {                if (nums[j] < nums[i] && dp[j] + 1 > dp[i]) {                    dp[i] = dp[j] + 1;                    parent[i] = j;                }            }            if (dp[i] > maxLen) {                maxLen = dp[i];                bestIdx = i;            }        }
        List<Integer> res = new ArrayList<>();        int curr = bestIdx;        while (curr != -1) {            res.add(nums[curr]);            curr = parent[curr];        }        Collections.reverse(res);        return res;    }
    public static void main(String[] args) {        int[] arr = {10, 9, 2, 5, 3, 7, 101, 18};        System.out.println("LIS sequence: " + findLIS(arr));    }}
Output
LIS sequence: [2, 5, 7, 101]

What this code does

  • Array parent tracks predecessor indices whenever a longer subsequence extends.
  • Tracing parent pointers backwards from bestIdx yields reverse sequence.
  • Collections.reverse restores the chronological sequence [2, 5, 7, 101].

Whenever dp[i] updates via dp[j] + 1, record parent[i] = j. After filling the table, identify the index bestIdx holding the maximum value in dp. Trace backwards from bestIdx using parent pointers until reaching negative one. Collect the elements into an array list and reverse the order. Reversal restores original left-to-right chronological ordering in O(n) time. Pointer tracking provides a clean and deterministic way to recover optimal paths.

Next step

Check your understanding

10 quick questions