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?
  1. A. 4 3
  2. B. 4 2
  3. C. 6 3
  4. 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

Exams that ask this topic