Number of Substrings Containing All Three Characters — LeetCode 1358 Python Solution
MediumHash TableStringSliding Window
- Problem
- #1358
- Pattern
- Sliding Window
- Reading time
- 2 min
- Source
- leetcode.com
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n), where n is the length of the string s |
| Space | O(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
LeetCode 3Longest Substring Without Repeating CharactersMediumLeetCode 30Substring with Concatenation of All WordsHardLeetCode 76Minimum Window SubstringHardLeetCode 187Repeated DNA SequencesMediumLeetCode 395Longest Substring with At Least K Repeating CharactersMediumLeetCode 424Longest Repeating Character ReplacementMedium
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.