Longest Increasing Subsequence: Patience Sorting
Find the longest strictly increasing subsequence in O(n log n) time using patience sorting and binary search techniques.
The longest increasing subsequence (LIS) is the longest ordered selection of values that rise from left to right. Patience sorting finds its length in O(n log n), while parent indices can reconstruct one valid subsequence. Use bisect_left for strict LIS and bisect_right when equal values may extend the sequence; the article includes duplicate, decreasing, empty, and signed-value checks.
Longest Increasing Subsequence: Patience Sorting
The longest increasing subsequence (LIS) is the longest subsequence whose values rise from left to right. It may skip elements in the input. A dynamic-programming solution takes O(n²) time; patience sorting with binary search finds the length in O(n log n).
For each subsequence length, a tails array stores the smallest ending value seen so far. Binary search finds where each input value belongs. The array length gives the LIS length, but tails is not necessarily a subsequence from the input.
Introduction
The exact comparison depends on the problem statement. A strictly increasing subsequence requires each value to be greater than the last; a non-decreasing subsequence allows equal values.
LIS appears in problems such as nesting envelopes and finding a longest ordered subset of values. The patience-sorting method tracks one best tail value for each possible length, then uses binary search to update that state as it scans the input.
This guide covers the O(n log n) length algorithm, reconstruction with parent indices, and the O(n²) dynamic-programming alternative.
When to Use
LIS applies when:
- Box stacking problems — Stacking boxes where each has dimensions
- Maximum non-overlapping intervals — Finding largest subset of non-overlapping segments
- Hotel renovation planning — Maximum guests in hotel given check-in/check-out times
- Russian doll envelope problems — Nesting objects with multiple constraints
- Online judge problems with n up to 10⁵ — O(n²) too slow, need O(n log n)
When Not to Use
- When the input is small and the simpler O(n²) reconstruction is easier to review
- When you need to count all longest subsequences; the
tailsmethod tracks length, not the number of ways
Architecture: Patience Sorting + Binary Search
graph TD
A["Input: arr = [3,1,4,2,5]"] --> B[Initialize tails array]
B --> C[Process each element]
C --> D{Insert position?}
D -->|Binary search| E["Update tails[pos] = element"]
E --> F{"tails[pos] updated?"}
F -->|Yes| G[Length unchanged]
F -->|"No (append)"| H[Length increases]
G --> C
H --> C
C --> I["LIS length = len(tails)"]
For a strictly increasing subsequence, each element replaces the first tail that is greater than or equal to it. Smaller tail values leave more room for later elements to extend the sequence.
Strictly increasing vs. non-decreasing
Python’s bisect_left finds the first tail >= value. Equal values replace one another, so they do not extend a strictly increasing subsequence. Use bisect_right, which finds the first tail > value, when equal values may follow one another. For [2, 2, 2], the strict LIS length is 1; the non-decreasing length is 3.
Why tails is not the answer
For [2, 6, 3, 4, 1, 5], the final tails values are [1, 3, 4, 5]. That list is not a subsequence of the input: 1 appears after 3 and 4. To return an actual LIS, store predecessor indices while building tails and follow them backward.
Implementation
Strict LIS Length in O(n log n)
import bisect
def lis_length(nums):
"""
Find LIS length in O(n log n) time using patience sorting.
Returns the length of the longest increasing subsequence.
"""
if not nums:
return 0
tails = []
for num in nums:
# Find position where num should be inserted
pos = bisect.bisect_left(tails, num)
if pos == len(tails):
# num extends longest subsequence
tails.append(num)
else:
# num improves (smaller) tail for length pos+1
tails[pos] = num
return len(tails)
For a non-decreasing subsequence, use bisect_right so equal values can extend tails:
def lis_length_nondecreasing(nums):
tails = []
for num in nums:
pos = bisect.bisect_right(tails, num)
if pos == len(tails):
tails.append(num)
else:
tails[pos] = num
return len(tails)
Reconstruct One LIS
def lis_reconstruct(nums):
"""
Find actual LIS in O(n log n) time.
Returns one valid LIS (not necessarily unique).
"""
if not nums:
return []
# Phase 1: Track the best tail index for each length and each item's parent
tails = []
tail_indices = []
parent = [-1] * len(nums)
for i, num in enumerate(nums):
pos = bisect.bisect_left(tails, num)
if pos > 0:
parent[i] = tail_indices[pos - 1]
if pos == len(tails):
tails.append(num)
tail_indices.append(i)
else:
tails[pos] = num
tail_indices[pos] = i
# Phase 2: Follow parent indices from the last tail
index = tail_indices[-1]
lis = []
while index != -1:
lis.append(nums[index])
index = parent[index]
return lis[::-1]
Before replacing a tail at position pos, parent[i] records the earlier input index that ended the best subsequence of length pos. Following those links from the last tail index reconstructs one valid LIS, even when values are negative or repeated.
Boundary and reconstruction checks
These assertions cover empty input, duplicates, decreasing values, and signed values. The final checks verify that reconstruction returns an increasing subsequence from the input:
def is_subsequence(candidate, values):
remaining = iter(values)
return all(any(value == item for item in remaining) for value in candidate)
assert lis_length([]) == 0
assert lis_reconstruct([]) == []
assert lis_length([2, 2, 2]) == 1
assert lis_length_nondecreasing([2, 2, 2]) == 3
assert lis_length([5, 4, 3]) == 1
values = [-3, -1, -2, 0]
answer = lis_reconstruct(values)
assert len(answer) == 3
assert all(left < right for left, right in zip(answer, answer[1:]))
assert is_subsequence(answer, values)
O(n²) DP Approach (for reference)
def lis_length_dp(nums):
"""
O(n²) DP approach - easier to understand but slower.
dp[i] = LIS length ending at index i.
"""
if not nums:
return 0
n = len(nums)
dp = [1] * n
for i in range(1, n):
for j in range(i):
if nums[j] < nums[i]:
dp[i] = max(dp[i], dp[j] + 1)
return max(dp)
Production Failure Scenarios
| Failure | Cause | Mitigation |
|---|---|---|
| Wrong binary search variant | Using bisect_right instead of bisect_left for strict LIS |
Use bisect_left for strict and bisect_right for non-decreasing |
| Off-by-one in reconstruction | Mismatched index tracking | Test carefully with duplicate values |
| Strict vs non-strict confusion | “Increasing” vs “non-decreasing” | Clarify problem: strictly increasing (<) or non-decreasing (<=) |
| Negative numbers | Not handling negative input correctly | Algorithm works for any comparable elements |
Common Pitfalls / Anti-Patterns
- Confusing
bisect_leftandbisect_right— Usebisect_leftfor strict LIS andbisect_rightwhen equal values may extend the sequence - Not handling empty input — LIS of empty array is 0
- Treating
tailsas a subsequence — It stores best ending values, which may come from input positions in a different order; use parent indices to reconstruct one answer - Multiple valid LIS — Algorithm returns one valid LIS, not necessarily the lexicographically smallest
Trade-off Analysis
| Approach | Time Complexity | Space Complexity | Finds Length | Reconstructs LIS | Counts LIS |
|---|---|---|---|---|---|
| O(n²) DP | O(n²) | O(n) | Yes | Yes | Yes |
| O(n log n) Patience Sorting | O(n log n) | O(n) | Yes | With tracking | No |
| O(n log n) Fenwick Tree | O(n log n) | O(n) | Yes | Yes | Yes |
Choosing the Right Approach
- Use O(n²) DP when n is small and the direct reconstruction or extra constraints make it easier to review
- Use O(n log n) Patience Sorting when n is large; add parent indices if you need one actual subsequence
- Use O(n log n) Fenwick Tree when you need counts, full reconstruction, or coordinate compression is natural
Quick Recap Checklist
- tails[pos] = smallest ending value of length (pos+1) subsequence
-
bisect_leftfinds the first>=tail for strict LIS;bisect_rightfinds the first>tail for non-decreasing LIS - len(tails) at end = LIS length
-
tailsstores best ending values and may not itself be a subsequence - Store parent indices when reconstructing one actual subsequence
- Test with: all decreasing, all same, already increasing, single element
Interview Questions
By definition, tails[i] stores the minimum possible tail value for an
increasing subsequence of length i+1. When processing a new element,
we find its position using binary search—the smallest tail >= num.
Placing num there maintains the invariant since num
is <= previous value but extends a longer or equally-long subsequence.
In patience sorting, you place cards into piles following rules: place a card on the leftmost pile whose top card is >= the new card. The number of piles equals the LIS length. The tails array is exactly these pile top cards. This connection proves the algorithm works—the piles provide an ordering that captures increasing subsequences.
Yes. Sort envelopes by width ascending, then height descending for equal widths. This prevents counting envelopes with same width as both fit. Then find LIS on heights using O(n log n). The sorting ensures width constraint is satisfied while height LIS finds the maximum nesting depth.
LIS finds the longest subsequence within a single array where elements strictly increase. LCS finds the longest subsequence common to two sequences, preserving order but not necessarily increasing values. LCS can be reduced to LIS on a transformed array when one sequence has unique elements, but they solve different fundamental problems.
You can find LDS by negating all elements and applying the LIS algorithm, or by reversing the comparison direction. Alternatively, compute LIS on the reversed array. For strictly decreasing, use bisect_left on negated values; for non-increasing, use bisect_right on negated values.
The DP approach defines dp[i] as the length of the longest increasing subsequence ending at index i. Initialize all dp[i] = 1. For each i, check all j < i: if nums[j] < nums[i], update dp[i] = max(dp[i], dp[j] + 1). The answer is max(dp).
- Time: O(n²)
- Space: O(n)
- Advantage: Simple to implement and easy to modify for LIS reconstruction
The space complexity is O(n) in the worst case (when the array is already increasing, the tails array grows to size n). For reconstruction with backtracking, an additional O(n) array stores parent indices, keeping total space O(n). The algorithm uses no recursion stack beyond iteration.
Use an O(n²) DP with two arrays: length[i] for LIS length ending at i, and count[i] for number of LIS ending at i. For each pair (j, i), if nums[j] < nums[i]:
- If
length[j] + 1 > length[i]: updatelength[i] = length[j] + 1,count[i] = count[j] - If
length[j] + 1 == length[i]: addcount[j]tocount[i]
Sum counts for all indices with maximum length. For O(n log n), use a Fenwick tree over coordinate-compressed values.
For strictly increasing LIS: duplicates are not allowed in the subsequence. Using bisect_left ensures we replace the first tail >= num, so equal elements replace each other and a duplicate will never extend the LIS. For non-decreasing LIS (allow equals): use bisect_right so equal elements are placed after existing tails, allowing them to extend the sequence.
Yes. Coordinate-compress the values, then process left to right. For each value, query the maximum LIS length among values less than it (range max query), add 1, and update the Fenwick or segment tree at the current value's position. This achieves O(n log n) and naturally extends to counting the number of LIS and 2D problems like Russian Doll Envelopes with multiple constraints.
Take nums = [3, 1, 4, 2, 5]:
- 3: tails=[], pos=0, len=0, append → tails=[3]
- 1: bisect_left([3],1)=0, replace → tails=[1]
- 4: bisect_left([1],4)=1, append → tails=[1,4]
- 2: bisect_left([1,4],2)=1, replace → tails=[1,2]
- 5: bisect_left([1,2],5)=2, append → tails=[1,2,5]
bisect_left finds the first tail >= num. Replacing that tail with a smaller value keeps the door open for future elements to extend further. The invariant holds: tails[i] is always the minimum possible tail for any increasing subsequence of length i+1.
Two approaches work. When the problem guarantees the LIS starts before it ends, duplicate the array and run LIS on each suffix. For harder cases, use DP: compute the longest chain reaching each position from every starting point, then take the maximum. A concrete example: if you need the max points you can hit on a circle, convert positions to angles, sort them, then run LIS on the sorted angles.
Maintain tails, the input index for each tail, and a parent index for each input element. When an element lands at position pos, its parent is the current tail index at pos - 1, if that position exists. After scanning, follow parent links from the last tail index and reverse the collected values. This returns one LIS in O(n log n) time and O(n) space. It may be one of several valid answers.
Cover empty input (length 0), one element (length 1), increasing input (length n), decreasing input (strict length 1), repeated values (strict length 1, non-decreasing length n), and negative values. Reconstruction tests should also check that the result is increasing and appears in the original input in the same order.
Dilworth's theorem says any partially ordered set has the size of its largest antichain equal to the minimum chain count needed to partition it. Applied to LIS: the longest increasing subsequence length equals the minimum number of decreasing subsequences covering the array. Patience sorting builds exactly this decomposition—each pile is a decreasing subsequence. This is why the algorithm works, not just that it works.
Use O(n²) DP when the input is small, when custom constraints make the direct recurrence easier to review, or when you need a simple way to count LIS. Patience sorting can also reconstruct one LIS in O(n log n) time by storing parent indices. Counting the number of LIS needs additional state, such as a Fenwick tree.
Patience sorting binary-searches a simple array—cache-friendly for sequential access, low constant factor. A Fenwick tree needs coordinate compression and handles "max DP value for all values less than x" queries more naturally. Fenwick trees win when you need counting, range minimum queries, or 2D LIS. Patience sorting wins for simplicity and speed when you only need length.
Process each element as it arrives: binary search its position in the tails array and update. To reconstruct the subsequence later, also track predecessor indices. Memory usage is O(n) for the element history; update time is O(log n) per element. This works well in real-time systems where you need LIS length as data flows in.
Answer: n minus the LIS length. You can only keep elements that form an increasing subsequence, so the max you can keep is the LIS. The problem of "minimum deletions to make it increasing" reduces directly to LIS—you don't need a separate deletion algorithm.
Dilworth's theorem says the answer equals the LIS length. Run LIS on the original array—that's your partition count. To actually partition, use the greedy patience sorting approach: for each element, place it on the leftmost pile where it fits (non-increasing means each element <= pile tail). The pile count matches the LIS length.
Further Reading
- Dynamic Programming: States and Transitions — Learn how to design DP states for LIS-like problems
- Russian Doll Envelopes (LeetCode 354) — Classic 2D LIS application
- Number of Longest Increasing Subsequence (LeetCode 673) — Count distinct LIS using Fenwick tree
- Patience Sorting on Wikipedia — Detailed explanation of the card game analogy
- Longest Increasing Subsequence on CP-Algorithms — Comprehensive algorithmic treatment
- Minimum Number of Operations to Make Array Increasing (LeetCode 1964) — Variation requiring LIS thinking
Conclusion
For strict LIS, tails[i] holds the smallest ending value found for a subsequence of length i + 1; use bisect_left. Use bisect_right when equal values may extend the sequence. tails gives the length, while parent indices recover one actual subsequence. For more on the dynamic-programming approach, see Dynamic Programming: States and Transitions.
Category
Related Posts
1D Dynamic Programming Problems: Classic Patterns
Learn to solve common 1D dynamic programming problems including climbing stairs, house robber, and coin change with optimized space solutions.
2D Dynamic Programming: Matrix Chain and Beyond
Master 2D DP problems with two state variables for string manipulation, matrix chain multiplication, and optimal game strategies.
DP on Trees and Graphs: Tree DP and Graph DP
Apply dynamic programming to tree and graph structures using DFS-based state propagation for optimal subtree and path calculations.