Number of Substrings Containing All Three Characters

medium

Given a string s consisting only of the characters a, b, and c, return the number of substrings that contain at least one occurrence of each of a, b, and c.

Hints

Instead of measuring a window, count how many valid substrings end at each index.
A substring ending at i contains all three iff it starts at or before the earliest recent position of a, b, c.
Keep last[a], last[b], last[c] and add min(last) + 1 for each index.

Common doubts

Validity is monotone in the start: once a substring has all three, extending it left keeps them. So valid starts form a prefix, and their count is min(last) + 1.
To include all three characters, the start can't be later than the most recent occurrence of the rarest-to-appear one — i.e. the minimum of the three last indices.
Its last index is -1, so min(last) is -1 and the count contributed is 0 — correct, since no valid substring exists yet.

Interview follow-ups

Expand right; once the window has all three, every start <= left is valid, so add left to the total, shrinking to keep the invariant.
Same idea with an array of K last-seen indices, adding min(last) + 1 per right endpoint.

Fun facts

  • Counting per right endpoint — 'how many valid windows end here?' — is the second core sliding-window mode, alongside 'how long is the best window?'.
  • The last-seen-index trick reappears in problems like 'longest substring without repeats' as a way to jump the left pointer.

Asked at

AmazonGoogleMicrosoft
Frequently Sometimes Occasionally
Example 1
Input: s = "abcabc"
Output: 10
There are 10 substrings that contain at least one a, one b, and one c.
Example 2
Input: s = "aaacb"
Output: 3
The valid substrings are "aacb", "acb", and "aaacb".
Constraints

- 3 <= s.length <= 5 * 10^4 - s consists only of characters a, b and c.

Solve this problem →