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
Find Longest Special Substring (Thrice) INPUT String s = "aaaa" a [0] a [1] a [2] a [3] Special Substring: Made of single char only "aa", "aaa" = OK "ab" = NOT OK Character Run: 'a' appears in run of length 4 ALGORITHM STEPS 1 Find Character Runs Run: 'a' x 4 consecutive 2 Generate Substrings From run length 4: Len 1: "a" x4 Len 2: "aa" x3 Len 3: "aaa" x2 Len 4: "aaaa" x1 (occurrences) 3 Count Occurrences Track count for each len 4 Find Max with 3+ count Len 2 has count 3 (OK) Len 3 has count 2 (NO) FINAL RESULT Longest special substring occurring 3+ times: Occurrence 1: aa [0:2] Occurrence 2: aa [1:3] Occurrence 3: aa [2:4] 3 occurrences found! Output: 2 Length of "aa" = 2 (max len with 3+ count) Key Insight: For a run of length L, we can extract substrings of length k exactly (L - k + 1) times. We need (L - k + 1) >= 3, so k <= L - 2. For L=4: max k where count >= 3 is k=2 (count=3). This optimized approach analyzes runs directly instead of checking all possible substrings. TutorialsPoint - Find Longest Special Substring That Occurs Thrice I | Optimized Character Run Analysis
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