Algorithms · Visualized
DP: Longest Increasing Subsequence
Dynamic Programming
Break problems into overlapping subproblems and store answers.
Finds the length of the longest subsequence (not necessarily contiguous) where elements are strictly increasing. Time: O(n²) with the straightforward DP approach average, O(n²) worst; space: O(n) — the dp array.
Big-O: The most-asked interview category — 35 classics here.
Longest Increasing Subsequence
Dynamic ProgrammingFinds the length of the longest subsequence (not necessarily contiguous) where elements are strictly increasing. dp[i] represents the length of the longest increasing subsequence ending exactly at index i, built by checking every earlier index that could extend into a longer increasing chain.
How Longest Increasing Subsequence Works
- Create a DP array of the same length as the input, initialized to 1 everywhere (every element is trivially an increasing subsequence of length 1 by itself).
- For each index i, look back at every earlier index j (from 0 to i-1).
- If the value at j is smaller than the value at i (meaning the sequence could increase from j to i), consider extending that subsequence: dp[i] could become dp[j] + 1.
- Set dp[i] to the maximum among all such valid extensions found (or leave it at 1 if no earlier element is smaller).
- After filling the whole dp array, the answer is the maximum value found anywhere in dp (not necessarily the last position, since the longest subsequence might end anywhere).
Longest Increasing Subsequence Worked Example
Input: [10, 9, 2, 5, 3, 7, 101, 18]
dp starts all 1s. dp[3](val5): looking back, val2(index2)<5 → dp[3]=dp[2]+1=2. dp[4](val3): val2<3 → dp[4]=dp[2]+1=2. dp[5](val7): val2,5,3 all <7 → best is dp[3]+1=3 → dp[5]=3. dp[6](val101): all previous values are smaller → best is dp[5]+1=4 → dp[6]=4. dp[7](val18): val2,5,3,7 are smaller → best is dp[5]+1=4 → dp[7]=4. Maximum value in dp array: 4 (subsequence like 2,5,7,101 or 2,3,7,18).
def lis(nums):
tails = []
for v in nums:
lo, hi = 0, len(tails)
while lo < hi:
mid = (lo + hi) // 2
if tails[mid] < v:
lo = mid + 1
else:
hi = mid
if lo == len(tails):
tails.append(v)
else:
tails[lo] = v
return len(tails)Behind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Longest Increasing Subsequence Time & Space Complexity
When to Use Longest Increasing Subsequence
- Stock trend analysis (longest run of increasing prices), version/dependency chain analysis, and patience sorting algorithms.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.