Longest Increasing Subsequence: Patience Sorting

Find the longest strictly increasing subsequence in O(n log n) time using patience sorting and binary search techniques.

published: reading time: 16 min read author: Geek Workbench updated: November 22, 2026
Quick Summary

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 tails method tracks length, not the number of ways
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

  1. Confusing bisect_left and bisect_right — Use bisect_left for strict LIS and bisect_right when equal values may extend the sequence
  2. Not handling empty input — LIS of empty array is 0
  3. Treating tails as a subsequence — It stores best ending values, which may come from input positions in a different order; use parent indices to reconstruct one answer
  4. 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_left finds the first >= tail for strict LIS; bisect_right finds the first > tail for non-decreasing LIS
  • len(tails) at end = LIS length
  • tails stores 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

1. Why does the tails array always stay sorted?

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.

2. How does LIS relate to patience sorting?

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.

3. Can you find LIS in O(n log n) for 2D problems like Russian Doll Envelopes?

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.

4. What is the difference between LIS and Longest Common Subsequence (LCS)?

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.

5. How would you find the Longest Decreasing Subsequence (LDS)?

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.

6. How does the O(n²) DP solution for LIS work?

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
7. What is the space complexity of the O(n log n) LIS algorithm?

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.

8. How would you find the number of longest increasing subsequences (LeetCode 673)?

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]: update length[i] = length[j] + 1, count[i] = count[j]
  • If length[j] + 1 == length[i]: add count[j] to count[i]

Sum counts for all indices with maximum length. For O(n log n), use a Fenwick tree over coordinate-compressed values.

9. What happens when the input has duplicate elements in the LIS algorithm?

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.

10. Can LIS be solved using segment trees or Fenwick trees?

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.

11. Walk through a complete example of the binary search step-by-step on tails array.

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.

12. How do you handle LIS when dealing with a circular array or cyclic behavior?

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.

13. How would you reconstruct the actual LIS subsequence from the O(n log n) algorithm?

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.

14. What edge cases should you test for a production LIS implementation?

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.

15. What is the connection between LIS and Dilworth's Decomposition Theorem?

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.

16. When would you choose O(n²) DP over O(n log n) patience sorting for LIS?

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.

17. How does patience sorting compare to a Fenwick tree for the O(n log n) LIS approach?

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.

18. How would you adapt LIS for a streaming scenario where elements arrive one at a time?

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.

19. What happens to LIS when the problem asks for the minimum number of deletions to make the array strictly increasing?

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.

20. How do you modify LIS to handle the "minimum number of non-increasing subsequences" partition problem?

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

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.

#dynamic-programming #dp #1d-dp

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.

#dynamic-programming #dp #2d-dp

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.

#dynamic-programming #tree-dp #graph-dp