Find Longest Special Substring That Occurs Thrice I - 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 Special Substrings
$ Input: s = "aaaa"
Output: 2
💡 Note: Special substrings: "a" occurs 4 times, "aa" occurs 3 times, "aaa" occurs 2 times (less than 3). The longest special substring that occurs at least thrice is "aa" with length 2.
Example 2 — Mixed Characters
$ Input: s = "abcdef"
Output: -1
💡 Note: Each character appears only once, so no special substring can occur 3 or more times. Return -1.
Example 3 — Multiple Character Runs
$ Input: s = "abcaba"
Output: 1
💡 Note: Only "a" and "b" can form special substrings. Character "a" appears 3 times total, character "b" appears 2 times. Only "a" occurs at least 3 times, so return length 1.

Constraints

  • 3 ≤ s.length ≤ 50
  • s consists of only lowercase English letters.

Visualization

Tap to expand
Problem Overview: Special Substring AnalysisaaabaaInput: "aaabaa""aaa" run"aa" runSpecial Substring AnalysisLength 1 "a": appears 5 times (3+2) ✓Length 2 "aa": appears 3 times (2+1) ✓Result: 2
Understanding the Visualization
1
Input String
String with consecutive character runs
2
Find Special Substrings
Identify substrings of same character
3
Count Occurrences
Return longest length appearing ≥3 times
Key Takeaway
🎯 Key Insight: Count consecutive character runs instead of generating all substrings for optimal performance
Asked in
Google 12 Facebook 8 Amazon 6
8.4K Views
Medium Frequency
~15 min Avg. Time
156 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen