Skip to content
mlmentorship

Longest Increasing Subsequence

Keep the smallest ending value for each achieved length, then recover a witness only when the task requires one.

Published · 18 min read ·Core ·Mixed

ML breadth · active recall

Practice before you read

8 minutes. Explain the mechanism, why it works, when it fails, and one alternative.

ML breadth · closed-book attempt

Longest Increasing Subsequence

Explain the mechanism, why it works, when it fails, and one alternative.

Problem

Input. A list nums of integers, possibly empty or containing repeated values. Output. Return the length of the longest strictly increasing subsequence, not its values or indices. Rules. A subsequence can skip positions but must preserve their original order. Every selected value must be strictly greater than the preceding selected value; equality does not extend it. Leave the list unchanged. Empty input returns zero. Example. [10, 9, 2, 5, 3, 7, 101, 18] returns 4, witnessed by [2, 3, 7, 18]. For [2, 2, 2], return 1 rather than 3.

08:00recommended time

Closing or reloading clears the scratchpad. Only score, weak rubric dimensions, attempt count, and retry date can be stored locally.

30-second answer map

For every achievable length, retain the smallest ending value found so far.

Problem trace

A smaller tail preserves length while leaving more room to extend

Input and goalFind the longest strictly increasing subsequence. Values do not need to be next to each other.
Initialize empty tailsBefore reading nums, smallest_end is empty; the first bisect position is slot 0.
10i=09253710118-j=0-------
examplenums = [10, 9, 2, 5, 3, 7, 101, 18]rowAxistop = nums; bottom = smallest_end slots for lengths 1..8nextValue10tails[]operationstart
i
(0, 0)
j
(1, 0)
example
nums = [10, 9, 2, 5, 3, 7, 101, 18]

Recognize it
The problem asks only for the length of a strictly increasing subsequence in a long array, suggesting O(n log n) tail compression rather than quadratic pair DP.
Keep true
After each input prefix, smallest_end[k] is the minimum possible tail of any increasing subsequence of length k+1 in that prefix, and the tail array is increasing.
Reuse it
Keep the most permissive representative for every achieved progress level; the same dominance idea prunes states in scheduling, envelopes, and frontier DP.
Before reading nums, smallest_end is empty; the first bisect position is slot 0. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why does replacing 5 with 3 preserve length two? Why is the tail array not generally a recovered subsequence?
Full interview answer 18 min read

Find the longest strictly increasing sequence that can be selected without changing the input order.

Problem

Input. A list nums of integers, possibly empty or containing repeated values.

Output. Return the length of the longest strictly increasing subsequence, not its values or indices.

Rules. A subsequence can skip positions but must preserve their original order. Every selected value must be strictly greater than the preceding selected value; equality does not extend it. Leave the list unchanged. Empty input returns zero.

Example. [10, 9, 2, 5, 3, 7, 101, 18] returns 4, witnessed by [2, 3, 7, 18]. For [2, 2, 2], return 1 rather than 3.

Picture

The upper row stays in input order. Lower slot j represents length j + 1, not an input position.

Problem trace

Separate short stream: minimal tails are bounds, not necessarily a witness

Worked example: a smaller tail preserves length but is not the saved subsequenceProcessing (3,5,7,2) changes the length-one tail to 2. Tails (2,5,7) are extension bounds, not a subsequence of that processed input.Extension bounds can point backwardin source time3index 05index 17index 22index 3Updated tails: one bound for eachachievable length2index 35index 17index 2Two at index three cannot come beforefive at index one. The actual witnessis still 3,5,7.
Read it this way: Processing (3,5,7,2) changes the length-one tail to 2. Tails (2,5,7) are extension bounds, not a subsequence of that processed input. Why can tail two at input index three not precede tail five at input index one in an actual subsequence?
Reference drawing

Problem trace

A smaller tail preserves length while leaving more room to extend

Worked example: a smaller tail preserves length but is not the saved subsequenceProcessing (3,5,7,2) changes the length-one tail to 2. Tails (2,5,7) are extension bounds, not a subsequence of that processed input.Extension bounds can point backwardin source time3index 05index 17index 22index 3Updated tails: one bound for eachachievable length2index 35index 17index 2Two at index three cannot come beforefive at index one. The actual witnessis still 3,5,7.
Execution trace
Input and goalFind the longest strictly increasing subsequence. Values do not need to be next to each other.
Initialize empty tailsBefore reading nums, smallest_end is empty; the first bisect position is slot 0.
10i=09253710118-j=0-------
examplenums = [10, 9, 2, 5, 3, 7, 101, 18]rowAxistop = nums; bottom = smallest_end slots for lengths 1..8nextValue10tails[]operationstart
i
(0, 0)
j
(1, 0)
example
nums = [10, 9, 2, 5, 3, 7, 101, 18]

