Number of Substrings Containing All Three Characters (LeetCode 1358): Solution and Explanation

Medium
Hash Table
String
Sliding Window

Given a string of the letters a, b and c, count the substrings that contain each of the three letters at least once.

Intuition

Count substrings by their end index i. If a substring ending at i contains all three letters, then making it longer on the left keeps all three letters. So the good starts for end i are exactly 0..p for some cutoff p.

The cutoff is the latest start that still reaches every letter. A substring s[p..i] has an a only if p is at or before the most recent a, and the same for b and c.

So p = min(last_a, last_b, last_c), and end i adds p + 1 substrings. While a letter has not appeared, its last index is -1, which makes the contribution 0 with no special case.

This is a sliding window in disguise: p + 1 is the left edge the shrinking-window solution would reach, but here three numbers replace the whole window.

Approach: Last-seen positions

  1. Set last = [-1, -1, -1] for a, b and c, and count = 0.
  2. For each index i, set last[s[i] - 'a'] = i.
  3. Add min(last) + 1 to count.
  4. Return count.

Step-by-step example

s = "abcabc"
  1. i = 0 and i = 1: only a and b are seen, so min(last) = -1 and nothing is added.
  2. i = 2 ('c'): last = [0, 1, 2], min 0, add 1 ("abc"). count = 1.
  3. i = 3 ('a'): last = [3, 1, 2], min 1, add 2. count = 3.
  4. i = 4 ('b'): last = [3, 4, 2], min 2, add 3. count = 6.
  5. i = 5 ('c'): last = [3, 4, 5], min 3, add 4. count = 10, the answer.

Code: Python, Java, C++

1class Solution:
2    def numberOfSubstrings(self, s: str) -> int:
3        last = [-1, -1, -1]
4        count = 0
5        for i, ch in enumerate(s):
6            last[ord(ch) - ord('a')] = i
7            count += min(last) + 1
8        return count
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

Each character is handled once with a constant amount of work.

Space

O(1)

Only three positions and a counter are stored.

Other approaches

Shrinking window with letter counts (time O(n), space O(1))

Grow a window to the right and keep counts of a, b and c. While all three counts are positive, every end from right to the end of the string works, so add n - right and shrink from the left.

Complement counting (time O(n), space O(1))

Count all n(n+1)/2 substrings and subtract those missing at least one letter, using inclusion-exclusion over runs that avoid a letter. Correct but harder to get right.

Check every substring (time O(n^2), space O(1))

For each start, extend the end until all three letters appear; then every longer end works too. Without that shortcut it is cubic, with it quadratic.

Common mistakes

  • Adding min(last) instead of min(last) + 1. Starts are 0-based, so cutoff p allows p + 1 starts.
  • Starting last at 0 instead of -1, which counts substrings before a letter has appeared.
  • Counting with the shrinking window and adding right - left + 1 instead of the number of valid starts or ends.
  • Assuming the answer is small: for 50,000 characters it can exceed a billion, close to the 32-bit limit.

Frequently asked questions

Why is the number of valid starts min(last) + 1?

A start p works when p is at or before the latest a, the latest b and the latest c. The tightest of those is the smallest one, and starts 0 through it make min(last) + 1 options.

How does this extend to more letters?

Keep one last-seen index per required letter and add the minimum plus one. For many letters, a shrinking window with counts is often simpler than taking a minimum over a large array.

Is this really a sliding window problem?

Yes. The minimum of the last positions is where the left edge of the shortest valid window ending at i sits, so the solution tracks a window without moving a pointer explicitly.