Data Structures & AlgorithmsHardInfosys SP/DSE · Product Company SDE

Problem: Split a string into pieces that are all palindromes and list every such partition (backtracking).

Problem: Split a string into pieces that are all palindromes and list every such partition (backtracking).
def pal_parts(s):
    res = []
    def bt(i, path):
        if i == len(s): res.append(path[:]); return
        for j in range(i + 1, len(s) + 1):
            if s[i:j] == s[i:j][::-1]:
                path.append(s[i:j]); bt(j, path); path.pop()
    bt(0, [])
    return res
r = pal_parts("abaab")
print(len(r), min(r, key=len))
What is printed?
  1. A. 5 ['a', 'baab']
  2. B. 4 ['a', 'baab']
  3. C. 4 ['aba', 'a', 'b']
  4. D. 3 ['a', 'baab']

Correct answer: B. 4 ['a', 'baab']

Partitions of "abaab": a|b|a|a|b, a|b|aa|b, a|baab, aba|a|b → 4. The fewest pieces is 2 (a | baab), which is what min by length returns ("abaab" itself is not a palindrome). Worst case O(n · 2ⁿ); the minimum-cut version is solved by DP in O(n²).

More Coding Interview Problems questions

Exams that ask this topic