Data Structures & AlgorithmsModerateAmazon · Microsoft OA
Problem: Count the ways to partition a string into substrings that are all palindromes.
Problem: Count the ways to partition a string into substrings that are all palindromes.
def parts(s):
n = len(s); dp = [1] + [0] * n
for i in range(1, n + 1):
for j in range(i):
t = s[j:i]
if t == t[::-1]: dp[i] += dp[j]
return dp[n]
print(parts("aabb"), parts("abab"))What is printed?- A. 4 3
- B. 4 2
- C. 6 3
- D. 2 3
Correct answer: A. 4 3
'aabb': a|a|b|b, aa|b|b, a|a|bb, aa|bb = 4. 'abab': a|b|a|b, aba|b, a|bab = 3. dp[i] adds dp[j] whenever s[j:i] is a palindrome.
More Coding Interview Problems questions
- Problem: Insert +, − or between the digits of num (or leave digits joined) so that the expression equals target. Count the expressions (no…
- Problem: Check whether a number is a power of four with bit tricks. python def p4(n): return n > 0 and n & (n - 1) == 0 and n & 0x55555555…
- Problem: A number is 'happy' if repeatedly replacing it by the sum of the squares of its digits reaches 1. Cycle detection uses a set…
- Problem: Break n into at least two positive integers to maximise their product. python def brk(n): dp = [0, 1] + [0] (n - 1) for i in…
- A suffix array of a string of length n is built by putting all suffixes in a list and sorting them with a comparison sort, where each…
- What is the solution of T(n) = T(n/2) + T(n/4) + n?