Count Substrings That Differ by One Character - Problem
Imagine you're a text editor developer working on a "smart suggestion" feature. Given two strings s and t, you need to find how many substrings from s can be transformed into substrings of t by changing exactly one character.
More formally, count the number of ways you can:
- Choose a non-empty substring from s
- Replace exactly one character in it
- Make it match some substring in t
For example, in "computer" and "computation", the substring "comput" from the first string differs from "comput" in the second string by exactly one character (position doesn't matter for counting).
Goal: Return the total count of such valid transformations.
Input & Output
example_1.py โ Basic Example
$
Input:
s = "aba", t = "baba"
โบ
Output:
6
๐ก Note:
The substrings are: "a" from s โ "b" from t (change aโb), "b" from s โ "a" from t (change bโa), "ab" from s โ "ba" from t (change aโb), "ba" from s โ "ab" from t (change bโa), "aba" from s โ "bab" from t (change aโb), "aba" from s โ "aba" from t (change bโa)
example_2.py โ Same Characters
$
Input:
s = "ab", t = "bb"
โบ
Output:
3
๐ก Note:
The valid transformations are: "a" โ "b" (change aโb), "ab" โ "bb" (change aโb), "b" โ "b" is not valid since no change needed
example_3.py โ Single Character
$
Input:
s = "a", t = "a"
โบ
Output:
0
๐ก Note:
No valid substrings because "a" and "a" are identical, so we cannot make exactly one character change
Visualization
Tap to expand
Understanding the Visualization
1
Identify difference positions
Find all positions where the two strings have different characters
2
Count matching neighbors
For each difference, count how many characters match before and after
3
Calculate combinations
Multiply prefix and suffix counts to get total valid substrings
4
Sum all possibilities
Add up counts from all difference positions
Key Takeaway
๐ฏ Key Insight: Instead of generating all substrings, we fix each difference position and count how many valid substrings can be formed around it using mathematical combinations.
Time & Space Complexity
Time Complexity
O(nm)
We process each character pair once, where n and m are string lengths
โ Linear Growth
Space Complexity
O(nm)
Two DP arrays to store prefix and suffix matching lengths
โก Linearithmic Space
Constraints
- 1 โค s.length, t.length โค 100
- s and t consist of lowercase English letters only
- Must differ by exactly one character - not zero, not two or more
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code