Mutating counts without cleanup
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.
Move from brute-force thinking to an efficient approach using hash map strategy.
Given two strings s and t, find the number of ways you can choose a non-empty substring of s and replace a single character by a different character such that the resulting substring is a substring of t. In other words, find the number of substrings in s that differ from some substring in t by exactly one character.
For example, the underlined substrings in "computer" and "computation" only differ by the 'e'/'a', so this is a valid way.
Return the number of substrings that satisfy the condition above.
A substring is a contiguous sequence of characters within a string.
Example 1:
Input: s = "aba", t = "baba"
Output: 6
Explanation: The following are the pairs of substrings from s and t that differ by exactly 1 character:
("aba", "baba")
("aba", "baba")
("aba", "baba")
("aba", "baba")
("aba", "baba")
("aba", "baba")
The underlined portions are the substrings that are chosen from s and t.
Example 2:
Input: s = "ab", t = "bb"
Output: 3
Explanation: The following are the pairs of substrings from s and t that differ by 1 character:
("ab", "bb")
("ab", "bb")
("ab", "bb")
The underlined portions are the substrings that are chosen from s and t.
Constraints:
1 <= s.length, t.length <= 100s and t consist of lowercase English letters only.Problem summary: Given two strings s and t, find the number of ways you can choose a non-empty substring of s and replace a single character by a different character such that the resulting substring is a substring of t. In other words, find the number of substrings in s that differ from some substring in t by exactly one character. For example, the underlined substrings in "computer" and "computation" only differ by the 'e'/'a', so this is a valid way. Return the number of substrings that satisfy the condition above. A substring is a contiguous sequence of characters within a string.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Hash Map · Dynamic Programming
"aba" "baba"
"ab" "bb"
count-words-obtained-after-adding-a-letter)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1638: Count Substrings That Differ by One Character
class Solution {
public int countSubstrings(String s, String t) {
int ans = 0;
int m = s.length(), n = t.length();
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (s.charAt(i) != t.charAt(j)) {
int l = 0, r = 0;
while (i - l > 0 && j - l > 0 && s.charAt(i - l - 1) == t.charAt(j - l - 1)) {
++l;
}
while (i + r + 1 < m && j + r + 1 < n
&& s.charAt(i + r + 1) == t.charAt(j + r + 1)) {
++r;
}
ans += (l + 1) * (r + 1);
}
}
}
return ans;
}
}
// Accepted solution for LeetCode #1638: Count Substrings That Differ by One Character
func countSubstrings(s string, t string) (ans int) {
m, n := len(s), len(t)
for i, a := range s {
for j, b := range t {
if a != b {
l, r := 0, 0
for i > l && j > l && s[i-l-1] == t[j-l-1] {
l++
}
for i+r+1 < m && j+r+1 < n && s[i+r+1] == t[j+r+1] {
r++
}
ans += (l + 1) * (r + 1)
}
}
}
return
}
# Accepted solution for LeetCode #1638: Count Substrings That Differ by One Character
class Solution:
def countSubstrings(self, s: str, t: str) -> int:
ans = 0
m, n = len(s), len(t)
for i, a in enumerate(s):
for j, b in enumerate(t):
if a != b:
l = r = 0
while i > l and j > l and s[i - l - 1] == t[j - l - 1]:
l += 1
while (
i + r + 1 < m and j + r + 1 < n and s[i + r + 1] == t[j + r + 1]
):
r += 1
ans += (l + 1) * (r + 1)
return ans
// Accepted solution for LeetCode #1638: Count Substrings That Differ by One Character
struct Solution;
impl Solution {
fn count_substrings(s: String, t: String) -> i32 {
let n = s.len();
let m = t.len();
let s: Vec<char> = s.chars().collect();
let t: Vec<char> = t.chars().collect();
let mut res = 0;
for i in 0..n {
for j in 0..m {
let k = (n - i).min(m - j);
let mut diff = 0;
for d in 0..k {
if s[i + d] != t[j + d] {
diff += 1;
}
if diff == 1 {
res += 1;
}
}
}
}
res
}
}
#[test]
fn test() {
let s = "aba".to_string();
let t = "baba".to_string();
let res = 6;
assert_eq!(Solution::count_substrings(s, t), res);
let s = "ab".to_string();
let t = "bb".to_string();
let res = 3;
assert_eq!(Solution::count_substrings(s, t), res);
let s = "a".to_string();
let t = "a".to_string();
let res = 0;
assert_eq!(Solution::count_substrings(s, t), res);
let s = "abe".to_string();
let t = "bbc".to_string();
let res = 10;
assert_eq!(Solution::count_substrings(s, t), res);
}
// Accepted solution for LeetCode #1638: Count Substrings That Differ by One Character
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #1638: Count Substrings That Differ by One Character
// class Solution {
// public int countSubstrings(String s, String t) {
// int ans = 0;
// int m = s.length(), n = t.length();
// for (int i = 0; i < m; ++i) {
// for (int j = 0; j < n; ++j) {
// if (s.charAt(i) != t.charAt(j)) {
// int l = 0, r = 0;
// while (i - l > 0 && j - l > 0 && s.charAt(i - l - 1) == t.charAt(j - l - 1)) {
// ++l;
// }
// while (i + r + 1 < m && j + r + 1 < n
// && s.charAt(i + r + 1) == t.charAt(j + r + 1)) {
// ++r;
// }
// ans += (l + 1) * (r + 1);
// }
// }
// }
// return ans;
// }
// }
Use this to step through a reusable interview workflow for this problem.
Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.
Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.
Review these before coding to avoid predictable interview regressions.
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.
Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.
Usually fails on: Correctness breaks on cases that differ only in hidden state.
Fix: Define state so each unique subproblem maps to one DP cell.