Skip to content

Latest commit

 

History

History
70 lines (53 loc) · 1.35 KB

File metadata and controls

70 lines (53 loc) · 1.35 KB

Dynamic-programming Problem 38

LeetCode: https://leetcode.com/problems/scramble-string/ Difficulty: Medium

Problem

Solve this dynamic-programming problem efficiently.

Brute Force Approach

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)

Optimal Approach

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)

Visual Diagram

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.