oneby7

Sliding Window Counting windows

184. Number of Substrings Containing All Three Characters

Medium

You are given a string s made of the letters a, b and c. Return the number of substrings of s that hold each of the three letters at least once.

A substring is a block of letters that sit next to each other in s, with at least one letter. Two substrings are different if they start or end at different positions, even when they hold the same letters.

Example 1

Input: s = "abcba"

Output: 5

Explanation: Five substrings hold all three letters: abc, abcb, abcba, bcba and cba. The others, such as bcb, miss a letter.

Example 2

Input: s = "aaacb"

Output: 3

Explanation: A substring with all three letters must reach the b at the end and start at one of the three as. That gives aaacb, aacb and acb.

Example 3

Input: s = "ccbcbb"

Output: 0

Explanation: The string has no a, so no substring holds all three letters.

Check your understanding

Work out the answer for this input before you write any code.

s = "abcabc"

Constraints

  • 1 ≤ s.length ≤ 105
  • s holds only the letters a, b and c.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.