Find Longest Special Substring That Occurs Thrice I - Problem
You are given a string s consisting of lowercase English letters. Your task is to find the longest special substring that appears at least three times in the string.
A special substring is one that contains only a single type of character. For example:
"aaa","bb", and"c"are special substrings"abc","aab", and"xy"are not special substrings
Goal: Return the length of the longest special substring that occurs at least 3 times, or -1 if no such substring exists.
Note: A substring is a contiguous sequence of characters within the string.
Input & Output
example_1.py ā Basic Case
$
Input:
s = "aaaa"
āŗ
Output:
2
š” Note:
The special substrings are "a" (appears 4 times), "aa" (appears 3 times), "aaa" (appears 2 times), and "aaaa" (appears 1 time). The longest special substring that occurs at least thrice is "aa" with length 2.
example_2.py ā Mixed Characters
$
Input:
s = "abcdef"
āŗ
Output:
-1
š” Note:
All characters appear only once. Each single character special substring ("a", "b", "c", "d", "e", "f") appears exactly 1 time, which is less than 3. No special substring occurs at least thrice.
example_3.py ā Multiple Groups
$
Input:
s = "abcaba"
āŗ
Output:
1
š” Note:
The character 'a' appears 3 times and 'b' appears 2 times. The special substring "a" occurs 3 times (at positions 0, 3, 5), which satisfies the requirement. The longest special substring that occurs at least thrice is "a" with length 1.
Visualization
Tap to expand
Understanding the Visualization
1
Scan DNA Strand
Examine the DNA sequence character by character
2
Group Identical Nucleotides
Identify consecutive sequences of the same nucleotide (A, T, G, C)
3
Count Pattern Occurrences
For each group, calculate how many patterns of each length it contributes
4
Find Most Common Pattern
Identify the longest pattern that appears at least 3 times across the strand
Key Takeaway
šÆ Key Insight: Instead of checking every possible substring (O(n³)), group consecutive identical characters and use mathematical formulas to count special substrings efficiently in O(n) time.
Time & Space Complexity
Time Complexity
O(n)
Single pass to group characters, constant work per group
ā Linear Growth
Space Complexity
O(n)
Hash map to store counts for each (character, length) combination
ā” Linearithmic Space
Constraints
- 3 ⤠s.length ⤠50
- s consists of only lowercase English letters
- A special substring must occur at least 3 times
- Return -1 if no valid special substring exists
š”
Explanation
AI Ready
š” Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code