Recognize it
The problem asks only for the length of a strictly increasing subsequence in a long array, suggesting O(n log n) tail compression rather than quadratic pair DP.
Keep true
After each input prefix, smallest_end[k] is the minimum possible tail of any increasing subsequence of length k+1 in that prefix, and the tail array is increasing.
Reuse it
Keep the most permissive representative for every achieved progress level; the same dominance idea prunes states in scheduling, envelopes, and frontier DP.
Before reading nums, smallest_end is empty; the first bisect position is slot 0. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why does replacing 5 with 3 preserve length two? Why is the tail array not generally a recovered subsequence?
Read it this way: Processing (3,5,7,2) changes the length-one tail to 2. Tails (2,5,7) are extension bounds, not a subsequence of that processed input. Why can tail two at input index three not precede tail five at input index one in an actual subsequence?

Code

smallest_end[j] is the minimum ending value among length-j + 1 subsequences found in the processed prefix.

bisect_left finds the first tail at least num. Replace that tail, or append when every tail is smaller. Equal values replace rather than extend, because the required order is strict.

from bisect import bisect_left

def length_of_lis(nums: list[int]) -> int:
   smallest_end: list[int] = []
   for num in nums:
      index = bisect_left(smallest_end, num)
      if index == len(smallest_end):
         smallest_end.append(num)
      else:
         smallest_end[index] = num
   return len(smallest_end)

Why Replacement Works

A smaller tail dominates only at the same length. Every future value that extends the larger tail also extends the smaller one.

Every tail before index is smaller than num, so the preceding length can extend legally.

No longer predecessor can end below num, because its minimum tail is already at least num.

Replacement lowers one representative without losing any achieved length. The tails remain strictly increasing, so binary search remains valid.

Tails Are Not Necessarily a Witness

For the pictured input, [2,3,7,18] happens to be a subsequence. That coincidence is not the invariant.

Input [3,5,6,2,4] ends with these representatives:

Achieved length123
Minimum tail246
Original index342

Indices 3,4,2 go backward, so the tails do not form one witness. [3,5,6] is a valid length-three witness.

Cost and Boundaries

For constant-cost comparisons, time is and auxiliary space is . More precisely, only the achieved lengths occupy tail slots.

Empty input returns zero. An all-equal nonempty input returns one. The input is not modified.

Recall: Why can a smaller tail replace another? Their achieved lengths must match; then the smaller tail allows every extension the larger one allowed.

Allow Equal Values

Choose this when: The requested subsequence may be nondecreasing.

Use bisect_right so an equal value can extend existing equal tails. The representative meaning changes from strictly increasing to nondecreasing.

from bisect import bisect_right

def length_nondecreasing(nums):
   tails = []
   for value in nums:
      slot = bisect_right(tails, value)
      if slot == len(tails):
         tails.append(value)
      else:
         tails[slot] = value
   return len(tails)

Three equal values have nondecreasing length three, but strict length one. Time and space have the same bounds as the reference.

Recover Original Indices

Choose this when: The answer must include an actual subsequence, not just its length.

Each representative stores its original input index. Before replacement, save the preceding length’s current representative as this new element’s predecessor.

Later replacements do not change those saved links. They point backward in input order and downward in value.

from bisect import bisect_left

def lis_witness_indices(nums):
   tails, tail_indices = [], []
   previous = [-1] * len(nums)
   for index, value in enumerate(nums):
      slot = bisect_left(tails, value)
      if slot:
         previous[index] = tail_indices[slot - 1]
      if slot == len(tails):
         tails.append(value)
         tail_indices.append(index)
      else:
         tails[slot], tail_indices[slot] = value, index
   result = []
   index = tail_indices[-1] if tail_indices else -1
   while index != -1:
      result.append(index)
      index = previous[index]
   return list(reversed(result))

For [3,5,6,2,4], this returns indices [0,1,2], certifying 3 < 5 < 6.

Empty input returns []. Ties may choose a different optimal witness; the function does not promise the earliest indices or lexicographically smallest values.

Time is . Predecessor storage and the returned witness use space. Neither adaptation modifies the input.

Transfer

This compression keeps one most-permissive representative per progress level. It does not discard longer progress just because a shorter state has a smaller value.

Changing the equality rule changes the binary-search boundary. Requiring a witness changes the retained evidence, not the minimum-tail length proof.