LeetCode #1358 Medium

Number of Substrings Containing All Three Characters

Number of Substrings Containing All Three Characters is LeetCode 1358 (Medium). The string s uses only the letters a, b and c.

  • Return how many substrings contain at least one a, at least one b and at least one c.
  • With up to 50,000 characters there are over a billion substrings, so they have to be counted without listing them.
Constraints
  • 3 <= s.length <= 5 * 10⁴
  • s only consists of 'a', 'b' or 'c' characters.
sliding-windowstringshashmap
Open on LeetCode ↗
02

Intuition

Fix where the substring ends, at index i. Moving its start further left only adds letters, so once a start works, every start to its left works too. The good starts are 0 up to some latest start.

That latest start is the smallest of the three last-seen positions of a, b and c up to i. Start one step later and you skip the only remaining copy of that letter. So exactly min(last) + 1 substrings end at i.

Keep the three positions as you scan and add min(last) + 1 at every index. A letter not seen yet has position −1, which adds 0, as it should.

How to spot this pattern

"Count substrings that contain at least one of each" is monotone: once a substring qualifies, stretching it keeps it qualified. Counting by the end index, with the latest start that still qualifies, turns it into one pass.

03

Approach

Try it first

Before reading on, fix the end of a substring at index i and ask which start points give a substring with all three letters. Is there a pattern in which starts work? Then think about what you need to remember to find the last start that works.

1

Start with no letter seen

Set last = [-1, -1, -1] for a, b and c, and total = 0. −1 means the letter has not appeared yet, and it makes the count below come out to 0 for free.

2

Record the current letter first

At index i, set the current letter's entry in last to i. The substring ends at i, so this letter is inside it, and its latest copy is here.

3

Add the substrings that end here

Add min(last) + 1 to total. Starts 0 through min(last) each keep at least one copy of every letter, which is min(last) + 1 substrings; any later start loses the letter with the oldest last copy.

4

Return the total

Each substring is counted once, at the index where it ends, so after the scan total is the answer. One pass with three integers is all it takes.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def numberOfSubstrings(self, s: str) -> int:
▶3 last = [-1, -1, -1]
▶4 total = 0
▶5 for i, ch in enumerate(s):
▶6 last[ord(ch) - ord("a")] = i
▶7 total += min(last) + 1
▶8 return total
a0b1c2a3b4c5last seen—a—b—csmallest + 1+1=total0no letter seen yet
lastnone, none, none
total0
Every substring will be counted at the index where it ends. For that we only need where a, b and c were last seen; none has appeared yet.
a0b1c2a3b4c5last0 startslast seen0a—b—csmallest + 1-1+1=0total0no b or c yet → add 0
letteralast seen at 0
smallest-1
total0
a is now last seen at 0. No b or c has appeared yet, so no substring ending here can hold all three letters; the smallest position is −1 and this index adds 0.
a0b1c2a3b4c5lastlast0 startslast seen0a1b—csmallest + 1-1+1=0total0no c yet → add 0
letterblast seen at 1
smallest-1
total0
b is now last seen at 1. No c has appeared yet, so no substring ending here can hold all three letters; the smallest position is −1 and this index adds 0.
a0b1c2a3b4c5lastlastlast1 startlast seen0a1b2csmallest + 10+1=1total1ends at 2: 1 start → add 1
letterclast seen at 2
smallest0
total1
c is now last seen at 2. The oldest last copy is the a at index 0. Any start from 0 to 0 keeps it inside, so 1 substring ends here; a start after 0 would lose that a.
a0b1c2a3b4c5lastlastlast2 startslast seen3a1b2csmallest + 11+1=2total3ends at 3: 2 starts → add 2
letteralast seen at 3
smallest1
total3
a is now last seen at 3. The oldest last copy is the b at index 1. Any start from 0 to 1 keeps it inside, so 2 substrings end here; a start after 1 would lose that b.
a0b1c2a3b4c5lastlastlast3 startslast seen3a4b2csmallest + 12+1=3total6ends at 4: 3 starts → add 3
letterblast seen at 4
smallest2
total6
b is now last seen at 4. The oldest last copy is the c at index 2. Any start from 0 to 2 keeps it inside, so 3 substrings end here; a start after 2 would lose that c.
a0b1c2a3b4c5lastlastlast4 startslast seen3a4b5csmallest + 13+1=4total10ends at 5: 4 starts → add 4
letterclast seen at 5
smallest3
total10
c is now last seen at 5. The oldest last copy is the a at index 3. Any start from 0 to 3 keeps it inside, so 4 substrings end here; a start after 3 would lose that a.
a0b1c2a3b4c5last seen3a4b5csmallest + 1+1=total10answer: 10
answer10
Each valid substring was counted once, at its end index, so the answer is 10.
05

Common pitfalls

Starting the last-seen positions at 0

✗ Wrong
last = [0, 0, 0]
✓ Right
last = [-1, -1, -1]

0 claims every letter was already seen at index 0. For s = "aaa" no substring has all three letters, but each index adds 0 + 1, so the code returns 3 instead of 0.

Dropping the + 1

✗ Wrong
total += min(last)
✓ Right
total += min(last) + 1

Positions start at 0, so starts 0 through min(last) are min(last) + 1 choices. For s = "abc" the only valid substring is the whole string, but min(last) is 0 there and the code returns 0.

Counting before recording the current letter

✗ Wrong
total += min(last) + 1
last[ord(ch) - ord("a")] = i
✓ Right
last[ord(ch) - ord("a")] = i
total += min(last) + 1

The current letter is part of every substring that ends here. Counting first ignores it: for s = "abc" the c at index 2 is still marked unseen when the count is taken, so the answer comes out 0 instead of 1.

06

Edge cases

One letter never appears, like "aabb"

That letter's position stays −1 for the whole scan, so every index adds 0 and the answer is 0. The tracer's third example shows it.

07

Complexity

Time
O(n)
Space
O(1)
One pass over the string with constant work per character: one write and a minimum of three numbers. The answer for 50,000 characters is at most about 1.25 × 10⁹, which still fits in a 32-bit int.
08

Number of Substrings Containing All Three Characters FAQ

Can a sliding window solve it too?

Yes. Grow the right end and keep letter counts; while the window holds all three letters, shrink it from the left. After shrinking, every start before left was valid for this end, so add left to the total. It is also O(n), but needs an inner loop and a count array.

What if every one of k letters had to appear?

Keep the last position of each of the k letters and add the smallest one plus 1 at each index. The idea is unchanged; only finding the minimum costs O(k) per character, unless the positions are kept in an ordered structure.