Skip to main content

Count Distinct Ways to Form Target from Two Strings - Solution & Explanation

Practice this problem

Problem Statement

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:

  • For each character of target, choose one matching character from either word1 or word2.
  • The chosen indices from word1 must be strictly increasing.
  • The chosen indices from word2 must be strictly increasing.
  • At least one character must be chosen from both 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 <= 100
  • word1, word2, and target consist of lowercase English letters only.

Approach Overview

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

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Recursive Brute ForceO(2^(n+m))O(n+m)Useful for understanding the full search space on tiny inputs
Top-Down DP with MemoizationO(n*m*k)O(n*m*k)Best general interview solution with clean recursion
Bottom-Up Dynamic ProgrammingO(n*m*k)O(n*m)Preferred when recursion depth or memory layout matters
Character Index Preprocessing + DPO(n*m*k)O(n*m+k)Efficient for large strings with many repeated characters

Video Solution

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 →

Frequently Asked Questions

Is Count Distinct Ways to Form Target from Two Strings easy or hard?
Count Distinct Ways to Form Target from Two Strings is categorized as Hard because the brute force search space grows exponentially. Solving it efficiently requires recognizing overlapping subproblems and designing a correct multi-dimensional DP state.
Count Distinct Ways to Form Target from Two Strings Python/Java solution
Python solutions usually use @lru_cache for memoized recursion, making the implementation compact and readable. Java solutions commonly use 3D arrays or HashMap-based memoization to store DP states efficiently.
How to solve Count Distinct Ways to Form Target from Two Strings in O(n*m*k)?
Use memoized DFS or bottom-up DP. Each state represents how many ways remain after choosing prefixes from both strings and matching a prefix of the target. Transition only when characters match, and reuse cached results for overlapping subproblems.
What is the best approach for Count Distinct Ways to Form Target from Two Strings?
The best approach is dynamic programming with memoization. Define states using indices of the two source strings and the target string, then cache computed results to avoid repeated work. This reduces exponential recursion into a polynomial-time solution with manageable memory usage.
Is Count Distinct Ways to Form Target from Two Strings asked at Google/Amazon/Meta?
Hard dynamic programming problems involving subsequences, memoization, and combinatorics commonly appear in interviews at Google, Amazon, and Meta. This problem tests recursive state modeling, optimization, and DP transition design under constraints.
What data structure is used in Count Distinct Ways to Form Target from Two Strings?
The core data structure is a dynamic programming table or memoization cache. Hash maps or arrays are often used to store computed states, while character index arrays can speed up matching operations in optimized implementations.
What is the time complexity of Count Distinct Ways to Form Target from Two Strings?
The optimal dynamic programming solution typically runs in O(n*m*k) time, where n and m are the lengths of the source strings and k is the target length. Space complexity is also O(n*m*k) for memoization, though iterative optimizations can reduce memory usage.

Ready to solve this problem?

Practice Count Distinct Ways to Form Target from Two Strings with our built-in code editor and test cases.

Practice on FleetCode