Find Longest Awesome Substring - Problem
Find Longest Awesome Substring
You're given a string s consisting only of digits. Your task is to find the longest awesome substring.
An awesome substring is a non-empty substring where you can rearrange the characters to form a palindrome. This means at most one character can have an odd frequency - all others must appear an even number of times.
Key Insight: Since we can swap characters freely, we only care about the frequency of each digit, not their positions!
Examples:
"3242415"โ The substring"24241"can be rearranged to"24142"(palindrome)"12321"โ The entire string is already awesome (can form palindrome"12321")
Goal: Return the length of the maximum length awesome substring.
Input & Output
example_1.py โ Basic Case
$
Input:
s = "3242415"
โบ
Output:
5
๐ก Note:
The longest awesome substring is "24241" (from index 1 to 5). It can be rearranged to form palindrome "24142" since digit 1 appears once (odd), digits 2 and 4 each appear twice (even).
example_2.py โ Already Palindrome
$
Input:
s = "12321"
โบ
Output:
5
๐ก Note:
The entire string "12321" is already a palindrome and awesome. Digit frequencies: 1โ2 times, 2โ2 times, 3โ1 time. At most one digit (3) has odd frequency.
example_3.py โ Single Character
$
Input:
s = "213"
โบ
Output:
1
๐ก Note:
Each individual character forms an awesome substring of length 1. No longer awesome substring exists since all pairs would have different digits (each appearing once, giving 2 odd frequencies).
Constraints
- 1 โค s.length โค 105
- s consists only of digits (0-9)
- An awesome substring must be non-empty
- At most one character can have odd frequency for palindrome formation
Visualization
Tap to expand
Understanding the Visualization
1
Create Fingerprint
Each position in string creates a bitmask fingerprint representing which digits appear odd number of times
2
Pattern Matching
Look for previous positions with same fingerprint (all even frequencies) or fingerprint differing by exactly 1 bit (one odd frequency)
3
Calculate Distance
When patterns match, the substring between positions can form a palindrome - calculate its length
4
Track Maximum
Keep track of the longest valid substring found using this pattern matching technique
Key Takeaway
๐ฏ Key Insight: By representing digit frequency parity as bit patterns, we transform a complex substring problem into efficient pattern matching, achieving optimal O(n) time complexity.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code