Solving Leetcode Interviews in Seconds with AI: Number of Substrings Containing All Three Characters
Introduction
In this blog post, we will explore how to solve the LeetCode problem "1358" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.
Problem Statement
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 1: 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). Example 2: Input: s = "aaacb" Output: 3 Explanation: The substrings containing at least one occurrence of the characters a, b and c are "aaacb", "aacb" and "acb". Example 3: Input: s = "abc" Output: 1 Constraints: 3 <= s.length <= 5 x 10^4 s only consists of a, b or c characters.
Explanation
Here's a breakdown of the approach and the Python code:
- Sliding Window: Use a sliding window to efficiently find substrings containing 'a', 'b', and 'c'. The window expands to the right until it contains all three characters, and then it contracts from the left while maintaining that condition.
- Counting Valid Substrings: For each right endpoint of the sliding window, the number of valid substrings ending at that endpoint is determined by how far the left endpoint can be moved to the right while still containing 'a', 'b', and 'c'.
Efficient Character Tracking: Use a dictionary or array to keep track of the counts of 'a', 'b', and 'c' within the current window.
Runtime Complexity: O(n), where n is the length of the string. Storage Complexity: O(1) (constant space for character counts).
Code
def number_of_substrings(s: str) -> int:
"""
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.
"""
count = 0
left = 0
char_counts = {'a': 0, 'b': 0, 'c': 0}
for right in range(len(s)):
char_counts[s[right]] += 1
while (char_counts['a'] > 0 and
char_counts['b'] > 0 and
char_counts['c'] > 0):
count += len(s) - right # All substrings from left to the end are valid
char_counts[s[left]] -= 1
left += 1
return count