Two Pointers | Array | Solution for LeetCode#1358
IntuitionTo find the number of substrings containing all three characters 'a', 'b', and 'c', we can use a sliding window approach. The idea is to expand the win
![image.png](https://assets.leetcode.com/users/images/838c8c4c-1c35-43d0-b017-35c8d0f88980_1741662775.8058112.png)

# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
To find the number of substrings containing all three characters 'a', 'b', and 'c', we can use a sliding window approach. The idea is to expand the window until it contains all three characters, then contract it to find smaller substrings that still meet the criteria.

# Approach
<!-- Describe your approach to solving the problem. -->
1. Initialize a count array to keep track of the occurrences of 'a', 'b', and 'c'.
2. Use two pointers, i and j, to represent the ends of the sliding window.
3. Expand the window by moving i backwards until it contains at least one 'a', 'b', and 'c'.
4. Once all three characters are in the window, move j backwards to find smaller valid substrings. For each valid window, count the number of substrings ending at each position j.
5. Repeat the process until the entire string is processed.

# Complexity
- Time complexity: $$O(n)$$
<!-- Add your time complexity here, e.g. $$O(n)$$ -->

- Space complexity: $$O(1)$$
<!-- Add your space complexity here, e.g. $$O(n)$$ -->

# Code
```java []
class Solution {
    public int numberOfSubstrings(String s) {
        int n=s.length();
        int cnt=0;
        int[] arr=new int[3];

        int i=n-1, j=n-1;
        while(i>=0 && j>=0){
            arr[s.charAt(i)-'a']++;

            while(arr[0]>0 && arr[1]>0 && arr[2]>0){                  
                    cnt+=i+1;  
                    arr[s.charAt(j)-'a']--;
                    j--;                
            }
            i--;
        }

        return cnt;
    }

}
```
```python []
class Solution:
    def numberOfSubstrings(self, s: str) -> int:
        arr=[0]*3
        cnt=0
        n=len(s)

        i=n-1
        j=n-1

        while i>=0 and j>=0:
            arr[ord(s[i])-ord('a')]+=1

            while arr[0]>0 and arr[1]>0 and arr[2]>0:
                cnt+=i+1
                arr[ord(s[j])-ord('a')]-=1
                j-=1
            
            i-=1
        

        return cnt
```


['Python', 'Java', 'Python3']