300. Longest Increasing Subsequence
Medium NeetCode 150 ↗ Open on LeetCode Source: Standard solution only
Quick review
- Pattern
- 1-D Dynamic Programming
- Time
- O(n log n)
- Space
- O(n)
Standard Solution (C++)
SummaryFind the length of the longest strictly increasing subsequence within an array of integers.
Approach
Patience sorting with binary search. Maintain a list 'tails' where tails[i] is the smallest possible tail value of an increasing subsequence of length i+1.
- For each number, binary-search for the first tail that is not less than it.
- If found, overwrite it; otherwise append, extending the longest subsequence.
- The length of 'tails' is the answer.
class Solution {
public:
int lengthOfLIS(vector<int>& nums) {
vector<int> tails;
for (int x : nums) {
auto it = lower_bound(tails.begin(), tails.end(), x);
if (it == tails.end()) tails.push_back(x);
else *it = x;
}
return tails.size();
}
}; Time O(n log n) Space O(n)
A canonical reference solution. Problem statement © LeetCode — see the official link above.
▶ Run it — editable in-browser playground with a sample driver C++
Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.
C++ ▶ Runnable Auto-generated driver with sample input — unverified.
Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.