Notes
All notes

1-D Dynamic Programming (LeetCode #13)

Dynamic programming (DP) is what you reach for when a recursive solution recomputes the same subproblem. Instead of solving it again, you remember the answer. The 1-D variety is the friendliest: the state is a single index or amount, and dp[i] depends on a few earlier states. This post covers all 12 NeetCode 1-D DP problems.

The technique

The four-step recipe.

  1. Define the state — what does dp[i] mean? (e.g. “fewest coins to make amount i”.)
  2. Write the recurrence — how does dp[i] follow from smaller states?
  3. Set base cases — the answers you know directly.
  4. Fill in order — dependencies first; shrink to variables if only the last one or two are needed.
dp = [base] * (n + 1)
for i in range(1, n + 1):
    dp[i] = combine(dp[i-1], dp[i-2], ...)
return dp[n]

Memoization (top-down) and tabulation (bottom-up) have the same complexity; tabulation is usually faster and enables the space trick.

Climbing Stairs

The question. Climb n steps, taking 1 or 2 at a time; count the ways.

The idea. To land on step i you came from i-1 or i-2:

\[ dp[i] = dp[i-1] + dp[i-2], \quad dp[0] = dp[1] = 1 \]

def climb_stairs(n):
    a, b = 1, 1
    for _ in range(n):
        a, b = b, a + b
    return a

\(O(n)\) time, \(O(1)\) space.

Min Cost Climbing Stairs

The question. cost[i] is the cost to step off stair i. Start at stair 0 or 1; find the minimum cost to reach the top (past the last stair).

Input:  [10,15,20]  -> 15      (start at 1)

The idea. dp[i] is the min cost to reach stair i. You can arrive from i-1 or i-2, paying the cost of the stair you step from:

\[ dp[i] = \min(dp[i-1] + cost[i-1],\ dp[i-2] + cost[i-2]) \]

Walk it through on [10,15,20]: dp[0]=0, dp[1]=0 (free start), dp[2]=min(0+15, 0+10)=10, dp[3]=min(10+20, 0+15)=15.

def min_cost_climbing_stairs(cost):
    prev, curr = 0, 0
    for i in range(2, len(cost) + 1):
        prev, curr = curr, min(curr + cost[i-1], prev + cost[i-2])
    return curr

\(O(n)\) time, \(O(1)\) space.

House Robber

The question. No two adjacent houses; maximise the take.

\[ dp[i] = \max(dp[i-1],\ dp[i-2] + nums[i]) \]

def rob(nums):
    prev, curr = 0, 0
    for x in nums:
        prev, curr = curr, max(curr, prev + x)
    return curr

\(O(n)\) time, \(O(1)\) space.

House Robber II

The question. Same as House Robber, but the houses form a circle (first and last are adjacent).

The idea. If the houses form a circle, either the first or the last is robbed, but not both. Solve House Robber twice: once on nums[:-1] (excluding the last) and once on nums[1:] (excluding the first), and take the maximum.

Walk it through on [2,3,2]: rob([2,3]) = 3, rob([3,2]) = 3 → 3.

def rob_ii(nums):
    if len(nums) == 1:
        return nums[0]
    return max(rob(nums[:-1]), rob(nums[1:]))

\(O(n)\) time, \(O(1)\) space.

Longest Palindromic Substring

The question. Return the longest contiguous palindrome in a string.

Input:  "babad"  -> "bab"  (or "aba")

The idea — expand around centers. A palindrome mirrors around a center, which is either a single character (odd length) or the gap between two characters (even). For each of the 2n-1 centers, expand while the characters match, and keep the longest.

Walk it through on "babad": center at index 1 (a) expands to bab; center at 2 (b) expands to nothing longer; the best is bab.

def longest_palindrome(s):
    best = ""
    def expand(l, r):
        while l >= 0 and r < len(s) and s[l] == s[r]:
            l -= 1; r += 1
        return s[l+1:r]
    for i in range(len(s)):
        best = max(best, expand(i, i), expand(i, i+1), key=len)
    return best

\(O(n^2)\) time, \(O(1)\) space.

Palindromic Substrings

The question. Count how many substrings are palindromes.

The idea. The same expand-around-centers, counting every successful expansion — including the odd and even centers.

Walk it through on s = "aaa" (answer 6: a,a,a,aa,aa,aaa). Each center contributes one count per palindrome found:

center expansions that match new count
(0,0) odd a 1
(0,1) even aa 2
(1,1) odd a, then aaa 4
(1,2) even aa 5
(2,2) odd a 6
(2,3) even none (r out of range) 6

Only when both runs keep going does the count grow again, so the dead aa-center (2,3) costs nothing.

def count_substrings(s):
    count = 0
    def expand(l, r):
        nonlocal count
        while l >= 0 and r < len(s) and s[l] == s[r]:
            count += 1; l -= 1; r += 1
    for i in range(len(s)):
        expand(i, i)        # odd
        expand(i, i + 1)    # even
    return count

Why only odd/even centers. Every palindrome has a center that is either one character (odd length) or the gap between two characters (even length); expanding from all \(2n-1\) centers covers every possibility exactly once.

Complexity. \(O(n^2)\) time (each center expands at most \(O(n)\)), \(O(1)\) space.

Edge cases. Empty string → 0. All identical characters → the triangular number \(n(n+1)/2\).

Decode Ways

The question. A string of digits maps to letters (1=A, …, 26=Z). Count the number of ways to decode it.

Input:  "226"  -> 3      (2-2-6, 22-6, 2-26)

The idea. dp[i] = ways to decode the first i characters. The last character can be a single digit (if nonzero), or the last two can form a valid number (10–26).

Walk it through on "226": dp[0]=1; dp[1]=1 (“2”); dp[2]=2 (“2”+“2” or “22”); dp[3]=3 (2+2+6, 22+6, 2+26).

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  n/.style={draw, thick, rounded corners=2pt, minimum width=0.8cm, font=\scriptsize\ttfamily, inner sep=2pt}]
  \node[n, fill=blue!8] (r) at (0,0) {"226"};
  \node[n, fill=blue!8] (a) at (-1.3,-0.9) {"2"|"26"};
  \node[n, fill=blue!8] (b) at (1.3,-0.9) {"22"|"6"};
  \draw[->, thick] (r) -- (a) node[font=\tiny\ttfamily, midway, left] {1 digit};
  \draw[->, thick] (r) -- (b) node[font=\tiny\ttfamily, midway, right] {2 digits};
  \node[font=\rmfamily\small, text=black!60, anchor=north] at (0,-1.4) {take 1 or (if <=26) 2 digits};
