Longest Increasing Subsequence (LeetCode 300): Solution and Explanation
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.
Watch it run step by step
Try your own input and write the code →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
- Create
dpof length n filled with 1, since every element alone is an increasing subsequence. - Iterate
ifrom n - 1 down to 0. - For each
jfromi + 1to n - 1, check whethernums[i] < nums[j]. - If so,
nums[i]can be prepended to the best subsequence starting atj, so setdp[i] = max(dp[i], 1 + dp[j]). - Return
max(dp).
Step-by-step example
nums = [1,3,2,4]
- Start with
dp = [1, 1, 1, 1]. Index 3 (value 4) has nothing after it, sodp[3] = 1. - i = 2 (value 2): 4 is larger, so
dp[2] = 1 + dp[3] = 2. - i = 1 (value 3): 2 is not larger, 4 is, so
dp[1] = 1 + dp[3] = 2. - i = 0 (value 1): j = 1 gives
1 + 2 = 3, j = 2 gives 3, j = 3 gives 2, sodp[0] = 3. dp = [3, 2, 2, 1]andmax(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)1class Solution {
2 public int lengthOfLIS(int[] nums) {
3 int[] dp = new int[nums.length];
4 Arrays.fill(dp, 1);
5 int maxLen = 1;
6
7 for (int i = nums.length - 1; i >= 0; i--) {
8 for (int j = i + 1; j < nums.length; j++) {
9 if (nums[i] < nums[j]) {
10 dp[i] = Math.max(dp[i], 1 + dp[j]);
11 }
12 }
13 maxLen = Math.max(maxLen, dp[i]);
14 }
15 return maxLen;
16 }
17}1class Solution {
2public:
3 int lengthOfLIS(vector<int>& nums) {
4 vector<int> dp(nums.size(), 1);
5
6 for (int i = nums.size() - 1; i >= 0; i--) {
7 for (int j = i + 1; j < nums.size(); j++) {
8 if (nums[i] < nums[j]) {
9 dp[i] = max(dp[i], 1 + dp[j]);
10 }
11 }
12 }
13 return *max_element(dp.begin(), dp.end());
14 }
15};Time and space complexity
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.
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 ofmax(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
tailsarray 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.