Find Longest Awesome Substring - Problem

You are given a string s. An awesome substring is a non-empty substring of s such that we can make any number of swaps in order to make it a palindrome.

Return the length of the maximum length awesome substring of s.

Note: A palindrome is a string that reads the same forward and backward. For example, "racecar" and "aabbaa" are palindromes, while "hello" is not.

Input & Output

Example 1 — Basic Case
$ Input: s = "3242415"
Output: 5
💡 Note: The substring "24241" can be rearranged to form the palindrome "24142" since digits 2,4,1 each appear twice and 4 appears once, satisfying the palindrome condition.
Example 2 — Single Digit
$ Input: s = "12345"
Output: 1
💡 Note: No substring longer than 1 can form a palindrome since all digits are different. Any single digit forms a palindrome, so the answer is 1.
Example 3 — All Same Digits
$ Input: s = "213213"
Output: 6
💡 Note: The entire string can form a palindrome (e.g., "123321") since each digit 1,2,3 appears exactly twice, all even counts.

Constraints

  • 1 ≤ s.length ≤ 105
  • s consists only of digits.

Visualization

Tap to expand
Find Longest Awesome Substring INPUT String s = "3242415" 3 0 2 1 4 2 2 3 4 4 1 5 5 6 Awesome Substring: Can be rearranged to form a palindrome (at most 1 char with odd frequency) Bitmask Representation: Each bit = digit parity XOR toggles bit on/off mask = 0000000000 (10 bits) Digits 0-9 ALGORITHM STEPS 1 Initialize HashMap Store mask -> first index map[0] = -1, mask = 0 2 XOR each digit mask ^= (1 << digit) Toggle bit for digit 3 Check same mask If mask seen, all chars have even count 4 Check 1-bit diff masks mask ^ (1<<j) for j=0-9 allows 1 odd char Trace (partial): i=0: '3' mask=0b1000 i=1: '2' mask=0b1100 i=2: '4' mask=0b11100 i=3: '2' mask=0b11000 ... Best len=5: "32424" FINAL RESULT Longest Awesome Substring: 3 2 4 2 4 1 5 "32424" (indices 0-4) Output: 5 Why "32424" is awesome? Char counts: 2=2, 3=1, 4=2 Only '3' has odd count Can form: "24342" [OK] Time: O(n) Space: O(1024) = O(1) Key Insight: Use bitmask to track parity of digit counts. A substring is "awesome" if its bitmask has at most 1 bit set (meaning at most one digit has odd frequency). XOR of two positions gives the mask for that substring. Store first occurrence of each mask in HashMap. Only 1024 possible masks (2^10 for digits 0-9). TutorialsPoint - Find Longest Awesome Substring | Optimal Solution (Bitmask + HashMap)
Asked in
Google 25 Facebook 20 Amazon 15
23.5K Views
Medium Frequency
~25 min Avg. Time
892 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