Try it first — give it 25 minutes
0/4 revealedStuck? Take one hint at a time. The struggle is where the pattern sticks.
The problem in plain English
You get an integer array nums. A subsequence keeps some elements in their original order and may skip others (it doesn't have to be contiguous). Return the length of the longest subsequence whose values are strictly increasing: each value bigger than the one before, with no equal neighbours.
nums has 1 to 2500 elements, each between −10⁴ and 10⁴.
Example: nums = [10, 9, 2, 5, 3, 7, 101, 18] → 4. One answer is [2, 3, 7, 18]; [2, 5, 7, 101] works too.
Start with brute force
Try every subsequence, keep those that increase, return the longest. There are 2ⁿ subsequences; for n = 2500 that number has over 750 digits. No chance.
Building the intuition
Step 1: the O(n²) DP
Use the recipe. The trick for subsequences is to pin down where the subsequence ends.
- State.
dp[i]means the length of the longest increasing subsequence that ends exactly atnums[i](it must usenums[i]as its last element). - Recurrence. The element before
nums[i]is somenums[j]withj < iandnums[j] < nums[i]. Extend the best one:dp[i] = 1 + max(dp[j])over thosej, or 1 if there are none. - Base case. Every element alone is an increasing subsequence of length 1.
- Order. Left to right. The answer is the max of the whole table, not
dp[n − 1], because the best subsequence can end anywhere.
dp = [1] * n
for i in range(n):
for j in range(i):
if nums[j] < nums[i]:
dp[i] = max(dp[i], dp[j] + 1)
return max(dp)That's O(n²): about 3 million steps for n = 2500. It passes, and it's what you should say first in an interview.
Step 2: where is the waste?
For each i, the inner loop asks: "of all earlier subsequences ending below nums[i], which is longest?" It scans everything to answer that.
Flip the question. Instead of remembering every ending, remember for each length the smallest value a subsequence of that length can end with. A smaller ending is always at least as good: anything that can extend a subsequence ending in 7 can also extend one ending in 3.
Call it tails[k] = the smallest value that can end an increasing subsequence of length k + 1. This list is always sorted (a longer subsequence can't end lower than the best shorter one). Sorted means binary search.
For a new value x, find k, the first slot with tails[k] ≥ x:
- Every slot before
kholds a tail smaller thanx, soxcan extend a subsequence of lengthk. The best subsequence ending atxhas lengthk + 1. That's exactlydp[i]. - If
kis past the end,xmakes a new longest length: append it. - Otherwise
xis a smaller ending for lengthk + 1: overwritetails[k] = x.
The optimal approach
- Start with an empty
tails. - For each
xinnums:k= first index withtails[k] ≥ x(a lower-bound binary search).- If
k == len(tails), appendx. Otherwise settails[k] = x.
- Return
len(tails).
The subtle detail: ≥, not >. "Strictly increasing" means an equal value can't extend. Searching for the first tail ≥ x makes an equal value replace that tail instead of appending after it. With [7, 7, 7] you get length 1, as you should. (Python's bisect_left and C++'s lower_bound do exactly this.)
Warning: tails is not the subsequence itself. It's a mix of endings from different candidates. Only its length is meaningful.
The code
Every solution below is tested against the examples and edge cases before it ships. Pick your language — we'll remember it.
import bisect
class Solution:
def lengthOfLIS(self, nums: List[int]) -> int:
# tails[k] = the smallest value that can end an increasing subsequence of length k + 1
# (tails is always strictly increasing, so we can binary search it)
tails = []
for x in nums:
# k = first slot whose tail is >= x; x can extend every length before slot k,
# so the longest increasing subsequence ending at x has length k + 1 (that's dp[i])
k = bisect.bisect_left(tails, x)
if k == len(tails):
tails.append(x) # x beats every tail: a new, longer length
else:
tails[k] = x # same length, smaller ending: easier to extend later
return len(tails)class Solution {
public:
int lengthOfLIS(vector<int>& nums) {
// tails[k] = the smallest value that can end an increasing subsequence of length k + 1
// (tails is always strictly increasing, so we can binary search it)
vector<int> tails;
for (int x : nums) {
// k = first slot whose tail is >= x; x can extend every length before slot k,
// so the longest increasing subsequence ending at x has length k + 1 (that's dp[i])
int k = lower_bound(tails.begin(), tails.end(), x) - tails.begin();
if (k == (int)tails.size()) {
tails.push_back(x); // x beats every tail: a new, longer length
} else {
tails[k] = x; // same length, smaller ending: easier to extend later
}
}
return tails.size();
}
};class Solution {
public int lengthOfLIS(int[] nums) {
// tails[k] = the smallest value that can end an increasing subsequence of length k + 1
// (tails[0..size-1] is always strictly increasing, so we can binary search it)
int[] tails = new int[nums.length];
int size = 0;
for (int x : nums) {
// k = first slot whose tail is >= x; x can extend every length before slot k,
// so the longest increasing subsequence ending at x has length k + 1 (that's dp[i])
int lo = 0, hi = size;
while (lo < hi) {
int mid = (lo + hi) >>> 1;
if (tails[mid] < x) lo = mid + 1;
else hi = mid;
}
int k = lo;
tails[k] = x; // same length, smaller ending: easier to extend later
if (k == size) size++; // x beat every tail: a new, longer length
}
return size;
}
}/**
* @param {number[]} nums
* @return {number}
*/
var lengthOfLIS = function (nums) {
// tails[k] = the smallest value that can end an increasing subsequence of length k + 1
// (tails is always strictly increasing, so we can binary search it)
const tails = [];
for (const x of nums) {
// k = first slot whose tail is >= x; x can extend every length before slot k,
// so the longest increasing subsequence ending at x has length k + 1 (that's dp[i])
let lo = 0, hi = tails.length;
while (lo < hi) {
const mid = (lo + hi) >> 1;
if (tails[mid] < x) lo = mid + 1;
else hi = mid;
}
const k = lo;
if (k === tails.length) {
tails.push(x); // x beats every tail: a new, longer length
} else {
tails[k] = x; // same length, smaller ending: easier to extend later
}
}
return tails.length;
};Dry run
nums = [10, 9, 2, 5, 3, 7, 101, 18]. The last column is dp[i] = k + 1, the same table the O(n²) version fills.
| i | x | tails before | k (first tail ≥ x) | action | tails after | dp[i] |
|---|---|---|---|---|---|---|
| 0 | 10 | [] | 0 (end) | append | [10] | 1 |
| 1 | 9 | [10] | 0 | replace 10 | [9] | 1 |
| 2 | 2 | [9] | 0 | replace 9 | [2] | 1 |
| 3 | 5 | [2] | 1 (end) | append | [2, 5] | 2 |
| 4 | 3 | [2, 5] | 1 | replace 5 | [2, 3] | 2 |
| 5 | 7 | [2, 3] | 2 (end) | append | [2, 3, 7] | 3 |
| 6 | 101 | [2, 3, 7] | 3 (end) | append | [2, 3, 7, 101] | 4 |
| 7 | 18 | [2, 3, 7, 101] | 3 | replace 101 | [2, 3, 7, 18] | 4 |
Full DP table: dp = [1, 1, 1, 2, 2, 3, 4, 4], max 4. And len(tails) = 4. Same answer, but each row cost one binary search instead of a scan.
Complexity
- Time: O(n log n). One binary search over at most
ntails per element. - Space: O(n) for
tails(the O(n²) version also needs O(n) fordp).
Edge cases and traps
- Returning
dp[n − 1]in the O(n²) version. The longest subsequence may end earlier. Returnmax(dp). - Duplicates.
[7, 7, 7]→ 1. Usingbisect_right/upper_boundwould give 3, the answer for "non-decreasing". - Reading
tailsas the answer subsequence. In the dry run,[2, 3, 7, 18]happens to be valid, but in general it isn't. To rebuild a real subsequence, store each element's predecessor. - Already sorted, or reverse sorted.
[1, 2, 3, 4, 5]→ 5 (append every time).[5, 4, 3, 2, 1]→ 1 (replace slot 0 every time).
Say it in the interview
"Let
dp[i]be the longest increasing subsequence ending atnums[i]. It's 1 plus the bestdp[j]with a smaller value before it, which is O(n²). To speed it up I keeptails[k], the smallest value that ends an increasing subsequence of lengthk + 1. That list stays sorted, so for each number I binary-search the first tail that's at least as big and replace it, or append if there isn't one. The insertion position plus one isdp[i]. The answer is the length oftails: O(n log n) time, O(n) space."
Follow-ups interviewers ask
- "Return the subsequence itself." Store, for each element, the index of the element before it (from
tailspositions), then walk back from the last element of the longest one. - "Non-decreasing instead of strictly increasing?" Search for the first tail strictly greater than
x(bisect_right). - "Russian Doll Envelopes?" Sort by width ascending and height descending, then run this LIS on heights. The descending tie-break stops equal widths from nesting.
Practise the same idea
This is Day 84 of a free 90-day plan 🐸
90 problems in the order that builds on itself, one a day, with a walkthrough like this for each. Tick them off and keep your streak.
Get the full roadmap — free