Skip to the solution
MediumDSA10 min read

How do you find the longest increasing subsequence?

269 views

The problem

Question presented to candidate: "Given an array of integers, return the length of its longest strictly increasing subsequence. Start with whatever works, then make it faster, and tell me how you would return the subsequence itself. Please code it in Python."

What a strong answer should cover:

  • The O(n²) DP: dp[i] = LIS length ending at i, dp[i] = 1 + max(dp[j]) over earlier smaller nums[j], answer = max(dp) (not dp[-1]).
  • The O(n log n) idea: tails[k] = smallest possible tail of an increasing subsequence of length k + 1; tails stays sorted, so each number is placed with one binary search.
  • That tails is not itself an LIS, and how parent pointers rebuild a real one.
  • Strict vs non-decreasing: bisect_left vs bisect_right.
  • Python details: the bisect module, max(dp) raising ValueError on an empty list, and why the O(n²) double loop is slow in pure Python for n in the tens of thousands.

Clarifying questions expected:

  • Strictly increasing or non-decreasing?
  • Length only, or the subsequence too?
  • How large can n be?

Code / implementation expected: Yes — the O(n log n) tails solution with bisect_left in Python; the O(n²) DP is a good first step to mention or write.

  • dp
  • subsequence

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

10 min read · 11 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonLIS by O(n^2) DP and by the O(n log n) tails array, with the subsequence rebuilt
PythonComparisons vs binary-search steps, strict vs non-decreasing

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 107 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextMedium

How do you solve the Jump Game?

Continue