Number of Ways to Form a Target String Given a Dictionary — LeetCode 1639 Python Solution

HardArrayStringDynamic Programming
Problem
#1639
Reading time
4 min

The problem

You are given a list of strings of the same length words and a string target. Your task is to form target using the given words under the following rules: target should be formed from left to right.

Example

Input
words = ["acca","bbbb","caca"], target = "aba"
Output
6
Explanation
There are 6 ways to form target.

Python solution

Python
class Solution:
    def numWays(self, words: List[str], target: str) -> int:
        @cache
        def dfs(i: int, j: int) -> int:
            if i >= m:
                return 1
            if j >= n:
                return 0
            ans = dfs(i + 1, j + 1) * cnt[j][ord(target[i]) - ord('a')]
            ans = (ans + dfs(i, j + 1)) % mod
            return ans

        m, n = len(target), len(words[0])
        cnt = [[0] * 26 for _ in range(n)]
        for w in words:
            for j, c in enumerate(w):
                cnt[j][ord(c) - ord('a')] += 1
        mod = 10**9 + 7
        return dfs(0, 0)

Complexity

MeasureComplexity
TimeO(m \times n)
SpaceO(m \times n) auxiliary

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 1639. Number of Ways to Form a Target String Given a Dictionary is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.

The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1639. Number of Ways to Form a Target String Given a Dictionary?
LeetCode 1639. Number of Ways to Form a Target String Given a Dictionary is rated Hard on LeetCode.
What is the time complexity of LeetCode 1639. Number of Ways to Form a Target String Given a Dictionary?
The Python solution on this page runs in O(m \times n).
What is the space complexity of LeetCode 1639. Number of Ways to Form a Target String Given a Dictionary?
The Python solution on this page uses O(m \times n) auxiliary space.
What topics does LeetCode 1639. Number of Ways to Form a Target String Given a Dictionary cover?
LeetCode 1639. Number of Ways to Form a Target String Given a Dictionary is tagged Array, String and Dynamic Programming on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview