Skip to content

    Longest Increasing Subsequence

    DSA · Advanced

    Definition

    LIS is the longest subsequence with strictly increasing values.

    Shows how binary search speeds up DP to O(n log n).

    Diagram

    10 9 2 5 3 7 101 18tails: 2 3 7 18LIS = 4

    Flowchart

    Keep tails arrayFor each x, binary search positionReplace or appendLength of tails = LIS

    Example: Patience sorting

    from bisect import bisect_left
    tails = []
    for x in [10, 9, 2, 5, 3, 7, 101, 18]:
        i = bisect_left(tails, x)
        if i == len(tails): tails.append(x)
        else: tails[i] = x
    print(len(tails))

    Output: 4

    Complexity

    O(n log n)

    Key points

    • Simple DP is O(n²)
    • tails is not the actual sequence

    Interview questions

    Why replace in tails?

    A smaller tail keeps more room for future elements.

    More DSA topics