Number of Ways to Form a Target String Given a Dictionary — LeetCode 1639 Python Solution
- Problem
- #1639
- Pattern
- Dynamic Programming
- Reading time
- 4 min
- Source
- leetcode.com
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
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
| Measure | Complexity |
|---|---|
| Time | O(m \times n) |
| Space | O(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.