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 s and t, choose a non-empty substring of s and a substring of t with the same length. A substring is a run of neighbouring characters, such as "ab" in "abc". Count the choices where the two substrings differ in exactly one position. The same text taken from two different places in a string counts as two choices.

Example 1
Input: s = "aba", t = "baba"
Output: 6
Example 2
Input: s = "ab", t = "bb"
Output: 3
Explanation: ("a", "b") twice, once for each "b" in t, and ("ab", "bb").
Solution

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 s is held against every substring of t with the same length.

Walk through Example 2, where s = "ab" and t = "bb". The substrings of s are "a", "b" and "ab". In t they are "b" at position 0, "b" at position 1, and "bb". "a" differs from each "b" in one character, which gives two pairs. "b" against "b" has no difference at all, so it does not count. "ab" and "bb" differ only in their first character, which gives the third pair.

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] and a character t[j] that are not equal, and ask how many pairs have their one difference right there. Take s = "cat" and t = "cut", with the difference at a and u. Look at the picture below.

s = cat above t = cut. The middle letters a and u are the difference. One equal letter comes before it (c = c), so left = 1, and one after it (t = t), so right = 1. The pairs built around it are a and u, ca and cu, at and ut, cat and cut: (left + 1) times (right + 1) = 4.

The orange boxes, a and u, are the difference. Just before it, both strings have c, so one equal character lies on the left: left = 1. Just after it, both have t, so right = 1. A pair may start at the difference or one character back, and end at the difference or one character ahead.

The four rows on the right are those choices, from "a" against "u" down to "cat" against "cut". None of them has a second difference, because they only reach into equal characters. So two unequal characters add (left + 1) × (right + 1) pairs, where left and right count the equal characters on each side. Every counted pair is found once, at its one difference, so adding this up over all unequal s[i] and t[j] gives the answer.

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" and "bb"? Say s has m characters and t has n. A pair is a start in s, a start in t and a length, and each pair is compared character by character. That is O(m × n × min(m, n)²) work. Two strings of 100 characters already give 10,000 pairs of starts, each with up to 100 lengths of up to 100 characters.

Choosing the difference

Which characters can be the difference? Any s[i] and t[j] that are not equal, wherever they sit in their strings. Two loops, one inside the other, try every i in s with every j in t, and skip the places where the two characters are equal.

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 i and j, then the ones before those, and stop at the first unequal pair or at the start of either string. The number of equal characters this walk passes is left. A walk to the right in the same way, up to the end of either string, gives right.

Counting the pairs around one difference

How many pairs does one difference give? The start can be any of left + 1 places: the difference itself or one of the left equal characters before it. The end can be any of right + 1 places, chosen on its own. Every start goes with every end, which gives (left + 1) × (right + 1) pairs. The + 1 on each side is the choice not to extend at all.

Optional: storing the counts in tables

The walks to the left and right repeat work. When s[i - 1] equals t[j - 1], the equal characters before i and j are the ones before i - 1 and j - 1, plus that one pair. Two tables of m × n such counts, one filled from the start and one from the end, give each left and right in one step. That brings the time down to O(m × n), but the tables take O(m × n) memory.

Java Solution

The method countSubstrings works in these steps:

  1. First, set result to 0. Pick the difference with two loops, one inside the other: the outer loop moves i along s, and for each i the inner loop moves j along t. When s.charAt(i) equals t.charAt(j), go on to the next j, since equal characters cannot be the difference.
  2. Count left, starting from 0. While the characters at i - left - 1 and j - left - 1 exist and are equal, add 1. The index checks come before charAt, so position -1 is never read.
  3. Count right the same way, with i + right + 1 and j + right + 1, stopping at the end of either string.
  4. Add (left + 1) * (right + 1) to result. After both loops have finished, result holds the count.

The main method runs both examples, the "cat" and "cut" pair from the picture, two strings with no equal characters, and two equal one-letter strings.

Java
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:

Output
6
3
10
4
0

Example 1 gives 6 because "aba" and "baba" have six places where an s[i] and a t[j] differ. None of them has equal characters lined up beside it, so each adds 1 × 1.

Look at the third line: 10 for "cat" and "cut". Four of those pairs are the ones in the picture, around a and u. The other six are single letters that differ, such as "c" against "u" or "t" against "c", and each adds 1.

The fourth line, 4, counts only the single letters of "ab" and "xy". "ab" against "xy" differs in two positions, so it is left out. The last line is 0, since "a" against "a" has no difference to build on.

Dropping the + 1 and adding left * right loses every pair that does not extend on both sides. We tried it: that version returns 0 for both examples instead of 6 and 3.

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 s and t. The two loops visit m × n pairs (i, j), and for each difference the two walks together pass at most min(m, n) characters, since both stay inside the shorter string.
  • Space: O(1). The method keeps only i, j, left, right and result, and builds no table.

Count Binary Substrings also counts substrings by looking at the runs of equal characters on both sides of a boundary.