KatInterview

Longest Strictly Increasing Subsequence

Dynamic ProgrammingAuto-graded · 24 test cases
MediumAuto-gradedDynamic Programmingbinary-searchsubsequencesgreedy

Last updated

Tests understanding of dynamic programming optimization using binary search and greedy subsequence construction with the patience sorting technique.

You are given an array of integers. Your task is to compute the length of the longest subsequence where each element is strictly greater than the previous one.

A subsequence maintains the relative order of elements from the original array but does not need to be contiguous. "Strictly greater" means equal values do not count as increasing.

Constraints

  • 0 ≤ array length ≤ 2500
  • -10⁴ ≤ array elements ≤ 10⁴
  • An empty array has a longest increasing subsequence of length 0
  • If all elements are equal, the answer is 1 (a single element)

Examples

Example 1

Input: lis_length([10, 9, 2, 5, 3, 7, 101, 18])

Output: 4

Example 2

Input: lis_length([0, 1, 0, 3, 2, 3])

Output: 4

Example 3

Input: lis_length([7, 7, 7, 7, 7, 7, 7])

Output: 1

Example 4

Input: lis_length([3, 4, -1, 0, 6, 2, 3])

Output: 4

Hints

Hint 1

A dynamic programming approach with O(n²) time is straightforward but can be improved

Hint 2

Consider maintaining information about the smallest ending value for subsequences of each possible length

Hint 3

Binary search can help you efficiently find where to place each new element

Hint 4

The bisect_left function enforces strict inequality; bisect_right would allow non-decreasing sequences