Count Substrings That Differ by One Character - Problem

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.

Input & Output

Example 1 — Basic Case
$ Input: s = "ab", t = "bb"
Output: 1
💡 Note: The substring "a" from s differs from substring "b" from t by exactly one character (a ≠ b). This is the only valid substring pair.
Example 2 — Multiple Matches
$ Input: s = "aba", t = "bab"
Output: 6
💡 Note: Valid pairs: "a"→"b" (2 ways), "b"→"a" (2 ways), "ab"→"ba" (1 way), "ba"→"ab" (1 way). Total: 6 substring pairs with exactly one difference.
Example 3 — No Differences
$ Input: s = "ab", t = "ab"
Output: 0
💡 Note: All corresponding substrings are identical, so no substring differs by exactly one character.

Constraints

  • 1 ≤ s.length, t.length ≤ 100
  • s and t consist of lowercase English letters only

Visualization

Tap to expand
Count Substrings Differing by One CharacterString s:abString t:bbCompare substrings: Change exactly 1 character"a" from s1 diff"b" from tResult: 1 valid substring pair found
Understanding the Visualization
1
Input Strings
Two strings s and t with characters to compare
2
Find Differences
Identify character positions where s[i] ≠ t[j]
3
Count Valid Pairs
Count substring pairs differing by exactly one character
Key Takeaway
🎯 Key Insight: Use DP to count prefix/suffix matches around each character difference
Asked in
Google 25 Amazon 18 Microsoft 15
28.5K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen