Substrings of Size Three with Distinct Characters — LeetCode 1876 Python Solution

EasyHash TableStringCountingSliding Window
Problem
#1876
Reading time
2 min

The problem

A string is good if there are no repeated characters. Given a string s​​​​​, return the number of good substrings of length three in s​​​​​​.

Example

Input
s = "xyzzaz"
Output
1
Explanation
There are 4 substrings of size 3: "xyz", "yzz", "zza", and "zaz".

Python solution

Python
class Solution:
    def countGoodSubstrings(self, s: str) -> int:
        ans = mask = l = 0
        for r, x in enumerate(map(lambda c: ord(c) - 97, s)):
            while mask >> x & 1:
                y = ord(s[l]) - 97
                mask ^= 1 << y
                l += 1
            mask |= 1 << x
            ans += int(r - l + 1 >= 3)
        return ans

Complexity

MeasureComplexity
TimeO(n), where n is the length of the string s
SpaceO(1) auxiliary

Pattern: Sliding Window

Collapse a nested loop over every subarray into a single pass with two indices. LeetCode 1876. Substrings of Size Three with Distinct Characters is filed here because LeetCode tags it Sliding Window, which is the vocabulary this hub collects.

The sliding window guide has the Python template for the pattern and the 116 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1876. Substrings of Size Three with Distinct Characters?
LeetCode 1876. Substrings of Size Three with Distinct Characters is rated Easy on LeetCode.
What is the time complexity of LeetCode 1876. Substrings of Size Three with Distinct Characters?
The Python solution on this page runs in O(n), where n is the length of the string s.
What is the space complexity of LeetCode 1876. Substrings of Size Three with Distinct Characters?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 1876. Substrings of Size Three with Distinct Characters cover?
LeetCode 1876. Substrings of Size Three with Distinct Characters is tagged Hash Table, String, Counting and Sliding Window on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview