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
Problem: Find Longest Special Substring (≥3 times)Input: "aaaa"aaaaSpecial Substrings AnalysisLength 1: "a" occurs 4 times ✓Length 2: "aa" occurs 3 times ✓Length 3: "aaa" occurs 2 times ✗Positions of "aa":(0,1), (1,2), (2,3)Output: 2Longest special substring occurring ≥3 times has length 2
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
Asked in
Google 25 Amazon 18 Microsoft 12
12.5K Views
Medium Frequency
~25 min Avg. Time
348 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