Data Structures & AlgorithmsVery hardICPC regional · string DP

Problem: How many distinct subsequences (including the empty one) does 'aba' have? Run the DP below.

Problem: How many distinct subsequences (including the empty one) does 'aba' have? Run the DP below.
def dsub(s):
    dp = [1]
    last = {}
    for i, ch in enumerate(s, 1):
        dp.append(2 * dp[-1] - (dp[last[ch] - 1] if ch in last else 0))
        last[ch] = i
    return dp[-1]
print(dsub('aba'))
What is printed?
  1. A. 8
  2. B. 6
  3. C. 7
  4. D. 3

Correct answer: C. 7

Each new character doubles the count, minus the count before its previous occurrence: dp = 1, 2, 4, 7, i.e. '', a, b, ab, ba, aa, aba. Doubling without subtracting repeats gives 8, excluding the empty subsequence gives 6, and listing only the length-2 subsequences (ab, ba, aa) gives 3.

More Coding Interview Problems questions

Exams that ask this topic