You are given three strings word1, word2, and target.
Your task is to count the number of ways to form target by choosing characters from word1 and word2 under the following conditions:
target, choose one matching character from either word1 or word2.word1 must be strictly increasing.word2 must be strictly increasing.word1 and word2.Two ways are considered different if, for at least one position in target, the chosen character comes from a different string or a different index.
Return the number of ways. Since the answer may be very large, return it modulo 109 + 7.
Example 1:
Input: word1 = "abc", word2 = "bac", target = "abc"
Output: 5
Explanation:
There are 5 ways to form target:
word1[0] = 'a', word1[1] = 'b', word2[2] = 'c'word1[0] = 'a', word2[0] = 'b', word1[2] = 'c'word1[0] = 'a', word2[0] = 'b', word2[2] = 'c'word2[1] = 'a', word1[1] = 'b', word1[2] = 'c'word2[1] = 'a', word1[1] = 'b', word2[2] = 'c'All ways preserve the increasing index order inside each string and choose at least one character from each string.
Example 2:
Input: word1 = "cd", word2 = "cd", target = "ccd"
Output: 4
Explanation:
There are 4 ways to form target:
word1[0] = 'c', word2[0] = 'c', word1[1] = 'd'word1[0] = 'c', word2[0] = 'c', word2[1] = 'd'word2[0] = 'c', word1[0] = 'c', word1[1] = 'd'word2[0] = 'c', word1[0] = 'c', word2[1] = 'd'The first two 'c' characters in target must come one from each string. The final 'd' can be chosen from either string.
Example 3:
Input: word1 = "xy", word2 = "xy", target = "xyxy"
Output: 2
Explanation:
There are 2 ways to form target:
word1[0] = 'x', word1[1] = 'y', word2[0] = 'x', word2[1] = 'y'word2[0] = 'x', word2[1] = 'y', word1[0] = 'x', word1[1] = 'y'Each "xy" part in target comes entirely from one string.
Example 4:
Input: word1 = "ab", word2 = "cde", target = "ace"
Output: 1
Explanation:
The only way is to choose word1[0] = 'a', word2[0] = 'c', and word2[2] = 'e'. Thus, the answer is 1.
Constraints:
1 <= word1.length, word2.length, target.length <= 100word1, word2, and target consist of lowercase English letters only.Problem Overview: You need to count how many distinct ways a target string can be formed by choosing characters from two source strings while preserving character order. The challenge comes from handling overlapping subproblems efficiently because many index combinations lead to the same remaining state.
Approach 1: Recursive Brute Force (Exponential Time, O(2^(n+m)) time, O(n+m) space)
The direct approach uses recursion to try every valid choice from both strings. At each step, you compare the current target character against characters from the two source strings and recursively continue when a match is found. This works for very small inputs because it explores every subsequence combination explicitly. The main drawback is repeated computation of the same index states, which causes exponential growth.
Approach 2: Top-Down Dynamic Programming with Memoization (O(n*m*k) time, O(n*m*k) space)
This is the standard interview solution. Use a memoized DFS where the state is defined by indices in the first string, second string, and target string. For each state, iterate forward in both source strings to locate matching characters and accumulate the number of valid constructions. Memoization eliminates duplicate work by caching results for repeated states. This approach is easier to reason about than iterative DP and maps naturally to the recursive definition of the problem. It combines dynamic programming with recursion to reduce the search space dramatically.
Approach 3: Bottom-Up DP with Prefix Optimization (O(n*m*k) time, O(n*m) space)
An iterative DP solution avoids recursion depth issues and gives tighter memory control. Build a DP table where each cell stores the number of ways to form a prefix of the target using prefixes of the two strings. Transition values come from previous states when matching characters are found. Prefix accumulation or rolling arrays can reduce memory usage while keeping transitions efficient. This version is useful when you need production-grade stability or strict stack constraints.
Approach 4: Character Index Preprocessing + DP (Optimized Lookup)
You can preprocess character positions for both source strings using arrays or hash maps. During DP transitions, binary search or indexed traversal quickly finds the next valid matching positions instead of scanning linearly every time. This optimization improves constant factors significantly on larger inputs with repeated characters. It pairs well with hash table based indexing and memoized search.
Recommended for interviews: Interviewers typically expect the memoized dynamic programming solution because it demonstrates state modeling, pruning, and complexity optimization. Showing the brute force recursion first proves you understand the search space, while transitioning to DP shows the ability to identify overlapping subproblems and optimize them systematically.
Solutions for this problem are being prepared.
Try solving it yourself| Approach | Time | Space | When to Use |
|---|---|---|---|
| Recursive Brute Force | O(2^(n+m)) | O(n+m) | Useful for understanding the full search space on tiny inputs |
| Top-Down DP with Memoization | O(n*m*k) | O(n*m*k) | Best general interview solution with clean recursion |
| Bottom-Up Dynamic Programming | O(n*m*k) | O(n*m) | Preferred when recursion depth or memory layout matters |
| Character Index Preprocessing + DP | O(n*m*k) | O(n*m+k) | Efficient for large strings with many repeated characters |
Q4. Count Distinct Ways to Form Target from Two Strings || Easy DP || Leetcode Biweekly 186 || 2X 🚀 • Rajan Keshari ( CSE - IIT Dhanbad ) • 391 views views
Watch 2 more video solutions →Practice Count Distinct Ways to Form Target from Two Strings with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor