#1639

Number of Ways to Form a Target String Given a Dictionary

Hard
ArrayStringDynamic ProgrammingDynamic ProgrammingCharacter Frequency Counting
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n * m)
Space
O(1)
O(n)
💡

Intuition

Time O(n * m)Space O(n)

The optimal solution uses dynamic programming to efficiently count the ways to form the target string by leveraging character frequency counts from the words. This avoids the need to generate all combinations explicitly.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a frequency array to count occurrences of each character in each position of the words.
  2. 2Step 2: Initialize a DP array where dp[i] represents the number of ways to form the first i characters of the target.
  3. 3Step 3: Iterate over each character in the target and update the DP array based on the frequency of matching characters from the words.
solution.py23 lines
1# Full working Python code
2def countWays(words, target):
3    MOD = 10**9 + 7
4    m, n = len(words[0]), len(target)
5    dp = [0] * (n + 1)
6    dp[0] = 1
7    freq = [[0] * 26 for _ in range(m)]
8
9    for word in words:
10        for j in range(m):
11            freq[j][ord(word[j]) - ord('a')] += 1
12
13    for i in range(1, n + 1):
14        for j in range(m):
15            if target[i - 1] == words[j][i - 1]:
16                dp[i] = (dp[i] + dp[i - 1] * freq[i - 1][ord(target[i - 1]) - ord('a')]) % MOD) % MOD
17
18    return dp[n]
19
20# Example usage
21words = ["acca", "bbbb", "caca"]
22target = "aba"
23print(countWays(words, target))

Complexity note: The time complexity is O(n * m) because we iterate through the target string and for each character, we check the frequency of characters in the words, which takes linear time relative to the length of the target and the number of words.

  • 1Understanding how to use dynamic programming can greatly reduce the complexity of combinatorial problems.
  • 2Character frequency counts can help optimize the selection process in string formation problems.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.