1460. Number Of Substrings Containing All Three Characters¶
Difficulty: Medium
LeetCode Problem View on GitHub
1460. Number of Substrings Containing All Three Characters
Medium
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^4sonly consists of a, b or c characters.
Solution¶
class Solution {
public int numberOfSubstrings(String s) {
int n = s.length();
HashMap<Character, Integer> map = new HashMap<>();
int left = 0 , right = 0;
int count = 0;
while (left < n) {
while (right < n && map.size() < 3) {
map.put(s.charAt(right) , map.getOrDefault(s.charAt(right) , 0) + 1);
right++;
}
if(map.size() == 3) count += s.length() - (right) + 1;
map.put(s.charAt(left) , map.getOrDefault(s.charAt(left) , 0) -1);
if (map.get(s.charAt(left)) == 0) map.remove(s.charAt(left));
left++;
}
return count;
}
}
Complexity Analysis¶
- Time Complexity:
O(?) - Space Complexity:
O(?)
Approach¶
Detailed explanation of the approach will be added here