Leetcode 1460 Solution

This article provides solution to leetcode question 1460 (number-of-substrings-containing-all-three-characters)

https://leetcode.com/problems/number-of-substrings-containing-all-three-characters

Solution

class Solution:
    def numberOfSubstrings(self, s: str) -> int:
        l = 0
        r = -1

        m = collections.defaultdict(int)
        ans = 0

        while l <= len(s) - 3:
            while r < len(s) - 1 and len(m) < 3:
                r += 1
                m[s[r]] += 1

            if len(m) == 3:
                ans += len(s) - r

            m[s[l]] -= 1
            if m[s[l]] == 0:
                del m[s[l]]
            l += 1

        return ans