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?- A. 5
- B. 3
- C. 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
- Problem: How many two-digit numbers have a digit sum that is a prime number? Run the code. python def isp(n): return n > 1 and all(n % d…
- Problem: How many subarrays of [1, 2, 2, 3, 3, 3] have all equal maximum and minimum values? Run the code. python a = [1, 2, 2, 3, 3, 3]…
- Problem: How many integers in [1, 100] have exactly two prime factors counted with multiplicity? Run the code. python def omega(n): c = 0…
- Problem: What is the sum of all proper divisors of 220 (divisors smaller than 220)? Run the code. python print(sum(d for d in range(1…
- Problem: What is the minimum number of coins from {1, 6, 10} that sum to 37? Run the DP. python INF = 10 9 d = [0] + [INF] 37 for v in…
- Problem: How many distinct arrangements of the letters of 'MISSISSIPPI' exist? Run the code. python import math print(math.factorial(11)…