#2983

Palindrome Rearrangement Queries

Hard
Hash TableStringPrefix SumHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

Instead of generating rearrangements, we can count character frequencies in the specified ranges. For a string to be rearranged into a palindrome, each character must appear an even number of times, except for at most one character.

⚙️

Algorithm

3 steps
  1. 1Step 1: For each query, count the frequency of characters in both substrings.
  2. 2Step 2: Combine the frequency counts from both substrings.
  3. 3Step 3: Check if at most one character has an odd frequency in the combined counts.
solution.py12 lines
1from collections import Counter
2
3def can_form_palindrome(s, queries):
4    n = len(s)
5    results = []
6    for a, b, c, d in queries:
7        left_count = Counter(s[a:b + 1])
8        right_count = Counter(s[c:d + 1])
9        combined_count = left_count + right_count
10        odd_count = sum(1 for count in combined_count.values() if count % 2 != 0)
11        results.append(odd_count <= 1)
12    return results

Complexity note: This complexity is due to counting character frequencies, which requires a linear scan of the substrings, resulting in O(n) time for each query.

  • 1A string can be rearranged into a palindrome if at most one character has an odd frequency.
  • 2Character frequency counting is a powerful technique for solving string rearrangement problems.

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