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?- A. 8
- B. 6
- C. 7
- 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
- Problem: The minimum number of insertions to make 'abcab' a palindrome equals n minus the length of its longest palindromic subsequence…
- Problem: Count pairs (i < j) of a = [1, 2, 3] with a[i] XOR a[j] summed over all pairs. What is the total of the XOR values? Run the code…
- Problem: What is the maximum sum of a path from the top-left to the bottom-right of the grid [[1,3,1],[1,5,1],[4,2,1]] moving only right…
- Problem: How many binary strings of length 5 contain no two consecutive 1s?
- Problem: What is the maximum product of a non-empty contiguous subarray of [2, 3, -2, 4, -1]? Use the code below. python a = [2, 3, -2, 4…
- Problem: How many islands (4-connected groups of '1') are in the grid below? Run the DFS code. python g = ['11000', '11000', '00100'…