LeetCode #300 Medium

Longest Increasing Subsequence

Longest Increasing Subsequence is LeetCode 300 (Medium). Given an integer array nums, return the length of the longest strictly increasing subsequence.

A subsequence keeps the original order but may skip elements, so the chosen numbers do not have to be next to each other. Equal neighbours do not count as increasing.

The follow-up asks for O(n log n) time.

Constraints
  • 1 <= nums.length <= 2500
  • -10⁴ <= nums[i] <= 10⁴
dpbinary-search
Open on LeetCode ↗
02

Intuition

Many increasing subsequences of the same length can exist, but only one of them matters: the one that ends in the smallest number. Any later value that extends a chain ending in 9 also extends a chain ending in 2, so the chain ending in 9 can be forgotten.

So keep tails, where tails[k] is the smallest possible last number of an increasing subsequence of length k + 1. This list is always sorted. Each new number either goes past the end (a longer chain exists) or replaces the first entry that is not smaller than it (an equally long chain now ends lower). Finding that spot is a binary search, so each number costs O(log n).

03

Approach

1

Start with an empty tails list

tails will hold one entry per possible length. It starts empty because no subsequence has been seen yet.

2

Binary search for each number's place

For each x, find k, the first index with tails[k] >= x (bisect_left). Every entry before k is smaller than x, so x can extend a chain of length k into one of length k + 1.

3

Append or replace

  • If k == len(tails), every tail is smaller than x: append it, the longest chain just grew.
  • Otherwise set tails[k] = x. The length stays the same, but a chain of that length now ends in a smaller number, which can only help later values.
4

Why the list stays sorted

x lands just after the last entry smaller than it and replaces an entry at least as big. So it is bigger than the entry before it and not bigger than the one it replaced, which keeps the list increasing and the binary search valid.

5

Return the length

The answer is len(tails): one entry exists for every length that some increasing subsequence reaches.

04

Code in Python, C++ and Java

▶1from bisect import bisect_left
▶2from typing import List
▶3 
▶4 
▶5class Solution:
▶6 def lengthOfLIS(self, nums: List[int]) -> int:
▶7 tails = []
▶8 for x in nums:
▶9 k = bisect_left(tails, x)
▶10 if k == len(tails):
▶11 tails.append(x)
▶12 else:
▶13 tails[k] = x
▶14 return len(tails)
nums109253710118length 1one increasing subsequenceno piles yet
piles0pile k holds subsequences of length k
Deal the numbers onto piles. Each number goes on the leftmost pile whose top is not smaller than it, or starts a new pile on the right. The top of pile k is the smallest number that can end an increasing subsequence of length k, and a smaller ending is always easier to extend.
nums109253710118length 110one increasing subsequence10 starts the first pile
pile tops10always increasing, so binary search works
piles1
The first number is an increasing subsequence of length 1 on its own. Piles: 1.
nums109253710118length 1109one increasing subsequence9 is smaller than 10 → it replaces it on pile 1
pile tops9always increasing, so binary search works
piles1
Binary search finds pile 1, the first top that is not smaller than 9. A subsequence of length 1 can now end in 9 instead of 10, and a smaller ending leaves more room for later numbers. The number of piles does not change.
nums109253710118length 11092one increasing subsequence2 is smaller than 9 → it replaces it on pile 1
pile tops2always increasing, so binary search works
piles1
Binary search finds pile 1, the first top that is not smaller than 2. A subsequence of length 1 can now end in 2 instead of 9, and a smaller ending leaves more room for later numbers. The number of piles does not change.
nums109253710118length 11092length 25after 2one increasing subsequence5 is bigger than every top → new pile 2
pile tops2, 5always increasing, so binary search works
piles2
Binary search over the pile tops finds no top that is 5 or more, so 5 extends the longest chain so far. It remembers the top of the pile to its left (2), which is the number it follows. Piles: 2.
nums109253710118length 11092length 25after 23after 2one increasing subsequence3 is smaller than 5 → it replaces it on pile 2
pile tops2, 3always increasing, so binary search works
piles2
Binary search finds pile 2, the first top that is not smaller than 3. A subsequence of length 2 can now end in 3 instead of 5, and a smaller ending leaves more room for later numbers. The number of piles does not change.
nums109253710118length 11092length 25after 23after 2length 37after 3one increasing subsequence7 is bigger than every top → new pile 3
pile tops2, 3, 7always increasing, so binary search works
piles3
Binary search over the pile tops finds no top that is 7 or more, so 7 extends the longest chain so far. It remembers the top of the pile to its left (3), which is the number it follows. Piles: 3.
nums109253710118length 11092length 25after 23after 2length 37after 3length 4101after 7one increasing subsequence101 is bigger than every top → new pile 4
pile tops2, 3, 7, 101always increasing, so binary search works
piles4
Binary search over the pile tops finds no top that is 101 or more, so 101 extends the longest chain so far. It remembers the top of the pile to its left (7), which is the number it follows. Piles: 4.
nums109253710118length 11092length 25after 23after 2length 37after 3length 4101after 718after 7one increasing subsequence18 is smaller than 101 → it replaces it on pile 4
pile tops2, 3, 7, 18always increasing, so binary search works
piles4
Binary search finds pile 4, the first top that is not smaller than 18. A subsequence of length 4 can now end in 18 instead of 101, and a smaller ending leaves more room for later numbers. The number of piles does not change.
nums109253710118length 11092length 25after 23after 2length 37after 3length 4101after 718after 7one increasing subsequence1818 came after 7 → follow the link
read back18
Printing the subsequence. The pile tops alone can mix numbers from different subsequences, so they are not always a real answer. Each card, though, recorded the card it was placed after. Following those links from the last pile gives numbers that really appear in this order in the input.
nums109253710118length 11092length 25after 23after 2length 37after 3length 4101after 718after 7one increasing subsequence7187 came after 3 → follow the link
read back7, 18
Printing the subsequence. The pile tops alone can mix numbers from different subsequences, so they are not always a real answer. Each card, though, recorded the card it was placed after. Following those links from the last pile gives numbers that really appear in this order in the input.
nums109253710118length 11092length 25after 23after 2length 37after 3length 4101after 718after 7one increasing subsequence37183 came after 2 → follow the link
read back3, 7, 18
Printing the subsequence. The pile tops alone can mix numbers from different subsequences, so they are not always a real answer. Each card, though, recorded the card it was placed after. Following those links from the last pile gives numbers that really appear in this order in the input.
nums109253710118length 11092length 25after 23after 2length 37after 3length 4101after 718after 7one increasing subsequence237182 has no link → the subsequence starts here
read back2, 3, 7, 18
Printing the subsequence. The pile tops alone can mix numbers from different subsequences, so they are not always a real answer. Each card, though, recorded the card it was placed after. Following those links from the last pile gives numbers that really appear in this order in the input.
nums109253710118length 11092length 25after 23after 2length 37after 3length 4101after 718after 7one increasing subsequence23718answer: 4 piles, for example 2, 3, 7, 18
answer4number of piles
pile tops2, 3, 7, 18
Answer 4. The number of piles is the length of the longest increasing subsequence. Here the pile tops happen to form a valid answer too.
05

