Count Substrings That Differ by One Character Problem
Description
LeetCode Problem 1638.
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 <= 100sandtconsist of lowercase English letters only.
Solution
Approach: Expand Around Each Mismatch
Counting the pairs of substrings directly would try every start in s, every start in t and every length. Count from the differing character instead.
A valid pair has exactly one position where the characters differ. Say that is s[i] and t[j] with s[i] != t[j]. Every other position of the pair must match, so the pair can reach left only over equal characters and right only over equal characters:
left= how many characters right beforeiandjare equal (s[i-1] == t[j-1],s[i-2] == t[j-2], ...);right= the same count for the characters right after.
The pair can start at any of the left + 1 positions and end at any of the right + 1 positions, so this mismatch gives (left + 1) * (right + 1) pairs. Each pair is counted once, at its only mismatch. Add this up over all (i, j) with s[i] != t[j].
Complexity: O(m · n · min(m, n)) time in the worst case, which is fine for strings of length at most 100. O(1) extra space.
class Solution:
def countSubstrings(self, s: str, t: str) -> int:
m, n = len(s), len(t)
ans = 0
for i in range(m):
for j in range(n):
if s[i] == t[j]:
continue
# s[i] != t[j] is the one differing position. Count equal characters
# just before it (left) and just after it (right).
left = 0
while i - left > 0 and j - left > 0 and s[i - left - 1] == t[j - left - 1]:
left += 1
right = 0
while i + right + 1 < m and j + right + 1 < n and s[i + right + 1] == t[j + right + 1]:
right += 1
ans += (left + 1) * (right + 1)
return ans