Count Substrings Without Repeating Character — LeetCode 2743 Python Solution

MediumLeetCode PremiumHash TableStringSliding Window
Problem
#2743
Reading time
2 min

The problem

You are given a string s consisting only of lowercase English letters. We call a substring special if it contains no character which has occurred at least twice (in other words, it does not contain a repeating character).

Example

Input
s = "abcd"
Output
10
Explanation
Since each character occurs once, every substring is a special substring. We have 4 substrings of length one, 3 of length two, 2 of length three, and 1 substring of length four. So overall there are 4 + 3 + 2 + 1 = 10 special substrings.

Python solution

Python
class Solution:
    def numberOfSpecialSubstrings(self, s: str) -> int:
        cnt = Counter()
        ans = j = 0
        for i, c in enumerate(s):
            cnt[c] += 1
            while cnt[c] > 1:
                cnt[s[j]] -= 1
                j += 1
            ans += i - j + 1
        return ans

Complexity

MeasureComplexity
TimeO(n)
SpaceO(C) auxiliary

Pattern: Sliding Window

Collapse a nested loop over every subarray into a single pass with two indices. LeetCode 2743. Count Substrings Without Repeating Character 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 2743. Count Substrings Without Repeating Character?
LeetCode 2743. Count Substrings Without Repeating Character is rated Medium on LeetCode.
What is the time complexity of LeetCode 2743. Count Substrings Without Repeating Character?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 2743. Count Substrings Without Repeating Character?
The Python solution on this page uses O(C) auxiliary space.
What topics does LeetCode 2743. Count Substrings Without Repeating Character cover?
LeetCode 2743. Count Substrings Without Repeating Character is tagged Hash Table, String and Sliding Window on LeetCode.
Is LeetCode 2743. Count Substrings Without Repeating Character a premium problem?
Yes. LeetCode 2743. Count Substrings Without Repeating Character is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

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