Skip to main content
Back to problems
Leetcode
Medium
Arrays
Strings
Hash Maps
Google
Number Of Substrings Containing All Three Characters

Count how many substrings contain at least one of each of the characters 'a', 'b', and 'c'.

Acceptance 100%
Problem Statement

Problem

Given a string s consisting only of the characters 'a', 'b', and 'c', count the number of substrings that contain all three characters at least once.

A substring is a contiguous block of characters within the string.

Your task is to return the total number of valid substrings.

Notes

  • A substring is valid if it includes at least one 'a', one 'b', and one 'c'.
  • You should count every distinct substring by its start and end positions.

Input Format

  • A single string s
  • s contains only the letters 'a', 'b', and 'c'

Output Format

  • Return an integer: the number of substrings of s that contain all three characters

Constraints

  • 1 <= |s| <= $10^{5}$
  • s[i] ∈ {'a', 'b', 'c'}
Examples
Sample cases returned by the problem API.

Example 1

Input

s = "abcabc"

Output

10

Explanation

Valid substrings include "abc", "abca", "abcab", "abcabc", "bca", "bcab", "bcabc", "cab", "cabc", and another "abc" starting later.

Example 2

Input

s = "aaacb"

Output

3

Explanation

The valid substrings are "aaacb", "aacb", and "acb".

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.