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 That Differ by One Character INPUT String s = "ab" a b i=0 i=1 String t = "bb" b b j=0 j=1 Substrings of s: "a", "b", "ab" Substrings of t: "b", "b", "bb" ALGORITHM STEPS 1 Enumerate Centers For each pair (i,j), treat s[i] vs t[j] as mismatch 2 Expand Left Count matching chars to the left of center 3 Expand Right Count matching chars to the right of center 4 Calculate Count Add (left+1)*(right+1) to total result Example: i=0, j=0 s[0]='a' vs t[0]='b' Mismatch! left=0, right=0 Count += (0+1)*(0+1) = 1 Substring "a" ---> "b" FINAL RESULT Valid Substring Pairs s substring: "a" t substring: "b" Differ by 1 char at pos 0 Other Pairs Checked: "b" vs "b" - 0 diff (invalid) "ab" vs "bb" - 1 diff (counted) (already in "a" vs "b") Output 1 OK - 1 valid pair found Key Insight: Instead of checking all O(n^2 * m^2) substring pairs, we enumerate each position pair (i,j) as the "center of mismatch" and expand left/right while characters match. This gives O(n*m) complexity. Formula: count += (left_matches + 1) * (right_matches + 1) ensures we count all valid substrings. TutorialsPoint - Count Substrings That Differ by One Character | Optimized Enumeration Approach
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