✅Tracking Last Occurrences Technique 🔥| Visualization ✨| Math | Python | C++ | Java | C ✨
Approach
Complexity

Time complexity:  O(n)


Space complexity: O(1)

Code
# Approach

![image.png](https://assets.leetcode.com/users/images/c6108a83-abb2-454a-80a8-5a17797ffeb4_1741656827.628542.png)
![image.png](https://assets.leetcode.com/users/images/dfe9a0f3-6edf-4c67-b339-347c35ff26dd_1741656855.2443132.png)

# Complexity
- Time complexity:  $$O(n)$$ 

- Space complexity: $$O(1)$$

# Code
```python []
class Solution(object):
    def numberOfSubstrings(self, s):
        lastSeen = [-1, -1, -1] 
        count = 0 
        for i in range(len(s)):
            lastSeen[ord(s[i]) - ord('a')] = i
            if lastSeen[0] != -1 and lastSeen[1] != -1 and lastSeen[2] != -1:
                count += (1 + min(lastSeen[0], lastSeen[1], lastSeen[2]))
        return count

        
```
```C++ []
class Solution {
public:
    int numberOfSubstrings(string s) {
        vector<int> lastSeen(3, -1);
        int count = 0;

        for (int i = 0; i < s.size(); i++) {
            lastSeen[s[i] - 'a'] = i;
            if (lastSeen[0] != -1 && lastSeen[1] != -1 && lastSeen[2] != -1) {
                count += 1 + min({lastSeen[0], lastSeen[1], lastSeen[2]});
            }
        }
        return count;
    }
};


        
```
```Java []
class Solution {
    public int numberOfSubstrings(String s) {
        int[] lastSeen = {-1, -1, -1};
        int count = 0;

        for (int i = 0; i < s.length(); i++) {
            lastSeen[s.charAt(i) - 'a'] = i;
            if (lastSeen[0] != -1 && lastSeen[1] != -1 && lastSeen[2] != -1) {
                count += 1 + Math.min(lastSeen[0], Math.min(lastSeen[1], lastSeen[2]));
            }
        }
        return count;
    }
}


        
```
```C []
int numberOfSubstrings(char* s) {
    int lastSeen[3] = {-1, -1, -1};
    int count = 0;

    for (int i = 0; s[i] != '\0'; i++) {
        lastSeen[s[i] - 'a'] = i;
        if (lastSeen[0] != -1 && lastSeen[1] != -1 && lastSeen[2] != -1) {
            int minIndex = lastSeen[0];
            if (lastSeen[1] < minIndex) minIndex = lastSeen[1];
            if (lastSeen[2] < minIndex) minIndex = lastSeen[2];
            count += 1 + minIndex;
        }
    }
    return count;
}

        
```

![image.png](https://assets.leetcode.com/users/images/3b502ed1-e211-4e38-bf1d-25df0415b1d2_1741657259.008584.png)

['Array', 'Math', 'C', 'Python', 'C++', 'Java']