Number of Substrings Containing All Three Characters

MediumSliding Windowsliding window

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

You are given a string s made only of the characters 'a', 'b', and 'c'. Count the substrings (contiguous, non-empty) that contain **at least one** of each of the three characters. Substrings at different positions are counted separately even if their text is identical. Return the count. An O(n) solution is expected.

Examples

Input: s = "abcabc"
Output: 10
Starting at index 0 there are 4 valid substrings (abc, abca, abcab, abcabc), at index 1 there are 3, at index 2 there are 2, and at index 3 there is 1.
Input: s = "aaacb"
Output: 3
The valid substrings are aaacb, aacb, and acb.
Input: s = "abc"
Output: 1
Only the whole string contains all three characters.

Constraints

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

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More sliding window problems