diff --git a/Daily Questions/#1358 - Number of Substrings Containing All Three Characters - Medium/Explanation.md b/Daily Questions/#1358 - Number of Substrings Containing All Three Characters - Medium/Explanation.md new file mode 100644 index 0000000..41f5798 --- /dev/null +++ b/Daily Questions/#1358 - Number of Substrings Containing All Three Characters - Medium/Explanation.md @@ -0,0 +1,14 @@ +# Solution Explanation + +## Purpose +The code is designed to count the number of substrings that contain all three characters 'a', 'b', and 'c' at least once. + +## Code Breakdown + +### Initialization +```java +HashMap freq = new HashMap<>(); +int left = 0, cnt = 0; + +Time complexity: O(n) +Space complexity: O(n) \ No newline at end of file diff --git a/Daily Questions/#1358 - Number of Substrings Containing All Three Characters - Medium/Solution.java b/Daily Questions/#1358 - Number of Substrings Containing All Three Characters - Medium/Solution.java new file mode 100644 index 0000000..7f35070 --- /dev/null +++ b/Daily Questions/#1358 - Number of Substrings Containing All Three Characters - Medium/Solution.java @@ -0,0 +1,21 @@ +class Solution { + public int numberOfSubstrings(String s) { + HashMap freq = new HashMap<>(); + int left = 0, cnt = 0; + + for (int i = 0; i < s.length(); i++) { + freq.put(s.charAt(i), freq.getOrDefault(s.charAt(i), 0) + 1); + + while (freq.size() == 3) { + cnt += s.length() - i; + freq.put(s.charAt(left), freq.get(s.charAt(left)) - 1); + if (freq.get(s.charAt(left)) == 0) { + freq.remove(s.charAt(left)); + } + left++; + } + } + + return cnt; + } +} \ No newline at end of file