Created
March 11, 2025 18:56
-
-
Save tatsuyax25/670447db3268d5b5f1f1675ee568a7b6 to your computer and use it in GitHub Desktop.
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @param {string} s - Input string containing characters 'a', 'b', and 'c' | |
* @return {number} - Number of substrings containing at least one 'a', 'b', and 'c' | |
*/ | |
var numberOfSubstrings = function(s) { | |
let count = 0; // To keep track of the number of unique characters 'a', 'b', and 'c' in the current window | |
let map = {'a': 0, 'b': 0, 'c': 0}; // Map to store the count of each character 'a', 'b', and 'c' | |
let res = 0; // To store the result (number of substrings) | |
let l = 0; // Left pointer for the sliding window | |
// Loop through each character in the string with the right pointer | |
for (let r = 0; r < s.length; r++) { | |
if (s[r] in map) { | |
// If the character at position 'r' is in the map, increment its count | |
if (map[s[r]] === 0) count++; | |
map[s[r]]++; | |
} | |
// If all three characters 'a', 'b', and 'c' are in the current window | |
while (count === 3) { | |
// Add the number of substrings ending at position 'r' | |
res += s.length - r; | |
map[s[l]]--; | |
if (map[s[l]] === 0) count--; // Decrement the count if a character count reaches zero | |
l++; // Move the left pointer to the right | |
} | |
} | |
return res; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment