#1638

Count Substrings That Differ by One Character

Medium
Hash TableStringDynamic ProgrammingEnumerationHash MapEnumeration
LeetCode ↗

Approaches

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

Intuition

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

Instead of generating all substrings, we can use a HashMap to store all substrings of `t` and then iterate through `s` to check for valid modifications. This reduces the number of checks needed significantly.

⚙️

Algorithm

3 steps
  1. 1Step 1: Store all substrings of `t` in a HashMap with their counts.
  2. 2Step 2: Iterate through all substrings of `s` and for each substring, generate all possible modified versions by changing one character.
  3. 3Step 3: For each modified substring, check if it exists in the HashMap and add the count to the result.
solution.py16 lines
1def countSubstrings(s, t):
2    from collections import defaultdict
3    count_map = defaultdict(int)
4    for i in range(len(t)):
5        for j in range(i + 1, len(t) + 1):
6            count_map[t[i:j]] += 1
7    count = 0
8    for i in range(len(s)):
9        for j in range(i + 1, len(s) + 1):
10            substr = s[i:j]
11            for k in range(len(substr)):
12                for c in 'abcdefghijklmnopqrstuvwxyz':
13                    if c != substr[k]:
14                        modified = substr[:k] + c + substr[k + 1:]
15                        count += count_map[modified]
16    return count

Complexity note: The complexity arises from storing all substrings of `t` (O(n * m)) and then checking each substring of `s` (O(n² * m)). However, this is significantly more efficient than the brute force method due to reduced checks.

  • 1Using a HashMap to store substrings allows for quick lookups.
  • 2Generating all substrings can be expensive; optimizing checks is crucial.

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