Number of Substrings Containing All Three Characters — LeetCode 1358 Python Solution

MediumHash TableStringSliding Window
Problem
#1358
Reading time
2 min

The problem

Given a string s consisting only of characters a, b and c. Return the number of substrings containing at least one occurrence of all these characters a, b and c.

Example

Input
s = "abcabc"
Output
10
Explanation
The substrings containing at least one occurrence of the characters a, b and c are "abc", "abca", "abcab", "abcabc", "bca", "bcab", "bcabc", "cab", "cabc" and "abc" (again).

Python solution

Python
class Solution:
    def numberOfSubstrings(self, s: str) -> int:
        d = {"a": -1, "b": -1, "c": -1}
        ans = 0
        for i, c in enumerate(s):
            d[c] = i
            ans += min(d["a"], d["b"], d["c"]) + 1
        return ans

Complexity

MeasureComplexity
TimeO(n), where n is the length of the string s
SpaceO(1) auxiliary

Pattern: Sliding Window

Collapse a nested loop over every subarray into a single pass with two indices. LeetCode 1358. Number of Substrings Containing All Three Characters is filed here because LeetCode tags it Sliding Window, which is the vocabulary this hub collects.

The sliding window guide has the Python template for the pattern and the 116 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1358. Number of Substrings Containing All Three Characters?
LeetCode 1358. Number of Substrings Containing All Three Characters is rated Medium on LeetCode.
What is the time complexity of LeetCode 1358. Number of Substrings Containing All Three Characters?
The Python solution on this page runs in O(n), where n is the length of the string s.
What is the space complexity of LeetCode 1358. Number of Substrings Containing All Three Characters?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 1358. Number of Substrings Containing All Three Characters cover?
LeetCode 1358. Number of Substrings Containing All Three Characters is tagged Hash Table, String and Sliding Window on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview