Count Substrings That Differ by One Character
Count the pairs of same-length pieces of two strings that differ in exactly one character.
Given two strings stst"ab""abc"
Example 1
Output: 6
Example 2
Output: 3
Explanation: ("a", "b") twice, once for each "b" in t, and ("ab", "bb").
The Idea
You have probably typed "cut" when you meant "cat". The two words have the same length and match everywhere except at one letter. This problem counts near-matches like that, but between pieces of two strings: every substring of st
Walk through Example 2, where s = "ab"t = "bb"s"a""b""ab"t"b""b""bb""a""b""b""b""ab""bb"
Listing works for two short strings, but longer strings have many more substrings, and each pair must be compared character by character. Can we count the pairs without comparing each one?
Look at what every counted pair has in common: exactly one position where its two characters differ. So turn the search around and start from that difference. Pick a character s[i]t[j]s = "cat"t = "cut"au
The orange boxes, aucleft = 1tright = 1
The four rows on the right are those choices, from "a""u""cat""cut"(left + 1) × (right + 1)leftrights[i]t[j]
Solution Approach
In code, three things need settling: which characters act as the difference, how far to extend on each side, and how to count the pairs, with the direct way first and an optional faster one last.
Comparing every pair of substrings
Why not list every pair, as we did for "ab""bb"stst
Choosing the difference
Which characters can be the difference? Any s[i]t[j]isjt
Extending to each side
How far can a pair reach before it picks up a second difference? To the left, compare the characters just before ijleftright
Counting the pairs around one difference
How many pairs does one difference give? The start can be any of left + 1leftright + 1(left + 1) × (right + 1)+ 1
Optional: storing the counts in tables
The walks to the left and right repeat work. When s[i - 1]t[j - 1]iji - 1j - 1leftright
Java Solution
The method countSubstrings
- First, set
to 0. Pick the difference with two loops, one inside the other: the outer loop movesresult alongi , and for eachs the inner loop movesi alongj . Whent equalss.charAt(i) , go on to the nextt.charAt(j) , since equal characters cannot be the difference.j - Count
, starting from 0. While the characters atleft andi - left - 1 exist and are equal, add 1. The index checks come beforej - left - 1 , so position -1 is never read.charAt - Count
the same way, withright andi + right + 1 , stopping at the end of either string.j + right + 1 - Add
to(left + 1) * (right + 1) . After both loops have finished,result holds the count.result
The main"cat""cut"
public class CountSubstringsThatDifferByOneCharacter {
public static int countSubstrings(String s, String t) {
int result = 0;
for (int i = 0; i < s.length(); i++) {
for (int j = 0; j < t.length(); j++) {
if (s.charAt(i) == t.charAt(j)) {
continue; // not a difference: nothing to count here
}
int left = 0; // equal characters just before i and j
while (i - left - 1 >= 0 && j - left - 1 >= 0
&& s.charAt(i - left - 1) == t.charAt(j - left - 1)) {
left++;
}
int right = 0; // equal characters just after i and j
while (i + right + 1 < s.length() && j + right + 1 < t.length()
&& s.charAt(i + right + 1) == t.charAt(j + right + 1)) {
right++;
}
result += (left + 1) * (right + 1);
}
}
return result;
}
public static void main(String[] args) {
System.out.println(countSubstrings("aba", "baba"));
System.out.println(countSubstrings("ab", "bb"));
System.out.println(countSubstrings("cat", "cut"));
System.out.println(countSubstrings("ab", "xy"));
System.out.println(countSubstrings("a", "a"));
}
}
Running it prints:
6
3
10
4
0
Example 1 gives 6 because "aba""baba"s[i]t[j]
Look at the third line: 10 for "cat""cut"au"c""u""t""c"
The fourth line, 4, counts only the single letters of "ab""xy""ab""xy""a""a"
Dropping the + 1left * right
Complexity
The work is the two loops over every pair of positions, plus the walks out from each difference.
- Time: O(m × n × min(m, n)), where m and n are the lengths of
ands . The two loops visit m × n pairs (t ,i ), and for each difference the two walks together pass at most min(m, n) characters, since both stay inside the shorter string.j - Space: O(1). The method keeps only
,i ,j ,left andright , and builds no table.result