Leetcode #1639: Number of Ways to Form a Target String Given a Dictionary
In this guide, we solve Leetcode #1639 Number of Ways to Form a Target String Given a Dictionary in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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.
Quick Facts
- Difficulty: Hard
- Premium: No
- Tags: Array, String, Dynamic Programming
Intuition
The problem breaks into overlapping subproblems, so caching results prevents exponential repetition.
A carefully chosen DP state captures exactly what we need to build the final answer.
Approach
Define the DP state and recurrence, then compute states in the correct order.
Optionally compress space once the recurrence is clear.
Steps:
- Choose a DP state definition.
- Write the recurrence and base cases.
- Compute states in the correct order.
Example
Input: words = ["acca","bbbb","caca"], target = "aba"
Output: 6
Explanation: There are 6 ways to form target.
"aba" -> index 0 ("acca"), index 1 ("bbbb"), index 3 ("caca")
"aba" -> index 0 ("acca"), index 2 ("bbbb"), index 3 ("caca")
"aba" -> index 0 ("acca"), index 1 ("bbbb"), index 3 ("acca")
"aba" -> index 0 ("acca"), index 2 ("bbbb"), index 3 ("acca")
"aba" -> index 1 ("caca"), index 2 ("bbbb"), index 3 ("acca")
"aba" -> index 1 ("caca"), index 2 ("bbbb"), index 3 ("caca")
Python Solution
class Solution:
def numWays(self, words: List[str], target: str) -> int:
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
The time complexity is , and the space complexity is . The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.