Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Dynamic programming

Longest increasing subsequence in O(n log n)

Medium · Target 25 minutes · Dynamic programming · Type asked atMicrosoftTwo Sigma

Given an array nums, return the length of its longest strictly increasing subsequence. A subsequence keeps the original order but may skip elements.

Examples

InputOutputWhy
nums = [10, 9, 2, 5, 3, 7, 101, 18]4For example 2, 3, 7, 18.
nums = [0, 1, 0, 3, 2, 3]40, 1, 2, 3.
nums = [7, 7, 7]1Strictly increasing: equal values do not count.

Constraints

  • 1 ≤ n ≤ 10⁵
  • −10⁹ ≤ nums[i] ≤ 10⁹

Hints

Hint 1

The quadratic solution: best[i] is the length of the longest increasing subsequence ending at i, the maximum of best[j] + 1 over earlier, smaller nums[j]. Interviewers ask for something faster.

Hint 2

Two increasing subsequences of the same length are not equally useful: the one ending on the smaller value can be extended by more future elements.

Hint 3

Keep tails[L] = the smallest value on which an increasing subsequence of length L + 1 ends. The tails are increasing, so each new value can be placed by binary search: it replaces the first tail that is at least as large, or extends the list.

Where people lose marks

  • Using an upper bound for a strictly increasing subsequence. Equal values would then extend the list: [7, 7, 7] would give 3 instead of 1.
  • Returning the tails array as the subsequence. Its length is right; its contents are not a subsequence of nums in general.
  • Thinking the replacement loses information. Overwriting a tail with a smaller value never shortens any achievable length; it only makes more futures possible.
  • Writing the binary search with an off-by-one on the end. Search over the whole current length, including the position just past the last tail.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.