Dynamic Programming21 sections · 916 units
Open in Course

Breaking a String - Implementation

Handling the edge cases

Add 0 and nn as dummy break points. Now we have m+2m+2 points, and we need to fully break the string. Base case: dp[i][i+1]=0dp[i][i+1] = 0 (no break needed between adjacent points). Fill by increasing gap: gap = 2, 3, ..., m+1m+1. For each (i,j)(i, j) with gap jij - i, search k[opt[i][j1],opt[i+1][j]]k \in [opt[i][j-1], opt[i+1][j]]. Time: O(m2)O(m^2), Space: O(m2)O(m^2). Track opt[i][j]opt[i][j] alongside dp[i][j]dp[i][j]. Add sentinel break points at 0 and n to handle boundaries cleanly. The actual breaks are between sentinels.

Time complexity: O(n2)O(n^2).

Space complexity: O(n2)O(n^2).