Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Dynamic programming

How many times one string appears in another

Hard · Target 25 minutes · Dynamic programming · Type asked atGoogleBloomberg

Given strings s and t, return the number of distinct ways to choose positions of s that spell t in order: the number of times t appears in s as a subsequence. The empty string appears exactly once in any string.

Examples

InputOutputWhy
s = "rabbbit", t = "rabbit"3Leave out any one of the three b's.
s = "babgbag", t = "bag"5Five choices of positions.
s = "abc", t = ""1The empty string.

Constraints

  • 0 ≤ s.length, t.length ≤ 1000
  • The answer fits in a 64-bit integer

Hints

Hint 1

dp[i][j] = number of ways the first j characters of t appear in the first i characters of s.

Hint 2

Always: dp[i − 1][j] (do not use s[i − 1]). If s[i − 1] = t[j − 1], also dp[i − 1][j − 1].

Hint 3

dp[i][0] = 1; dp[0][j] = 0 for j > 0.

Where people lose marks

  • Running j upwards with one array, which uses the same character of s twice.
  • dp[0][0] = 0: the empty t must count once.
  • Overflow in 32-bit integers.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.