Number of Substrings Containing All Three Characters

Sliding Window / 2 Pointer Counting Subarrays / Substrings Problems Hard

Given a string s , consisting only of characters 'a' , 'b' , 'c'.Find the number of substrings that contain at least one occurrence of all these characters 'a' , 'b' , 'c'.

Examples:

Input : s = "abcba"

Output : 5

Explanation : The substrings containing at least one occurrence of the characters 'a' , 'b' , 'c' are "abc" , "abcb" , "abcba" , "bcba" , "cba".

Input : s = "ccabcc"

Output : 8

Explanation : The substrings containing at least one occurrence of the characters 'a' , 'b' , 'c' are "ccab" , "ccabc" , "ccabcc" , "cab" , "cabc" , "cabcc" , "abc" , "abcc".

Input : s = "abccba"

Constraints

  • 1 <= s.length <= 5*104
  • s consist only of characters 'a' , 'b' , 'c'.

Hints

  • Use a sliding window to determine all substrings that contain at least one occurrence of the characters 'a', 'b', and 'c'.
  • Maintain a frequency map (or array of size 3, one for each of 'a', 'b', and 'c') to track the count of each character in the current window.

Company Tags

Micron Technology ARM Optum Ernst & Young Western Digital Flipkart Ubisoft Salesforce Roche Dropbox Epic Games Goldman Sachs Epic Systems Zomato Philips Healthcare McKinsey & Company Splunk Intel Cloudflare Snowflake Roblox NVIDIA Instacart eBay Activision Blizzard Google Microsoft Amazon Meta Apple Netflix Adobe