Ctrl K

Spelling a Word Column by Column

Hard
You have several letter strips strips, all of the same length; positions on the strips are columns 0, 1, 2, …. Build the word goal under these rules: - the letters of goal are taken one at a time, left to right; - the next letter goal[i] may be taken from any strip strips[j] at any column k where strips[j][k] == goal[i]; - after that, column k and every column to its left become unusable on all strips, so the next letter must come from further right. Several letters may come from the same strip. Count the ways to build goal; two ways differ if some letter uses a different strip or column. Return the answer modulo 10⁹ + 7.
Example 1
strips=["ab", "ba"], goal="ab" → 1

The a must come from column 0 (strip "ab") and the b from column 1 (strip "ab" again). One way.

Example 2
strips=["aaa", "aaa"], goal="aa" → 12

There are three choices of two columns, (0, 1), (0, 2) and (1, 2), and each letter can come from either strip: 3 · 2 · 2 = 12.

Example 3
strips=["xy"], goal="yx" → 0
Constraints
  • 1 ≤ len(strips) ≤ 1000
  • 1 ≤ len(strips[i]) ≤ 1000, all strips have the same length
  • 1 ≤ len(goal) ≤ 1000
  • All strings consist of lowercase English letters
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsEvery Way to Space the Words HardWords Built From Shorter Words HardNumbers From Working Keys HardAssembling Fragments HardCut Columns to Sort Every Row Hard
loading Python…
Input
strips=["ab", "ba"], goal="ab"
Expected
1

Run checks the first 3 tests in your browser. Submit checks all 127 tests on the server, hidden ones included.