Back to June Back to Year 2026
MEDIUM 30 Jun 2026 View on LeetCode

1358. Number of Substrings Containing All Three Characters

</> Solution

/**
 * Problem: LeetCode 1358 - Number of Substrings Containing All Three Characters
 * Difficulty: Medium
 * Language: Java
 * Author: CodeByTushu
 */
class Solution {
    public int numberOfSubstrings(String s) {
        int[] count = new int[3];
        int left = 0;
        int ans = 0;

        for (int right = 0; right < s.length(); right++) {
            count[s.charAt(right) - 'a']++;

            while (count[0] > 0 && count[1] > 0 && count[2] > 0) {
                ans += s.length() - right;
                count[s.charAt(left) - 'a']--;
                left++;
            }
        }

        return ans;
    }
}

TIME COMPLEXITY

O(N)

SPACE COMPLEXITY

O(1)

TOPICS

Hash Table Sliding Window String