DP over earlier elements

dp[i] starts at 1 (the element alone). For every earlier j with nums[j] < nums[i], the chain ending at j can be extended by nums[i], so dp[i] takes the best dp[j] + 1. The answer is the largest value anywhere in dp, because the longest chain can end at any index.

▶1from typing import List
▶2 
▶3 
▶4class Solution:
▶5 def lengthOfLIS(self, nums: List[int]) -> int:
▶6 dp = [1] * len(nums)
▶7 for i in range(len(nums)):
▶8 for j in range(i):
▶9 if nums[j] < nums[i]:
▶10 dp[i] = max(dp[i], dp[j] + 1)
▶11 return max(dp)
06

Common pitfalls

Using bisect_right

✗ Wrong
k = bisect_right(tails, x)
✓ Right
k = bisect_left(tails, x)

bisect_right puts an equal value after its twin, so [7, 7, 7] grows to 3. Equal numbers are not strictly increasing; bisect_left makes the second 7 replace the first and the answer stays 1.

Returning tails as the subsequence

✗ Wrong
return tails
✓ Right
return len(tails)

On [3, 4, 1] the list ends as [1, 4], but 1 comes after 4 in the input, so that is not a subsequence at all. Only the length is guaranteed.

Returning the last DP value in the O(n²) version

✗ Wrong
return dp[-1]
✓ Right
return max(dp)

dp[i] is the best chain ending at i. On [1, 2, 0] the last value is 1, but the answer is 2 from [1, 2].

07

Complexity

Time
O(n log n)
Space
O(n)
One binary search over at most n tails per element. The DP version is O(n²) time and O(n) space.
08

Longest Increasing Subsequence FAQ

How do I get the actual numbers, not just the length?

Store, next to each number, the index of the number it was placed after: the current last entry of the length one shorter. When you finish, start from the last entry of the longest length and follow those links backwards, then reverse. The demo above does exactly this. In the O(n²) DP the same idea works with a parent[i] = j array saved whenever dp[i] improves.

Why is this called patience sorting?

It mirrors the card game: deal each card onto the leftmost pile whose top is not smaller, or start a new pile. The tops of the piles are exactly the tails list, and the number of piles is the answer. The idea was studied as a way to sort a deck, which is where the name comes from.

How do I find the longest non-decreasing subsequence instead?

Swap bisect_left for bisect_right. Then a value equal to a tail goes after it and can extend the chain, so [7, 7, 7] gives 3.