Substrings of Size Three with Distinct Characters

Count how many runs of three neighbouring characters in a string contain no repeated character.

Call a string good when no character appears in it twice. Given a string s, count its good substrings of length exactly 3. A substring is a run of characters that sit next to each other in s. Substrings at different positions count separately, even when they hold the same characters.

Example 1
Input: s = "xyzzaz"
Output: 1
Explanation: the substrings of length 3 are "xyz", "yzz", "zza" and "zaz", and only "xyz" is good.
Example 2
Input: s = "aababcabc"
Output: 4
Explanation: the good ones are "abc", "bca", "cab" and "abc" again, at a later position.
Solution

The Idea

Imagine reading a word through a small card with a hole in it, just wide enough to show three letters. You start at the left edge, read the three letters in the hole, then slide the card one letter to the right and read again. Every three-letter substring passes through the hole exactly once.

Do that with "xyzzaz". The hole shows xyz, then yzz, then zza, then zaz. The string has six characters, and the hole fits in four places, so there are 6 - 2 = 4 substrings to check. Each time, the question is the same: are the three letters in the hole all different?

Look at the picture below. Each row is one position of the hole, drawn as a blue frame, and the orange boxes are the letters that repeat.

A window of three characters slides over xyzzaz one position at a time. xyz is all different and is good. yzz and zza have z twice. In zaz the first and last characters are both z, so the count is 1.

The row labelled "xyz: all different" is the only good one, so the answer is 1. In the rows "yzz: z twice" and "zza: z twice", the repeated letters stand side by side. The last row, "zaz: first and last are both z", is different: the two z's are not neighbours, with the a between them.

So how do we tell, quickly, that three letters are all different? The last row shows that checking neighbours is not enough, because the first and last letter can match too. Three letters make exactly three pairs: first and second, second and third, first and third. If all three pairs differ, the substring is good.

The hole in the card has a usual name in code. A fixed-width frame that moves along an array or string one step at a time is called a sliding window, and here the window is always three characters wide.

Solution Approach

Turning that idea into code means settling two things: how to visit every window of three characters, and how to check one window.

Visiting every window

Which positions does the window take? A window can be named by the index of its last character. The first window ends at index 2, and the last one ends at the last index of the string, so a loop over i from 2 up to the end visits each window once. The window that ends at i holds the characters at i - 2, i - 1 and i.

Moving the window one step at a time means the windows overlap, and that is what the problem asks for. In Example 2, "abc" appears at two positions, and each one is a separate window, so it counts twice. A string shorter than 3 has no window at all, so the loop never runs and the answer is 0.

A simpler but slower way is to cut each substring out with s.substring(i - 2, i + 1) and put its characters into a set. A set keeps one copy of each character, so a set with fewer than 3 characters means a repeat. That builds a new string and a new set for every window. Reading the three characters straight from s builds nothing.

Checking three characters

How should one window be checked? Read the three characters into a, b and c, and test all three pairs: a != b, b != c and a != c. Leaving out the last one lets a window like zaz through.

Longer windows (optional)

What if the window were k characters wide instead of three? Comparing every pair would then take about k²/2 comparisons per window. A better way keeps a count of each character inside the window, plus the number of characters that appear more than once. When the window slides, one character enters and one leaves, so only two counts change. For a width of three, the three comparisons are shorter and just as fast.

Java Solution

The method countGoodSubstrings works in these steps:

  1. First, set count to 0. It holds the number of good windows found so far.
  2. Slide the window with one loop, where i is the index of the window's last character. It starts at 2 and runs to the end of s.
  3. Inside the loop, read the window's three characters into a (at i - 2), b (at i - 1) and c (at i).
  4. If a != b, b != c and a != c all hold, add 1 to count.
  5. When the loop ends, return count.

The main method runs both examples, then "aba" (first and last match), "abcabc" (every window good), "aaaa" (no window good) and "ab" (too short for a window).

Java
public class SubstringsOfSizeThreeWithDistinctCharacters {

    public static int countGoodSubstrings(String s) {
        int count = 0;
        for (int i = 2; i < s.length(); i++) {
            char a = s.charAt(i - 2);         // the window is s[i-2 .. i]
            char b = s.charAt(i - 1);
            char c = s.charAt(i);
            if (a != b && b != c && a != c) {
                count++;
            }
        }
        return count;
    }

    public static void main(String[] args) {
        System.out.println(countGoodSubstrings("xyzzaz"));
        System.out.println(countGoodSubstrings("aababcabc"));
        System.out.println(countGoodSubstrings("aba"));
        System.out.println(countGoodSubstrings("abcabc"));
        System.out.println(countGoodSubstrings("aaaa"));
        System.out.println(countGoodSubstrings("ab"));
    }
}

Running it prints:

Output
1
4
0
4
0
0

The 1 and the 4 at the top match the two examples. Look at the third line: "aba" gives 0, because a != c fails when the first and last characters are both a. With only the two neighbour checks, the same method returns 1 for "aba" and 2 for "xyzzaz", since zaz slips through.

The fourth line is 4 because "abcabc" has four windows, abc, bca, cab and abc, and all of them are good. The last two lines are 0 for different reasons. "aaaa" has two windows, both aaa, while "ab" has none, so the loop never runs.

Complexity

The work is one pass of the window over the string, with a fixed amount of work at each position.

  • Time: O(n), because the window takes n - 2 positions in a string of n characters, and at each one the loop reads three characters and makes at most three comparisons.
  • Space: O(1), because the method keeps only count, i and the three characters a, b and c, and never copies the string or builds substrings.

When the window has no fixed width and must grow and shrink to avoid repeats, keeping a count of each character in the window takes over: see Longest Substring Without Repeating Characters.