MediumNo. 2981
Find Longest Special Substring That Occurs Thrice I — LeetCode 2981 Python Solution
- Pattern
- Sliding Window
- Topics
- Hash Table, String, Binary Search, Counting, 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
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
- Time
- O((n + |Σ|) × log n)
- Space · auxiliary
- O(|Σ|), where n is the length of the string s, and |Σ| represents the size of the character set
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
| No. | Problem | Difficulty |
|---|---|---|
| 2982 | Find Longest Special Substring That Occurs Thrice II | Medium |
| 1876 | Substrings of Size Three with Distinct Characters | Easy |
| 0003 | Longest Substring Without Repeating Characters | Medium |
| 0030 | Substring with Concatenation of All Words | Hard |
| 0076 | Minimum Window Substring | Hard |
| 0187 | Repeated DNA Sequences | Medium |
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 + |Σ|) × 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(|Σ|), 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.