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

Medium · Target 15 minutes · Dynamic programming · Type asked atGoogleAmazonMicrosoft

Given a list of integers nums, return the length of its longest strictly increasing subsequence: elements taken in their original order, not necessarily adjacent, each larger than the one before.

Examples

InputOutputWhy
nums = [10,9,2,5,3,7,101,18]42, 3, 7, 18 (or 2, 5, 7, 101).
nums = [7,7,7]1Equal values do not count as increasing.
nums = [0,1,0,3,2,3]40, 1, 2, 3.

Constraints

  • 1 ≤ nums.length ≤ 2500
  • −10⁴ ≤ nums[i] ≤ 10⁴

Hints

Hint 1

Fix where the subsequence ends. Let end[i] be the longest increasing subsequence that ends exactly at i.

Hint 2

end[i] is 1, or 1 + end[j] for an earlier j with nums[j] < nums[i]: take the best.

Hint 3

The answer is the maximum of end[i] over all i, not end[n − 1].

Where people lose marks

  • Returning end[n − 1], which forces the subsequence to end at the last element.
  • Using ≤ instead of <, which counts non-decreasing runs.
  • Confusing subsequence with subarray: elements need not be adjacent.
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.