Find Longest Special Substring That Occurs Thrice I — LeetCode 2981 Python Solution
MediumHash TableStringBinary SearchCountingSliding Window
- Problem
- #2981
- Pattern
- Sliding Window
- Reading time
- 4 min
- Source
- leetcode.com
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 lComplexity
| Measure | Complexity |
|---|---|
| Time | O((n + |\Sigma|) \times \log n) |
| Space | O(|\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
LeetCode 2982Find Longest Special Substring That Occurs Thrice IIMediumLeetCode 1876Substrings of Size Three with Distinct CharactersEasyLeetCode 3Longest Substring Without Repeating CharactersMediumLeetCode 30Substring with Concatenation of All WordsHardLeetCode 76Minimum Window SubstringHardLeetCode 187Repeated DNA SequencesMedium
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.