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
Find Longest Special Substring (Thrice) INPUT String s = "aaaa" a idx 0 a idx 1 a idx 2 a idx 3 Special Substring: Made of only ONE character "aa", "aaa", "aaaa" = OK Goal: Find LONGEST special substring occurring at least 3 times ALGORITHM STEPS 1 Count Consecutive Track runs of same char 2 Store Top 3 Lengths For each char (a-z) 3 Generate Candidates Check 3x occurrence 4 Return Max Length Or -1 if none found For 'a' with run length 4: "aa" (len=2): 3 times - OK "aaa" (len=3): 2 times "aaaa" (len=4): 1 time Max valid length = 2 FINAL RESULT Output: 2 Why 2? "aa" appears 3 times in "aaaa": [aa]aa, a[aa]a, aa[aa] This is the longest valid! Visual Occurrences: a a a a #1 a a a a #2 #3: pos 2-3 Key Insight: For a run of length L, we can get special substrings of length k appearing (L - k + 1) times. Track top 3 run lengths per character. Binary search or greedy approach finds max length with 3+ occurrences. Time: O(n) | Space: O(26 * 3) = O(1) TutorialsPoint - Find Longest Special Substring That Occurs Thrice II | Optimal Solution
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