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?- A. 1 1; 3 3; 3 4;
- B. 1 1; 3 3; 3 3;
- C. 1 2; 3 3; 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
- Problem: Count Hamiltonian paths (visit every junction exactly once) in a 5-vertex road graph with bitmask DP over (visited set, current…
- Problem: a judge checks your rolling-hash solution with hash(s) = Σ s[i]·Bⁱ computed in unsigned 64-bit arithmetic (implicitly modulo…
- Problem: n ≤ 2·10⁵ values and q ≤ 2·10⁵ offline queries 'how many DISTINCT values are in a[l..r]?' (time limit 2 s). Which approach is…
- Problem: boxes (w, h) can nest when BOTH dimensions are strictly smaller. Find the longest nesting chain for n ≤ 2·10⁵. A candidate sorts…
- Problem: union–find runs m = 10⁶ operations on n = 10⁶ elements. Version X uses union by rank AND path compression; version Y uses path…
- Problem: a ring of n stalls holds 1 (occupied) or 0 (free). In one swap you exchange any two stalls. Find the minimum swaps to bring all…