LeetCode: https://leetcode.com/problems/scramble-string/ Difficulty: Medium
Solve this dynamic-programming problem efficiently.
function solve(n) {
// Recursive with exponential time
function helper(remaining) {
if (remaining === 0) return 1;
if (remaining < 0) return 0;
let count = 0;
for (const choice of choices) {
count += helper(remaining - choice);
}
return count;
}
return helper(n);
}⏱️ Time: O(n²) or O(n³)
💾 Space: O(n)
function solve(n) {
// DP with memoization/tabulation
const dp = new Array(n + 1).fill(0);
dp[0] = 1;
for (let i = 1; i <= n; i++) {
for (const choice of choices) {
if (i >= choice) {
dp[i] += dp[i - choice];
}
}
}
return dp[n];
}⏱️ Time: O(n) or O(n log n)
💾 Space: O(n) or O(1)
DP Table:
0 1 2 3 4 5
┌──┬──┬──┬──┬──┬──┐
│ 1│ 1│ 2│ 3│ 5│ 8│
└──┴──┴──┴──┴──┴──┘
↑ ↑
dp[i-1] + dp[i-2] = dp[i]
Visit LeetCode for full problem description.