← Back to DSA
#300
Longest Increasing Subsequence
Longest Increasing Subsequence solution for LeetCode 300, with the key idea, complexity breakdown, and working code in Java, C++, JavaScript, TypeScript, C, Go, and Rust.
Solve on LeetCode ↗Longest Increasing Subsequence
Why it belongs on this sheet
This is a classic DP benchmark problem and a good way to practice subsequence-style transitions.
Pattern
Best LIS ending at each index
Approach
For each position, look at all earlier positions with smaller values and extend the best subsequence ending there. Track the largest value in the DP array.
Java solution
import java.util.Arrays;
class Solution {
public int lengthOfLIS(int[] nums) {
int[] dp = new int[nums.length];
Arrays.fill(dp, 1);
int best = 1;
for (int i = 0; i < nums.length; i++) {
for (int j = 0; j < i; j++) {
if (nums[j] < nums[i]) {
dp[i] = Math.max(dp[i], dp[j] + 1);
}
}
best = Math.max(best, dp[i]);
}
return best;
}
}
Complexity
- Time:
O(n^2) - Space:
O(n)
Interview note
The O(n log n) version is a strong follow-up, but the quadratic DP is often enough for a first pass.
Dynamic Programming
7 DP Patterns > 100 LeetCode Questions
Most DP questions are repeated ideas. Stop treating DP like chaos. Learn the 7 repeatable patterns that unlock most placement-level questions.
7 patternsProgress tracking
Read 7 patterns (5 min)