All problems
0373HardStringDynamic Programming

Ways to Spell the Motif

Tracked in this browser only
Write code

Trains the technique from

LeetCode 115Distinct Subsequences

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

trace and motif are strings of English letters. Upper case and lower case are different letters throughout.

A pick is a set of positions in trace, read in increasing order, whose letters spell motif exactly. Two picks count as different when their position sets differ, even when the letters they read off are identical.

Return how many picks trace admits for motif.

Examples

Example 1

Input
trace = "AbAb", motif = "Ab"
Output
3

The picks are positions (0,1), (0,3) and (2,3). Each reads A then b.

Example 2

Input
trace = "aaaa", motif = "aa"
Output
6

Any two of the four positions spell the motif, and there are six such pairs.

Example 3

Input
trace = "aA", motif = "a"
Output
1

Only position 0 holds a lower-case a; position 1 holds a different letter because case matters.

Example 4

Input
trace = "ab", motif = "abc"
Output
0

The motif needs three positions and the trace only offers two, so no pick exists.

Constraints

  • 1 <= trace.length, motif.length <= 1000
  • trace and motif consist of English letters.

The signature

The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def num_distinct(trace: str, motif: str) -> int:
Java
public int numDistinct(String trace, String motif)
September 7
Apply