Python coding

Longest rising subsequence

Return the length of the longest subsequence of nums whose values strictly rise from left to right. A subsequence keeps the values in their original order but may skip any of them: [1, 4, 5] is one of [3, 1, 4, 1, 5].

nums has 0 to 10,000 integers between −10⁹ and 10⁹, possibly repeated. Aim for O(n log n) time.

Besides the tests, one large input (5,000 values) with a ~200 ms limit (scaled to your device's speed): brute force won't pass.

  • longest_rising([3,1,4,1,5,9,2,6]) → 4
  • longest_rising([8,8,8,8]) → 1
  • longest_rising([6,2,7,3,4]) → 3
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Let best[i] be the longest rising subsequence that ends at index i: 1 + the largest best[j] over earlier j with a smaller value. Correct, but it compares every pair: O(n²).

Hint 2

Flip the state: tails[k] is the smallest value that ends a rising subsequence of length k + 1. It stays sorted, so a binary search finds where each value goes.

Hint 3

For each x, take k = bisect_left(tails, x): at the end, x extends the longest one; otherwise it replaces a larger end. bisect_left keeps it strict: an equal value replaces, never extends.

Solution and why it works
pythonO(n log n) · O(n)
from bisect import bisect_left

def longest_rising(nums: list[int]) -> int:
    tails = []                           # tails[k]: smallest value that ends a rising subsequence of length k + 1
    for x in nums:
        k = bisect_left(tails, x)        # the first end that is not below x
        if k == len(tails):
            tails.append(x)              # x extends the longest subsequence
        else:
            tails[k] = x                 # a smaller end for length k + 1
    return len(tails)

best[i], the longest rising subsequence ending at i, is the textbook DP, but each state scans every earlier one: O(n²). Keeping, per length, the smallest value that ends a subsequence that long gives a sorted list, tails, so each value binary-searches its slot: O(n log n). A smaller end is never worse: more later values can extend it. Two traps: tails is not a valid subsequence, only its length is the answer; and bisect_right would chain equal values ([1, 2, 2, 3] gives 4, not 3).

Related lab: Big-O growth