Problem Statement

Longest Increasing Subsequence

You are given a list of numbers called nums. A subsequence is what you get by deleting some numbers from the list (maybe none) without changing the order of the ones that are left. We want the longest subsequence whose numbers go strictly up, meaning each next number is bigger than the one before it. Return how long that longest increasing run is. For example, from [10,9,2,5,3,7,101,18] you can pull out [2,3,7,101], which has 4 numbers all going up, so the answer is 4.

mediumDynamic ProgrammingDynamic ProgrammingTime: 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.

Trace it on nums=[10,9,2,5,3,7,101,18]

start: tails=[]
num=10 -> pos=0==len, append -> tails=[10]
num=9  -> pos=0<len, replace -> tails=[9]
num=2  -> pos=0<len, replace -> tails=[2]
num=5  -> pos=1==len, append -> tails=[2,5]; num=3 -> pos=1<len, replace -> tails=[2,3]
num=7  -> pos=2==len, append -> tails=[2,3,7]
num=101-> pos=3==len, append -> tails=[2,3,7,101]; num=18 -> pos=3<len, replace -> tails=[2,3,7,18]
return len(tails)=4

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.

Shape of the loop

tails = []
for num in nums:
    pos = lower_bound(tails, num)   # first index with tails[pos] >= num
    if pos == len(tails): tails.append(num)
    else: tails[pos] = num
return len(tails)

Pseudocode only — the full worked solution lives in the Solution tab.

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