Lesson 40 of 73 2 min

Problem: Longest Increasing Subsequence

Learn how to find the longest strictly increasing subsequence in O(n^2) and O(n log n).

Problem Statement

Given an integer array nums, return the length of the longest strictly increasing subsequence.

A subsequence is a sequence that can be derived from an array by deleting some or no elements without changing the order of the remaining elements.

Approach 1: Bottom-Up DP ($O(n^2)$)

  1. State: dp[i] is the length of the longest increasing subsequence ending at index i.
  2. Base Case: dp[i] = 1 (Every element is a subsequence of length 1).
  3. Transition: For each element j < i, if nums[i] > nums[j], then dp[i] = max(dp[i], dp[j] + 1).

Java Implementation

public int lengthOfLIS(int[] nums) {
    if (nums.length == 0) return 0;
    
    int[] dp = new int[nums.length];
    Arrays.fill(dp, 1);
    int maxLen = 1;
    
    for (int i = 1; i < nums.length; i++) {
        for (int j = 0; j < i; j++) {
            if (nums[i] > nums[j]) {
                dp[i] = Math.max(dp[i], dp[j] + 1);
            }
        }
        maxLen = Math.max(maxLen, dp[i]);
    }
    return maxLen;
}

Approach 2: Binary Search ($O(n \log n)$)

This advanced approach maintains a list of "tails" of all increasing subsequences.

  • For each number:
    • If it's larger than the largest tail, append it.
    • Otherwise, find the smallest tail larger than it and replace it.

Complexity Analysis

  • Time Complexity: $O(n^2)$ for DP, $O(n \log n)$ for Binary Search.
  • Space Complexity: $O(n)$.

Interview Tips

  • "Approach 1 is the standard DP way. Approach 2 is an optimized version that is often asked in senior-level interviews."

Want to track your progress?

Sign in to save your progress, track completed lessons, and pick up where you left off.