2025-03-11 Daily Challenge

Today I have done leetcode's March LeetCoding Challenge with cpp.

March LeetCoding Challenge 11

Description

Number of Substrings Containing All Three Characters

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 ab 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 ab 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 characters.

Solution

class Solution {
public:
  int numberOfSubstrings(string s) {
    unordered_map<char, int> count;
    int begin = 0;
    int answer = 0;
    for(int end = 0; end < s.length(); ++end) {
      count[s[end]] += 1;

      if(count.size() < 3) continue;

      while(count.size() == 3) {
        answer += s.length() - end;
        count[s[begin]] -= 1;
        if(!count[s[begin]]) count.erase(s[begin]);
        begin += 1;
      }
    }
    return answer;
  }
};

// Accepted
// 54/54 cases passed (48 ms)
// Your runtime beats 5.72 % of cpp submissions
// Your memory usage beats 14.74 % of cpp submissions (16.6 MB)