Problem 1358

Abstract / Summary

Count the number of substrings in a string that include at least one of each of three given characters.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1358.py

class Solution:
    def numberOfSubstrings(self, s: str) -> int:
        result = 0

        freq = { "a": 0, "b": 0, "c": 0 }

        right = 0
        for left in range(len(s)):
            # find minimal string starting at "left"
            while right < len(s) and freq["a"] * freq["b"] * freq["c"] == 0: # zero if at least one counter is zero
                freq[s[right]] += 1
                right          += 1

            # no more valid strings
            if freq["a"] * freq["b"] * freq["c"] == 0:
                break

            # all strings from "right" to the end are valid
            result += len(s) - right + 1
            freq[s[left]] -= 1

        return result
22 lines | 714 bytes | submitted December 7, 2023 | GitHub   28% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 74% (800k+ submissions).

Typical patterns to solve this problem:
  • Hash Table
  • Sliding Window
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation solves the problem of counting substrings that contain at least one occurrence of each character 'a', 'b', and 'c'. It employs a sliding-window technique with two pointers, left and right, that move through the input string exactly once. Frequency counters for the three required characters are maintained in a dictionary, allowing the algorithm to determine when a window satisfies the “all three characters present” condition. When such a window is found, the number of valid substrings that start at the current left index is added to the result in constant time.

Key Steps

Initialization

The function begins by setting up the result accumulator, a frequency map for the three characters, and the right-hand pointer. The frequency map starts with zero counts for 'a', 'b', and 'c'.

result = 0
freq = { "a": 0, "b": 0, "c": 0 }
right = 0

Expanding the Right Pointer

For each possible starting position left, the algorithm expands the right pointer until the current window contains at least one of each required character. The condition freq["a"] * freq["b"] * freq["c"] == 0 evaluates to true as long as any count is zero, so the loop continues while the window is incomplete.

while right < len(s) and freq["a"] * freq["b"] * freq["c"] == 0:
    freq[s[right]] += 1
    right += 1

Early Termination

If the right pointer reaches the end of the string without satisfying the condition, the outer loop terminates because no further substrings can meet the requirement. This handles the edge case where the remaining suffix of the string lacks at least one of the three characters.

if freq["a"] * freq["b"] * freq["c"] == 0:
    break

Counting Valid Substrings

When the window first becomes valid, every extension of the window to the right (including the current right position) also remains valid because adding characters cannot remove the presence of 'a', 'b', or 'c'. Therefore, the number of substrings that start at left and satisfy the condition equals the number of possible right endpoints, which is len(s) - right + 1. This value is added directly to the result.

result += len(s) - right + 1

Shrinking from the Left

Before moving to the next left index, the algorithm decrements the count of the character that is being left behind. This prepares the frequency map for the next iteration without recomputing the entire window.

freq[s[left]] -= 1

Final Return

After iterating through all possible starting positions, the accumulated result is returned.

return result

Edge Cases Handled

The code gracefully manages several boundary conditions:

  • Empty Input - When s is an empty string, the outer loop never executes, and the function returns 0, correctly indicating that no substrings exist.
  • Missing Characters - If the input lacks any one of 'a', 'b', or 'c', the inner while loop will eventually exhaust the string without satisfying the product condition. The subsequent break exits the outer loop, yielding a result of 0.
  • Single-Character Strings - For strings of length one, the same logic applies: the product condition fails, the loop breaks, and the result remains 0.
  • Repeated Characters - When a character appears many times consecutively, the sliding window still expands only until the first occurrence of each required character, avoiding unnecessary work.

Performance Optimizations

The implementation incorporates several subtle optimizations that keep the execution efficient:

  • Single Pass with Two Pointers - By never resetting the right pointer for each new left, the algorithm ensures that each character of the string is visited at most twice, once when entering the window and once when leaving it.
  • Compact Condition Check - Using the product freq["a"] * freq["b"] * freq["c"] to test for the presence of all three characters reduces the number of logical operations compared to checking each count individually.
  • Constant-Time Contribution Calculation - Once a valid window is identified, the number of qualifying substrings is computed with a simple arithmetic expression, avoiding any inner loops or additional scans.
  • In-Place Frequency Updates - The frequency dictionary is updated incrementally as the window slides, eliminating the need for auxiliary data structures or recomputation of counts for each new window.
written by openai gpt

ELI5 - Simplified Explanation

Imagine a long train track made of letter blocks like a, b, and c connected in a row. The goal is to count every possible tunnel you can build that captures at least one of each letter.

First, think of two friends holding markers on the track. One friend stands at the start and the other friend walks forward to find a group of blocks that contains at least one a, one b, and one c. Once they find a group that has all three, they stop and look at how many blocks are left over at the end of the track. Because that group is already complete with the three letters, any larger group that includes those extra blocks at the end will also be a winner.

The first friend then steps forward to shrink the group from the other side, and the second friend starts moving forward again to see if they can find another set. This keeps happening until the whole track has been checked, carefully toting up every single valid group found along the way. It is like putting together a puzzle by sliding a window across the line to see how many different ways those letters can be grouped together.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 7.41 | σ = 1.25

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Java Python TS
WalkCCC C++ Java Python
leetcode.ca C++ Java Go Python Rust TS
Progiez C++ Java Python
github black-shadows C++
charles-wangkai Java
fartem Ruby
fsq C++
JoshCrozier JS
lzl124631x C++
Shamik07 Dart
varunu28 Java
wisdompeak C++
withaarzoo C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, Rust, TypeScript
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
fartem Ruby
fsq C++
JoshCrozier JavaScript
lzl124631x C++
Shamik07 Dart
varunu28 Java
wisdompeak C++
withaarzoo C++
26 links | 14 authors | 9 languages

Videos

7 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

6 solutions   December 7, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality