Longest Increasing Subsequence

35 min · lengthOfLIS()

Daily temperatures can dip, repeat, and spike. Hidden inside that noisy record may be a much longer upward trend than any one continuous stretch suggests.

Given an integer array nums, return the length of its longest strictly increasing subsequence. A subsequence keeps elements in their original order while allowing you to skip any number of positions.

The increase must be strict: every chosen value must be greater than the chosen value before it. Equal values never extend the sequence.

Constraints

  • 1 <= nums.length <= 2_500
  • -10_000 <= nums[i] <= 10_000

Hints

End at one position

Suppose the subsequence must end at index i. Which earlier indices could sit immediately before it, and which earlier answer would you want to extend?

Write the DP state

Let dp[i] be the longest increasing subsequence ending exactly at i. Start it at 1, then inspect every j < i with nums[j] < nums[i].

Keep only useful tails

For each possible length, remember the smallest ending value found so far. A smaller tail leaves more room for future values, and binary search finds the tail to replace.

Follow-up

Can you reconstruct one longest increasing subsequence, not just report its length?

Visible cases

Examples

Example 1

ready
Input
nums = [
  10,
  9,
  2,
  5,
  3,
  7,
  101,
  18
]
Expected
4
Why
one longest choice is 2, 3, 7, 18

Example 2

ready
Input
nums = [
  0,
  1,
  0,
  3,
  2,
  3
]
Expected
4
Why
0, 1, 2, 3 keeps order while skipping positions

Example 3

ready
Input
nums = [
  7,
  7,
  7,
  7
]
Expected
1
Why
equal values don't count as a strict increase

Interview signal

Asked at

AmazonGoogleMicrosoft
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite