Problem summary: Given a string s, partition s such that every substring of the partition is a palindrome. Return the minimum cuts needed for a palindrome partitioning of s.
Baseline thinking
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Dynamic Programming
Example 1
"aab"
Example 2
"a"
Example 3
"ab"
Related Problems
Palindrome Partitioning (palindrome-partitioning)
Palindrome Partitioning IV (palindrome-partitioning-iv)
Maximum Number of Non-overlapping Palindrome Substrings (maximum-number-of-non-overlapping-palindrome-substrings)
Number of Great Partitions (number-of-great-partitions)
Step 02
Core Insight
What unlocks the optimal approach
No official hints in dataset. Start from constraints and look for a monotonic or reusable state.
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03
Algorithm Walkthrough
Iteration Checklist
Define state (indices, window, stack, map, DP cell, or recursion frame).
Apply one transition step and update the invariant.
Record answer candidate when condition is met.
Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04
Edge Cases
Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Largest constraint values
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05
Full Annotated Code
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #132: Palindrome Partitioning II
class Solution {
public int minCut(String s) {
int n = s.length();
boolean[][] g = new boolean[n][n];
for (var row : g) {
Arrays.fill(row, true);
}
for (int i = n - 1; i >= 0; --i) {
for (int j = i + 1; j < n; ++j) {
g[i][j] = s.charAt(i) == s.charAt(j) && g[i + 1][j - 1];
}
}
int[] f = new int[n];
for (int i = 0; i < n; ++i) {
f[i] = i;
}
for (int i = 1; i < n; ++i) {
for (int j = 0; j <= i; ++j) {
if (g[j][i]) {
f[i] = Math.min(f[i], j > 0 ? 1 + f[j - 1] : 0);
}
}
}
return f[n - 1];
}
}
// Accepted solution for LeetCode #132: Palindrome Partitioning II
func minCut(s string) int {
n := len(s)
g := make([][]bool, n)
f := make([]int, n)
for i := range g {
g[i] = make([]bool, n)
f[i] = i
for j := range g[i] {
g[i][j] = true
}
}
for i := n - 1; i >= 0; i-- {
for j := i + 1; j < n; j++ {
g[i][j] = s[i] == s[j] && g[i+1][j-1]
}
}
for i := 1; i < n; i++ {
for j := 0; j <= i; j++ {
if g[j][i] {
if j == 0 {
f[i] = 0
} else {
f[i] = min(f[i], f[j-1]+1)
}
}
}
}
return f[n-1]
}
# Accepted solution for LeetCode #132: Palindrome Partitioning II
class Solution:
def minCut(self, s: str) -> int:
n = len(s)
g = [[True] * n for _ in range(n)]
for i in range(n - 1, -1, -1):
for j in range(i + 1, n):
g[i][j] = s[i] == s[j] and g[i + 1][j - 1]
f = list(range(n))
for i in range(1, n):
for j in range(i + 1):
if g[j][i]:
f[i] = min(f[i], 1 + f[j - 1] if j else 0)
return f[-1]
// Accepted solution for LeetCode #132: Palindrome Partitioning II
struct Solution;
use std::collections::HashMap;
impl Solution {
fn min_cut(s: String) -> i32 {
let n = s.len();
let s: Vec<char> = s.chars().collect();
let mut memo: HashMap<(usize, usize), i32> = HashMap::new();
Self::dp(0, n, &mut memo, &s)
}
fn dp(start: usize, end: usize, memo: &mut HashMap<(usize, usize), i32>, s: &[char]) -> i32 {
if let Some(&res) = memo.get(&(start, end)) {
return res;
}
let res = if Self::is_palindrome(start, end, s) {
0
} else {
let mut res = std::i32::MAX;
for i in start + 1..end {
if Self::is_palindrome(start, i, s) {
res = res.min(1 + Self::dp(i, end, memo, s));
}
}
res
};
memo.insert((start, end), res);
res
}
fn is_palindrome(start: usize, end: usize, s: &[char]) -> bool {
!s[start..end]
.iter()
.zip(s[start..end].iter().rev())
.any(|(a, b)| a != b)
}
}
#[test]
fn test() {
let s = "aab".to_string();
let res = 1;
assert_eq!(Solution::min_cut(s), res);
let s = "coder".to_string();
let res = 4;
assert_eq!(Solution::min_cut(s), res);
}
// Accepted solution for LeetCode #132: Palindrome Partitioning II
function minCut(s: string): number {
const n = s.length;
const g: boolean[][] = Array.from({ length: n }, () => Array(n).fill(true));
for (let i = n - 1; ~i; --i) {
for (let j = i + 1; j < n; ++j) {
g[i][j] = s[i] === s[j] && g[i + 1][j - 1];
}
}
const f: number[] = Array.from({ length: n }, (_, i) => i);
for (let i = 1; i < n; ++i) {
for (let j = 0; j <= i; ++j) {
if (g[j][i]) {
f[i] = Math.min(f[i], j ? 1 + f[j - 1] : 0);
}
}
}
return f[n - 1];
}
Step 06
Interactive Study Demo
Use this to step through a reusable interview workflow for this problem.
Press Step or Run All to begin.
Step 07
Complexity Analysis
Time
O(n^2)
Space
O(n^2)
Approach Breakdown
RECURSIVE
O(2ⁿ) time
O(n) space
Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.
DYNAMIC PROGRAMMING
O(n × m) time
O(n × m) space
Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.
Shortcut: Count your DP state dimensions → that’s your time. Can you drop one? That’s your space optimization.
Coach Notes
Common Mistakes
Review these before coding to avoid predictable interview regressions.
State misses one required dimension
Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.
Usually fails on: Correctness breaks on cases that differ only in hidden state.
Fix: Define state so each unique subproblem maps to one DP cell.