\end{tikzpicture}
def num_decodings(s):
    if not s:
        return 0
    prev, curr = 1, 0 if s[0] == "0" else 1
    for i in range(1, len(s)):
        one = curr if s[i] != "0" else 0
        two = prev if 10 <= int(s[i-1:i+1]) <= 26 else 0
        prev, curr = curr, one + two
    return curr

\(O(n)\) time, \(O(1)\) space.

Coin Change

The question. Fewest coins to make amount, or -1.

\[ dp[a] = 1 + \min_{\text{coin} \le a} dp[a - \text{coin}] \]

def coin_change(coins, amount):
    INF = float("inf")
    dp = [0] + [INF] * amount
    for a in range(1, amount + 1):
        for coin in coins:
            if coin <= a:
                dp[a] = min(dp[a], dp[a - coin] + 1)
    return dp[amount] if dp[amount] < INF else -1

\(O(\text{amount} \times \text{coins})\) time. The upward inner loop makes it the unbounded variant (coins may repeat).

Maximum Product Subarray

The question. Return the largest product of any contiguous subarray.

Input:  [2,3,-2,4]  -> 6      ([2,3])

Why the sum trick fails. With sums you keep the running max; with products, a negative × negative can become the largest. So track both the running maximum and minimum product ending at each position, because the minimum (very negative) can flip to the maximum when multiplied by a negative.

