Data Structures & AlgorithmsVery hardProduct company OA

Problem: Minimum cuts to split a string into palindromes: interval DP (pal table + cut array) versus the greedy 'always take the longest palindromic prefix'.

Problem: Minimum cuts to split a string into palindromes: interval DP (pal table + cut array) versus the greedy 'always take the longest palindromic prefix'.
def min_cuts(s):
    n = len(s)
    pal = [[False] * n for _ in range(n)]
    for i in range(n - 1, -1, -1):
        for j in range(i, n):
            pal[i][j] = s[i] == s[j] and (j - i < 2 or pal[i + 1][j - 1])
    cut = [0] * n
    for j in range(n):
        cut[j] = 0 if pal[0][j] else min(cut[i - 1] + 1 for i in range(1, j + 1) if pal[i][j])
    return cut[-1]
def greedy(s):
    i = cuts = 0
    while i < len(s):
        j = max(j for j in range(i, len(s)) if s[i:j + 1] == s[i:j + 1][::-1])
        i = j + 1; cuts += 1
    return cuts - 1
for s in ["aabbaab", "abacdcxy", "ababbbabbaba"]:
    print(min_cuts(s), greedy(s), end="; ")
print()
What is printed?
  1. A. 1 1; 3 3; 3 4;
  2. B. 1 1; 3 3; 3 3;
  3. C. 1 2; 3 3; 4 4;
  4. D. 2 1; 4 3; 3 4;

Correct answer: A. 1 1; 3 3; 3 4;

cut[j] = 0 if s[0..j] is a palindrome, otherwise min over palindromic s[i..j] of cut[i − 1] + 1; with the O(n²) pal table this is O(n²). aabbaab: 'aabbaa' + 'b' → 1 (greedy agrees). abacdcxy: aba | cdc | x | y → 3. For ababbbabbaba the greedy takes aba | bbb | abba | b | a (4 cuts), whereas the DP finds a | bab | bbabb | aba (3 cuts): grabbing the longest prefix is not optimal.

More Coding Interview Problems questions

Exams that ask this topic