#1542

Find Longest Awesome Substring

Hard
LeetCode ↗

Approaches

💡

Intuition

Time O(n²)Space O(1)

The brute force approach involves checking every possible substring of the given string to see if it can be rearranged into a palindrome. This is simple but inefficient, as it requires examining all combinations.

⚙️

Algorithm

4 steps
  1. 1Step 1: Generate all possible substrings of the string.
  2. 2Step 2: For each substring, count the frequency of each digit.
  3. 3Step 3: Check if the substring can be rearranged into a palindrome by ensuring at most one digit has an odd count.
  4. 4Step 4: Keep track of the maximum length of valid substrings.
solution.py12 lines
1def longestAwesome(s):
2    max_length = 0
3    for i in range(len(s)):
4        for j in range(i, len(s)):
5            substring = s[i:j+1]
6            count = [0] * 10
7            for char in substring:
8                count[int(char)] += 1
9            odd_count = sum(1 for c in count if c % 2 != 0)
10            if odd_count <= 1:
11                max_length = max(max_length, j - i + 1)
12    return max_length

Complexity note: The complexity is O(n²) because we are generating all substrings (O(n²) combinations) and checking each for palindrome potential, which takes O(n) time for counting.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.