Find Longest Special Substring That Occurs Thrice II - 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. For example, the string "abc" is not special, whereas the strings "ddd", "zz", and "f" are special.
Return the length of the longest special substring of s which occurs at least thrice, or -1 if no special substring occurs at least thrice.
A substring is a contiguous non-empty sequence of characters within a string.
Input & Output
Example 1 — Basic Case
$
Input:
s = "aaaa"
›
Output:
2
💡 Note:
Special substrings: "a" appears 4 times, "aa" appears 3 times, "aaa" appears 2 times, "aaaa" appears 1 time. The longest that occurs ≥3 times is "aa" with length 2.
Example 2 — Multiple Characters
$
Input:
s = "abcdef"
›
Output:
-1
💡 Note:
Each character appears only once, so no special substring can occur at least 3 times.
Example 3 — Mixed Pattern
$
Input:
s = "abcaba"
›
Output:
1
💡 Note:
Only single characters are special here. "a" appears 3 times and "b" appears 2 times. The longest special substring that occurs ≥3 times is "a" with length 1.
Constraints
- 3 ≤ s.length ≤ 5 × 104
- s consists of only lowercase English letters.
Visualization
Tap to expand
Understanding the Visualization
1
Input Analysis
String with consecutive character blocks
2
Find Special Substrings
Identify all substrings with single character type
3
Count & Filter
Count occurrences and find longest with ≥3 occurrences
Key Takeaway
🎯 Key Insight: Use mathematical counting - in a block of n identical characters, there are exactly (n-k+1) substrings of length k
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code