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?- A. 5 ['a', 'baab']
- B. 4 ['a', 'baab']
- C. 4 ['aba', 'a', 'b']
- 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
- Problem: Find all combinations of unlimited-use stamp values that total exactly 15 (each combination listed once, in non-decreasing…
- Problem: Restore all valid IPv4 addresses from a digit string (four parts, each 0–255, no leading zeros except "0"). python def…
- Problem: Return every value an arithmetic expression can take under all possible full parenthesisations (divide and conquer on each…
- Problem: A node is 'good' if no node on the path from the root to it has a greater value. Count good nodes. Trees are built from a…
- Problem: Exactly two keys of a BST were swapped by mistake. Find them with an inorder traversal: the first key is the left side of the…
- Problem: Trim a BST so that only keys in [lo, hi] remain (keeping BST structure), then print its preorder. Trees are built from a…