Leetcode 1358: Number of Substrings Containing All Three Characters

grid47
grid47
Exploring patterns and algorithms
Jun 24, 2024 6 min read

Given a string s consisting only of characters ‘a’, ‘b’, and ‘c’, your task is to find the number of substrings that contain at least one occurrence of each of the characters ‘a’, ‘b’, and ‘c’.
Problem
Approach
Steps
Complexity
Input: The input consists of a single string `s` containing only the characters 'a', 'b', and 'c'.
Example: "abacabc"
Constraints:
• 3 <= s.length <= 5 x 10^4
• s only consists of characters 'a', 'b', and 'c'.
Output: The output should be an integer representing the number of substrings containing at least one occurrence of 'a', 'b', and 'c'.
Example: 8
Constraints:
• The answer should be a non-negative integer.
Goal: To solve this problem efficiently, use a sliding window technique to track the number of substrings containing at least one of each character.
Steps:
• Define a helper function `atmost` to calculate the number of substrings with at most 'k' distinct characters.
• Subtract the result of `atmost(s, 2)` from `atmost(s, 3)` to get the number of substrings containing at least one 'a', 'b', and 'c'.
Goal: The string `s` can be as long as 50,000 characters, so an efficient approach is necessary.
Steps:
• The input string length is between 3 and 50,000 characters.
• The string consists only of 'a', 'b', or 'c'.
Assumptions:
• The string is guaranteed to contain only the characters 'a', 'b', and 'c'.
• The input will always have a length of at least 3.
Input: "abacabc"
Explanation: The substrings containing at least one of each character 'a', 'b', and 'c' are 'abc', 'abac', 'bac', 'acb', 'cab', 'abcab', 'bca', and 'cabc'. Thus, the result is 8.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus