Find Longest Awesome Substring — LeetCode 1542 Python Solution

HardBit ManipulationHash TableString
Problem
#1542
Reading time
3 min

The 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.

Example

Input
s = "3242415"
Output
5
Explanation
"24241" is the longest awesome substring, we can form the palindrome "24142" with some swaps.

Python solution

Python
class Solution:
    def longestAwesome(self, s: str) -> int:
        st = 0
        d = {0: -1}
        ans = 1
        for i, c in enumerate(s):
            v = int(c)
            st ^= 1 << v
            if st in d:
                ans = max(ans, i - d[st])
            else:
                d[st] = i
            for v in range(10):
                if st ^ (1 << v) in d:
                    ans = max(ans, i - d[st ^ (1 << v)])
        return ans

Complexity

MeasureComplexity
TimeO(n \times C)
SpaceO(2^C) auxiliary

Pattern: Bit Manipulation

Use XOR, masks and the low-bit trick to replace whole data structures with an integer. LeetCode 1542. Find Longest Awesome Substring is filed here because LeetCode tags it Bit Manipulation, which is the vocabulary this hub collects.

The bit manipulation guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1542. Find Longest Awesome Substring?
LeetCode 1542. Find Longest Awesome Substring is rated Hard on LeetCode.
What is the time complexity of LeetCode 1542. Find Longest Awesome Substring?
The Python solution on this page runs in O(n \times C).
What is the space complexity of LeetCode 1542. Find Longest Awesome Substring?
The Python solution on this page uses O(2^C) auxiliary space.
What topics does LeetCode 1542. Find Longest Awesome Substring cover?
LeetCode 1542. Find Longest Awesome Substring is tagged Bit Manipulation, Hash Table and String on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview