mediumDynamic ProgrammingDynamic Programming

Longest Increasing Subsequence

mediumTime: O(n log n)Space: O(n)

Signals to notice

longest increasing subsequencenot contiguousoptimal substructure with ordering

Brute force first

Generate all subsequences and check which are increasing. Exponential because every element is included or excluded. It is a fair place to begin because it matches the surface of the question, yet it does not capture the deeper structure that makes the problem simpler.

The key insight

Maintain a 'tails' array: tails[i] is the smallest tail element of all increasing subsequences of length i+1. For each element, binary search for its position in tails. Once you hold onto the right piece of information from moment to moment, the problem feels less like trial and error and more like following a shape that was there all along.

What must stay true

The tails array is always sorted. Each element either extends the longest subsequence (append) or replaces a larger tail (keeping the subsequence shorter but with more room to grow). When you keep that truth intact, each local choice supports the larger solution instead of fighting it.

Easy way to go wrong

The tails array does NOT contain the actual LIS — it tracks the best possible ending elements. The length of tails equals the LIS length. When the code becomes mechanical before the idea is clear, small edge cases start breaking the whole story.

Dynamic Programming Pattern