Longest Increasing Subsequence (LeetCode 300): Solution and Explanation

Medium
Array
Binary Search
Dynamic Programming

Given an array of integers, find the length of the longest subsequence whose values are strictly increasing. A subsequence keeps the original order but may skip elements.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

The brute force considers every subset of indices, checks whether the chosen values are strictly increasing, and keeps the longest. With 2^n subsets that is hopeless beyond a couple dozen elements, but it shows the real decision: for each element, do you include it or not.

A better way to think about it is to anchor the subsequence at a starting index. Let dp[i] be the length of the longest increasing subsequence that begins at nums[i]. Any such subsequence is either just nums[i] by itself, or nums[i] followed by the best subsequence starting at some later index j where nums[j] is larger. So dp[i] is 1 plus the largest dp[j] among those valid j.

Because dp[i] depends only on entries to its right, filling the array from the end backward means every dp[j] is final before it is used. The answer is the largest value anywhere in dp, since the longest subsequence can start at any index. This gives a clean quadratic solution, which comfortably handles the given limit of 2,500 elements.

Approach: O(n²) dynamic programming from the right

  1. Create dp of length n filled with 1, since every element alone is an increasing subsequence.
  2. Iterate i from n - 1 down to 0.
  3. For each j from i + 1 to n - 1, check whether nums[i] < nums[j].
  4. If so, nums[i] can be prepended to the best subsequence starting at j, so set dp[i] = max(dp[i], 1 + dp[j]).
  5. Return max(dp).

Step-by-step example

nums = [1,3,2,4]
  1. Start with dp = [1, 1, 1, 1]. Index 3 (value 4) has nothing after it, so dp[3] = 1.
  2. i = 2 (value 2): 4 is larger, so dp[2] = 1 + dp[3] = 2.
  3. i = 1 (value 3): 2 is not larger, 4 is, so dp[1] = 1 + dp[3] = 2.
  4. i = 0 (value 1): j = 1 gives 1 + 2 = 3, j = 2 gives 3, j = 3 gives 2, so dp[0] = 3.
  5. dp = [3, 2, 2, 1] and max(dp) = 3, for example [1,3,4] or [1,2,4].

Code: Python, Java, C++

1class Solution:
2    def lengthOfLIS(self, nums: List[int]) -> int:
3        dp = [1] * len(nums)
4        
5        for i in range(len(nums) - 1, -1, -1):
6            for j in range(i + 1, len(nums)):
7                if nums[i] < nums[j]:
8                    dp[i] = max(dp[i], 1 + dp[j])
9                    
10        return max(dp)

Time and space complexity

Time

O(n²)

For each index i the inner loop scans every later index, which is about n²/2 comparisons in total. With n at most 2,500 that is roughly three million comparisons, well within limits.

Space

O(n)

The dp array holds one length per element.

Other approaches

Patience sorting with binary search (time O(n log n), space O(n))

Keep an array tails where tails[k] is the smallest possible tail of an increasing subsequence of length k + 1. For each number, binary search for the first tail that is at least as large and replace it, or append if none exists. The length of tails is the answer. This is the follow-up for large inputs. For example, on [1,3,2,4] the tails go [1], [1,3], [1,2], [1,2,4].

Recursion with memoization (time O(n²), space O(n²))

Recurse on (index, previous chosen index) with include or skip choices and cache results. It mirrors the brute force directly but uses O(n²) memory for the cache, so the bottom-up table is usually preferred.

Common mistakes

  • Returning dp[0] instead of max(dp). The longest subsequence does not have to start at the first element.
  • Using <= instead of <, which counts equal values and breaks the strictly increasing requirement.
  • Treating the problem as a contiguous subarray question. Elements may be skipped, so a sliding window does not apply.
  • Believing the tails array in the binary search method is an actual subsequence. Only its length is meaningful.

Frequently asked questions

What is the time complexity of longest increasing subsequence?

The DP shown here is O(n²) time and O(n) space. The patience sorting variant with binary search brings time down to O(n log n) with the same space.

How does the O(n log n) LIS solution work?

It maintains the smallest tail value for every possible subsequence length. A new number either extends the longest subsequence or replaces a tail with a smaller value found by binary search, which keeps future options open. The number of tails at the end equals the LIS length.

How do I reconstruct the actual subsequence?

Store, for each i, the j that produced its best dp[i]. Start from the index with the largest dp value and follow those links forward to print the elements in order.

Is a subsequence the same as a subarray?

No. A subarray is contiguous, while a subsequence keeps order but can skip elements. That freedom is why this problem needs DP rather than a two-pointer window.