Skip to content

Longest Increasing Subsequence

MediumLeetCode #300Time O(n log n)Space O(n)

Given an integer array, return the length of its longest strictly increasing subsequence. A subsequence keeps the original order but may skip elements.

nums = [10, 9, 2, 5, 3, 7, 101, 18] -> 4 (for example 2, 3, 7, 18)

Start with the simple DP: dp[i] = 1 + max(dp[j]) over all j < i with nums[j] < nums[i] (or 1 if none). The answer is the max over all dp[i]. That is O(n²) and is a fine first answer.

To reach O(n log n), keep an array tails, where tails[k] is the smallest possible last value of any increasing subsequence of length k + 1. It stays sorted. For each number, binary search for the first tail >= num and overwrite it; if there is none, append. Smaller tails leave more room to extend later. The final length of tails is the answer.

tails is not an actual LIS. It mixes values from different subsequences, so only its length is meaningful.

Show solutionHide solution
from bisect import bisect_left
def length_of_lis(nums: list[int]) -> int:
tails = [] # tails[k] = smallest tail of any increasing subsequence of length k + 1
for num in nums:
i = bisect_left(tails, num) # first tail >= num (strict increase)
if i == len(tails):
tails.append(num)
else:
tails[i] = num
return len(tails)
  • Time: O(n log n) — n numbers, each does one O(log n) binary search.
  • Space: O(n) — tails can grow to length n when the input is already increasing.
  • Strict vs non-strict. Search for the first tail >= num (bisect_left). Using bisect_right would allow equal values and give [7, 7, 7] a length of 3.
  • Don’t return tails as the sequence. For [3, 4, 1] it ends as [1, 4], but 1 comes after 4 in the input, so that is not a subsequence. Only its length is valid. Rebuilding the sequence needs extra parent bookkeeping.
  • Greedy “extend the last element” fails. You need the DP or the tails idea.
  • State the O(n²) version first if you blank on binary search; it earns partial credit.

Number of Longest Increasing Subsequence (LeetCode 673)

Section titled “Number of Longest Increasing Subsequence (LeetCode 673)”

Count how many LIS exist. The trick: the O(n²) DP with two arrays: length[i] and count[i]. When a longer chain is found, reset the count; when an equal-length chain is found, add counts.

Nest envelopes where both width and height are strictly larger. The trick: sort by width ascending, and by height descending for equal widths, then run LIS on heights. The descending tie-break stops two envelopes of the same width from nesting.

Increasing Triplet Subsequence (LeetCode 334)

Section titled “Increasing Triplet Subsequence (LeetCode 334)”

Is there any increasing subsequence of length 3? The trick: the tails idea with only two slots, first and second. If a number exceeds second, you have a triplet. O(n) time, O(1) space.