The Count Substrings That Differ by One Character coding problem involves two strings, s and t. Your goal is to find the total number of pairs of substrings that have the same length and differ by exactly one character at exactly one position.
For example, "aba" and "aba" differ by zero characters. "aba" and "aca" differ by exactly one character at the second position. "aba" and "adc" differ by two characters. You are only interested in the "exactly one" case.
Microsoft uses this problem to test a candidate's ability to optimize nested search spaces. A brute-force approach (comparing every possible substring of every length) is extremely slow. This question evaluates whether you can use dynamic programming interview pattern or intelligent enumeration to skip redundant comparisons. It’s a great test of observational skills—noticing how character matches propagate along diagonals of a comparison matrix.
This problem can be solved using Dynamic Programming or Enumeration with Expansion.
left[i][j] stores the length of the common prefix of suffixes and . right[i][j] stores the length of the common suffix of prefixes and .s and t where , this mismatch can be the "one differing character." You then count how many matching characters are immediately to the left and how many are immediately to the right. The number of valid substring pairs for this specific mismatch is (left_matches + 1) * (right_matches + 1).s = "ab", t = "bb"
s[0] ('a') and t[0] ('b'). They differ.
s[1] ('b') matches t[1] ('b'). Matches = 1.s[0] ('a') and t[1] ('b'). They differ.
s[1] ('b') and t[0] ('b'). They match (skip).
Total pairs = 3.Think of string comparison as a 2D grid where indicates if . Most "substring match" problems involve looking at diagonal lines in this grid. Practice finding "blocks" of consecutive 1s (matches) interrupted by a single 0 (mismatch).