Find Longest Special Substring That Occurs Thrice I — LeetCode 2981 Python Solution

MediumHash TableStringBinary SearchCountingSliding Window
Problem
#2981
Reading time
4 min

The problem

You are given a string s that consists of lowercase English letters. A string is called special if it is made up of only a single character.

Example

Input
s = "aaaa"
Output
2
Explanation
The longest special substring which occurs thrice is "aa": substrings "aaaa", "aaaa", and "aaaa".

Python solution

Python
class Solution:
    def maximumLength(self, s: str) -> int:
        def check(x: int) -> bool:
            cnt = defaultdict(int)
            i = 0
            while i < n:
                j = i + 1
                while j < n and s[j] == s[i]:
                    j += 1
                cnt[s[i]] += max(0, j - i - x + 1)
                i = j
            return max(cnt.values()) >= 3

        n = len(s)
        l, r = 0, n
        while l < r:
            mid = (l + r + 1) >> 1
            if check(mid):
                l = mid
            else:
                r = mid - 1
        return -1 if l == 0 else l

Complexity

MeasureComplexity
TimeO((n + |\Sigma|) \times \log n)
SpaceO(|\Sigma|), where n is the length of the string s, and |\Sigma| represents the size of the character set auxiliary

Pattern: Sliding Window

Collapse a nested loop over every subarray into a single pass with two indices. LeetCode 2981. Find Longest Special Substring That Occurs Thrice I 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 2981. Find Longest Special Substring That Occurs Thrice I?
LeetCode 2981. Find Longest Special Substring That Occurs Thrice I is rated Medium on LeetCode.
What is the time complexity of LeetCode 2981. Find Longest Special Substring That Occurs Thrice I?
The Python solution on this page runs in O((n + |\Sigma|) \times \log n).
What is the space complexity of LeetCode 2981. Find Longest Special Substring That Occurs Thrice I?
The Python solution on this page uses O(|\Sigma|), where n is the length of the string s, and |\Sigma| represents the size of the character set auxiliary space.
What topics does LeetCode 2981. Find Longest Special Substring That Occurs Thrice I cover?
LeetCode 2981. Find Longest Special Substring That Occurs Thrice I is tagged Hash Table, String, Binary Search, 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