Find Longest Special Substring That Occurs Thrice II - Problem
Find the Longest Repeating Character Substring
You are given a string
A special substring is one that contains only a single unique character. For example:
•
•
•
Goal: Return the length of the longest special substring that occurs at least 3 times, or
Example: In
You are given a string
s consisting of lowercase English letters. Your task is to find the longest special substring that appears at least 3 times in the string.A special substring is one that contains only a single unique character. For example:
•
"aaa" is special (only 'a')•
"bb" is special (only 'b')•
"abc" is NOT special (multiple characters)Goal: Return the length of the longest special substring that occurs at least 3 times, or
-1 if no such substring exists.Example: In
"aaabbbccc", the substring "aa" appears 2 times, but "a" appears 3 times, so the answer is 1. Input & Output
example_1.py — Basic Case
$
Input:
s = "aaaa"
›
Output:
2
💡 Note:
The string "aaaa" has special substrings: "a" (appears 4 times), "aa" (appears 3 times), "aaa" (appears 2 times), "aaaa" (appears 1 time). The longest that appears at least 3 times is "aa" with length 2.
example_2.py — Mixed Characters
$
Input:
s = "abcdef"
›
Output:
-1
💡 Note:
No character repeats consecutively, so the only special substrings are single characters, each appearing exactly once. Since we need at least 3 occurrences, the answer is -1.
example_3.py — Multiple Groups
$
Input:
s = "abcaba"
›
Output:
1
💡 Note:
Character 'a' appears 3 times (positions 0, 3, 5) and character 'b' appears 2 times. Only 'a' appears at least 3 times, so the answer is 1.
Constraints
- 3 ≤ s.length ≤ 5 × 104
- s consists of only lowercase English letters
- Need at least 3 occurrences of the special substring
Visualization
Tap to expand
Understanding the Visualization
1
Scan & Group
Identify consecutive character sequences: 'aaabaa' → groups: [3,3] for 'a', [1] for 'b'
2
Track Top 3
Keep only the 3 longest sequences for each character (pad with zeros if needed)
3
Calculate Maximum
For each character, find max length appearing ≥3 times using three formulas
4
Return Best
Take the maximum result across all character types
Key Takeaway
🎯 Key Insight: We only need the top 3 consecutive lengths per character because there are exactly 3 ways to form 3 occurrences, and shorter substrings can always be derived from longer ones mathematically!
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code