Problem solution · Python

Palindrome Rearrangement Queries

Palindrome Rearrangement Queries: a Python solution using sliding window or two pointers. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Sliding window or two pointers
Source
walkccc LeetCode Solutions
Length
74 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Sliding window or two pointers

For Palindrome Rearrangement Queries, the implementation maintains a moving interval and updates only the information that enters or leaves the window.

  1. Choose the invariant that makes a window valid or useful.
  2. Advance the right boundary and add the new element.
  3. Move the left boundary only as needed while maintaining the invariant and updating the answer.

Code notes

  • 74 lines of Python from the credited upstream file 2983.py.
  • The implementation visibly relies on sequence storage.
  • No explicit loop blocks detected.

Complexity

Confirm that neither pointer moves backwards; if so, the scan is usually linear apart from the window’s data-structure operations.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codePalindrome Rearrangement Queries · PythonPython
Use this to learn the idea, then write your own version.
class Solution:  def canMakePalindromeQueries(      self,      s: str,      queries: list[list[int]],  ) -> list[bool]:    n = len(s)    # mirroredDiffs[i] := the number of different letters between the first i    # letters of s[0..n / 2) and the first i letters of s[n / 2..n)[::-1]    mirroredDiffs = self._getMirroredDiffs(s)    # counts[i] := the count of s[0..i)    counts = self._getCounts(s)    ans = []     def subtractArrays(a: list[int], b: list[int]):      return [x - y for x, y in zip(a, b)]     for a, b, c, d in queries:      # Use left-closed, right-open intervals to facilitate the calculation.      #   ...... [a, b) ...|... [rb, ra) ......      #   .... [rd, rc) .....|..... [c, d) ....      b += 1      d += 1      ra = n - a  # the reflected index of a in s[n / 2..n)      rb = n - b  # the reflected index of b in s[n / 2..n)      rc = n - c  # the reflected index of c in s[n / 2..n)      rd = n - d  # the reflected index of d in s[n / 2..n)      # No difference is allowed outside the query ranges.      if ((min(a, rd) > 0 and mirroredDiffs[min(a, rd)] > 0) or         (n // 2 > max(b, rc) and          mirroredDiffs[n // 2] - mirroredDiffs[max(b, rc)] > 0) or         (rd > b and mirroredDiffs[rd] - mirroredDiffs[b] > 0) or         (a > rc and mirroredDiffs[a] - mirroredDiffs[rc] > 0)):        ans.append(False)      else:        # The `count` map of the intersection of [a, b) and [rd, rc) in        # s[0..n / 2) must equate to the `count` map of the intersection of        # [c, d) and [rb, ra) in s[n / 2..n).        leftRangeCount = subtractArrays(counts[b], counts[a])        rightRangeCount = subtractArrays(counts[d], counts[c])        if a > rd:          rightRangeCount = subtractArrays(              rightRangeCount, subtractArrays(counts[min(a, rc)], counts[rd]))        if rc > b:          rightRangeCount = subtractArrays(              rightRangeCount, subtractArrays(counts[rc], counts[max(b, rd)]))        if c > rb:          leftRangeCount = subtractArrays(              leftRangeCount, subtractArrays(counts[min(c, ra)], counts[rb]))        if ra > d:          leftRangeCount = subtractArrays(              leftRangeCount, subtractArrays(counts[ra], counts[max(d, rb)]))        ans.append(min(leftRangeCount) >= 0                   and min(rightRangeCount) >= 0                   and leftRangeCount == rightRangeCount)     return ans   def _getMirroredDiffs(self, s: str) -> list[int]:    diffs = [0]    for i, j in zip(range(len(s)), reversed(range(len(s)))):      if i >= j:        break      diffs.append(diffs[-1] + (s[i] != s[j]))    return diffs   def _getCounts(self, s: str) -> list[list[int]]:    count = [0] * 26    counts = [count.copy()]    for c in s:      count[ord(c) - ord('a')] += 1      counts.append(count.copy())    return counts 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