Data Structures & AlgorithmsHardAmazon · Microsoft OA

Problem: Count how many distinct index sequences of s spell t as a subsequence.

Problem: Count how many distinct index sequences of s spell t as a subsequence.
def distinct(s, t):
    dp = [1] + [0] * len(t)
    for c in s:
        for j in range(len(t), 0, -1):
            if t[j-1] == c: dp[j] += dp[j-1]
    return dp[-1]
print(distinct("aabbcc", "abc"), distinct("abab", "ab"))
What is printed?
  1. A. 8 4
  2. B. 6 3
  3. C. 2 3
  4. D. 8 3

Correct answer: D. 8 3

For 'aabbcc' choose one of 2 a's, 2 b's and 2 c's in order: 2 × 2 × 2 = 8. For 'abab', the pairs (a, b) with a before b are (0,1), (0,3), (2,3): 3. Looping j backwards stops a character from being used twice in one update.

More Coding Interview Problems questions

Exams that ask this topic