Data Structures & AlgorithmsVery hardProduct Company SDE · CP practice

Problem: What is the minimum number of cuts needed to partition 'abcde' into palindromes? Run the DP.

Problem: What is the minimum number of cuts needed to partition 'abcde' into palindromes? Run the DP.
s = 'abcde'
n = len(s)
pal = [[False] * n for _ in range(n)]
for i in range(n):
    pal[i][i] = True
for L in range(2, n + 1):
    for i in range(n - L + 1):
        j = i + L - 1
        pal[i][j] = s[i] == s[j] and (L == 2 or pal[i + 1][j - 1])
cuts = [0] * n
for j in range(n):
    if pal[0][j]:
        cuts[j] = 0
    else:
        cuts[j] = min(cuts[i - 1] + 1 for i in range(1, j + 1) if pal[i][j])
print(cuts[n - 1])
What is printed?
  1. A. 5
  2. B. 3
  3. C. 4
  4. D. 6

Correct answer: C. 4

Each character must be its own palindrome piece in 'abcde', so the minimum is four cuts; the DP over palindromic substrings confirms it.

More Coding Interview Problems questions

Exams that ask this topic