Longest Increasing Subsequence
Medium · Dynamic programming
Jump to codeReturn the length of the longest strictly increasing subsequence of an integer array. Chosen elements keep their order but need not be adjacent.
Examples
Example 1
nums = [10,9,2,5,3,7,101,18]
Output: 4
Example 2
nums = [0,1,0,3,2,3]
Output: 4
Constraints
- 1 <= nums.length <= 1000
- -1000 <= nums[i] <= 1000
Need a hint?
Keep the smallest possible tail for each achievable subsequence length.
Asked in real interviews
Candidates reported versions of Longest Increasing Subsequence from these company interviews. Some company questions are locked and open with Premium or XP.
- Compute length of longest increasing subsequenceTikTok
- Design Algorithm for Longest Increasing Subsequence LengthExperian
- Maximal Square and Longest Increasing SubsequenceSalesforce
Solution approach
Maintain sorted tails. For each value x, binary-search the first tail ≥ x and replace it, or append if none exists. Smaller tails leave more room for future values. The tails list gives the correct length, although its final contents need not form one input subsequence.
Complexity
O(n log n) time and O(n) space.
Python reference solution
from bisect import bisect_left
def lengthOfLIS(nums):
tails = []
for value in nums:
index = bisect_left(tails, value)
if index == len(tails):
tails.append(value)
else:
tails[index] = value
return len(tails)
JavaScript solution
function lengthOfLIS(nums) {
const tails = [];
for (const value of nums) {
let left = 0, right = tails.length;
while (left < right) {
const middle = left + Math.floor((right - left) / 2);
if (tails[middle] < value) left = middle + 1;
else right = middle;
}
tails[left] = value;
}
return tails.length;
}
Java solution
import java.util.*;
class Solution {
public int lengthOfLIS(int[] nums) {
int[] tails = new int[nums.length];
int size = 0;
for (int value : nums) {
int left = 0, right = size;
while (left < right) {
int middle = left + (right - left) / 2;
if (tails[middle] < value) left = middle + 1;
else right = middle;
}
tails[left] = value;
if (left == size) size++;
}
return size;
}
}
C++ solution
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int lengthOfLIS(vector<int> &nums) {
vector<int> tails;
for (int value : nums) {
auto position = lower_bound(tails.begin(), tails.end(), value);
if (position == tails.end()) tails.push_back(value);
else *position = value;
}
return tails.size();
}
};
Trace a boundary case, then implement the approach in the editor. Submit checks your solution against all 8 test cases.
Keep your reasoning, pseudocode, and edge cases here.
Notes stay in this browser when storage is available.
Accepted submissions mark this problem complete. Progress stays in this browser.
[
[
10,
9,
2,
5,
3,
7,
101,
18
]
]4
[
[
0,
1,
0,
3,
2,
3
]
]4
[
[
7,
7,
7,
7,
7,
7,
7
]
]1
[
[
1,
2,
3,
4
]
]4
[
[
4,
3,
2,
1
]
]1
Drafts are saved per language in this browser when storage is available.