Problem 1177

Abstract / Summary

Check if a substring can be rearranged into a palindrome by ensuring at most one character has an odd count.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1177.py

class Solution:
    def canMakePaliQueries(self, s: str, queries: List[List[int]]) -> List[bool]:
        # state encodes whether that letter is found an odd or even times
        state = 0
        have  = []
        for c in s:
            c = ord(c) - ord("a")
            state ^= 1 << c
            have.append(state)

        for left, right, k in queries:
            final = have[right]
            if left > 0:
                final ^= have[left - 1]

            odd = final.bit_count()
            yield odd <= 2*k + 1 # at most one letter may have an odd count
                                 # whenever replacing an "odd-count letter",
                                 # try to choose another "odd-count letter"
                                 # thus eliminating two  "odds"
20 lines | 809 bytes | submitted March 31, 2024 | GitHub   35% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 42% (80k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Bit Manipulation
  • Hash Table
  • Prefix Sum
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation solves the problem of determining, for many substring queries, whether the substring can be rearranged into a palindrome after performing at most k character replacements. The core idea is to represent the parity (odd or even occurrence) of each letter using a single integer bitmask and to pre-compute a prefix array of these masks. Each query is answered in constant time by extracting the parity mask for the requested interval and checking a simple numeric condition.

Prefix Parity Construction

The algorithm first builds a running parity mask while scanning the input string. For each character the corresponding bit in the mask is toggled, and the current mask is stored in a list. This list, named have, holds the parity state of the prefix ending at each position.

state = 0
have = []
for c in s:
    c = ord(c) - ord("a")
    state ^= 1 << c
    have.append(state)

The variable state starts at zero, meaning all letters have even counts. The expression 1 << c creates a mask with a single bit set for the current character. The XOR operation flips that bit, turning an even count into odd and vice-versa. By appending the mask after each iteration, have[i] represents the parity of the substring s[0:i+1].

Query Evaluation

For each query [left, right, k] the code extracts the parity mask of the substring s[left:right+1]. This is done by XOR-ing the prefix mask at right with the prefix mask just before left (when left is greater than zero). The resulting mask, stored in final, has a set bit for each character that appears an odd number of times in the interval.

final = have[right]
if left > 0:
    final ^= have[left - 1]

The number of set bits in final is obtained with the built-in bit_count() method, which efficiently counts the ones in the integer representation.

odd = final.bit_count()

The decision rule checks whether the number of odd-count characters can be reduced to at most one by using at most k replacements. Each replacement can eliminate two odd counts (by turning one odd character into another odd character), so the condition odd <= 2*k + 1 captures this logic. The result is yielded as a Boolean value.

yield odd <= 2*k + 1

Edge Cases Handled

When left equals zero the code skips the XOR with a preceding prefix mask, correctly using the mask stored at right as the whole substring parity. The XOR operation also works when right is the last index, because have contains a mask for every position. The algorithm gracefully handles an empty string: the loop that builds have never executes, leaving have empty, and any query would attempt to access an index that does not exist, which is outside the intended input domain. For queries where k is large enough to cover all odd characters, the condition automatically evaluates to true because 2*k + 1 exceeds any possible odd count (the maximum odd count is 26 for lowercase English letters). The use of bit_count() correctly returns zero for a mask of zero, covering the case where the substring already has all even counts.

Performance Optimizations

The most significant optimization is the use of a single integer as a compact representation of the parity of all 26 letters. This eliminates the need for an array of counters per prefix, reducing memory overhead and improving cache locality. The XOR operation for updating the mask and for extracting interval parity are both O(1) bitwise operations executed in native C code, making them extremely fast.

Storing the prefix masks in a list enables each query to be answered without recomputing any counts. The bit_count() method is a highly optimized routine that counts set bits using processor-level instructions when available, providing a rapid way to determine the number of odd occurrences.

Yielding results instead of building an intermediate list allows the caller to consume answers lazily, which can be advantageous when the consumer processes results on the fly and does not need the entire output at once.

Overall, the combination of bitwise state encoding, prefix pre-computation, and built-in population count yields a solution that processes each query in constant time with minimal per-query overhead.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a long row of colorful blocks, and each block has a letter of the alphabet written on it. You have a special magic box that keeps track of the letters you have seen so far. Every time you see a letter, you toggle a light switch for that letter. If the switch was off, it turns on. If it was on, it turns off. This means the box always remembers if you have an odd or an even number of each letter. Because there are twenty-six letters in the alphabet, the box uses twenty-six little switches to store this information.

When someone asks you a question about a specific slice of the row, you look at the switches at the end of the slice and compare them to the switches just before the slice began. By flipping the switches from the beginning of the slice back to their original state, you can figure out exactly which letters appear an odd number of times in that specific part of the row.

If you have many letters that appear an odd number of times, you are allowed to swap out some of those letters to change them into pairs. Since changing one letter can fix one odd count, or by pairing it up with another odd count it can fix two at once, you count up how many odd letters exist. If that number of odd letters is small enough based on how many swaps you are allowed to make, then you can successfully rearrange those blocks to make a word that reads the same forward and backward.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 8 | μ = 7.22 | σ = 1.62

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Java Python TS
WalkCCC C++ Java Python
leetcode.ca C++ Java Go Python TS
Progiez C++ Java Python
github black-shadows C++
charles-wangkai Java
everthis JS
fsq C++
JoshCrozier JS
suxrobGM C#
varunu28 Java
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, TypeScript
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fsq C++
JoshCrozier JavaScript
suxrobGM C#
varunu28 Java
22 links | 11 authors | 7 languages

Videos

2 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

2 similar problems

Solved On The Same Day

2 solutions   March 31, 2024

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality