Debugging challengeIntermediate

LIS with the wrong state definition

Scenario

This function is supposed to return the length of the longest strictly increasing subsequence. It returns 4 for [10, 9, 2, 5, 3, 7, 101, 18] (correct) but 5 for [3, 1, 2, 5, 4, 6] where the answer is 4 (1, 2, 4, 6 or 1, 2, 5, 6). Find the bug.

Broken
1def length_of_lis(nums):
2 n = len(nums)
3 if n == 0:
4 return 0
5 # dp[i] = length of the longest increasing subsequence within nums[:i+1]
6 dp = [1] * n
7 for i in range(1, n):
8 dp[i] = dp[i - 1]
9 for j in range(i):
10 if nums[j] < nums[i]:
11 dp[i] = max(dp[i], dp[j] + 1)
12 return dp[n - 1]

The corrected version appears here once you have revealed everything below.

Your task

  1. Read the comment above dp. Is the recurrence consistent with that definition? Is the answer extraction consistent with it?
  2. Trace [3, 1, 2, 5, 4, 6] and show where the value first becomes wrong.
  3. Decide which state definition you want — "best ending at i" or "best within prefix i" — and make the recurrence, the initialization and the answer extraction all agree.
  4. Write the corrected function and give its complexity. Mention the O(n log n) alternative.
DebuggingSystematic ReasoningEdge Cases

Work it out

Write your analysis before revealing anything. The self-check below compares it against what a strong answer contains.

Reveal

Progressive — each section builds on the previous one.

The bug
Why it happens
The fix
Edge cases
Complexity
What this tests

Self-check

Tick what your analysis covered. Be honest — this feeds your readiness profile.

0/6

Related concepts