Walk it through on [2,3,-2,4]: at each step maintain (max, min) ending here. After -2: max -2, min -12. Then ×4: candidates 4, -8, -48; max 4, min -48. Overall best 6.

def max_product(nums):
    best = nums[0]
    cur_max = cur_min = nums[0]
    for x in nums[1:]:
        if x < 0:
            cur_max, cur_min = cur_min, cur_max   # negative flips them
        cur_max = max(x, cur_max * x)
        cur_min = min(x, cur_min * x)
        best = max(best, cur_max)
    return best

\(O(n)\) time, \(O(1)\) space.

Word Break

The question. Can s be split into dictionary words?

\[ dp[i] = \bigvee_{j<i} \big(dp[j] \land s[j{:}i] \in \text{dict}\big) \]

def word_break(s, word_dict):
    words = set(word_dict)
    dp = [False] * (len(s) + 1)
    dp[0] = True
    for i in range(1, len(s) + 1):
        for j in range(i):
            if dp[j] and s[j:i] in words:
                dp[i] = True; break
    return dp[-1]

\(O(n^2)\) time.

Longest Increasing Subsequence

The question. Length of the longest strictly increasing subsequence.

The idea (fast version). Keep a tails array where tails[k] is the smallest tail of an increasing subsequence of length k+1. Binary-search where each number goes: replace the first tail ≥ it, or append.

import bisect

def lis(nums):
    tails = []
    for x in nums:
        i = bisect.bisect_left(tails, x)
        if i == len(tails): tails.append(x)
        else: tails[i] = x
    return len(tails)

\(O(n \log n)\) time, \(O(n)\) space.

Partition Equal Subset Sum

The question. Can the array be split into two subsets with equal sums?

Input:  [1,5,11,5]  -> True      (1+5+5 = 11)

The idea. Equal halves means each sums to total / 2. So ask: is there a subset summing to target = total / 2? That is the 0/1 knapsack in disguise. dp[t] = “can we reach sum t?”; for each number, iterate t downward so each number is used once.

Walk it through on [1,5,11,5], target 11: reachable sums include 11 (the single element) → True.

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  c/.style={draw, thick, circle, minimum size=0.55cm, font=\scriptsize\ttfamily, inner sep=0pt}]
  \foreach \v [count=\i from 0] in {0,1,5,6,11} { \node[c, fill=blue!8] at (\i*0.85,0) {\v}; }
  \draw[->, thick] (0,0.28) -- (0.85,0.28);
  \draw[->, thick] (0.85,0.28) to[bend left=20] (1.7,0.28);
  \draw[->, thick, green!55!black] (0,-0.28) to[bend right=25] (3.4,-0.28);
  \node[font=\scriptsize\ttfamily, text=green!45!black, anchor=north] at (1.7,-0.55) {11 alone reaches target};
\end{tikzpicture}
def can_partition(nums):
    total = sum(nums)
    if total % 2:
        return False
    target = total // 2
    dp = [False] * (target + 1)
    dp[0] = True
    for x in nums:
        for t in range(target, x - 1, -1):    # downward: use x once
            dp[t] = dp[t] or dp[t - x]
    return dp[target]

\(O(n \cdot \text{target})\) time, \(O(\text{target})\) space.

Pitfalls

QQuestionSelf-check

Why track both max and min in Maximum Product Subarray? How does House Robber II reduce to House Robber?

ASolution

A large negative running product can become the largest when multiplied by another negative, so the minimum must be kept to catch that flip. Making the houses a circle means the first and last cannot both be robbed, so the answer is the best of solving the linear problem on nums[:-1] and on nums[1:].

Next: 2-D Dynamic Programming (LeetCode #14) — a table for two indices.