Substring XOR Queries — LeetCode 2564 Python Solution

MediumBit ManipulationArrayHash TableString
Problem
#2564
Reading time
3 min

The problem

You are given a binary string s, and a 2D integer array queries where queries[i] = [firsti, secondi]. For the ith query, find the shortest substring of s whose decimal value, val, yields secondi when bitwise XORed with firsti.

Example

Input
s = "101101", queries = [[0,5],[1,2]]
Output
[[0,2],[2,3]]
Explanation
For the first query the substring in range [0,2] is "101" which has a decimal value of 5, and 5 ^ 0 = 5, hence the answer to the first query is [0,2]. In the second query, the substring in range [2,3] is "11", and has a decimal value of 3, and 3 ^ 1 = 2. So, [2,3] is returned for the second query.

Python solution

Python
class Solution:
    def substringXorQueries(self, s: str, queries: List[List[int]]) -> List[List[int]]:
        d = {}
        n = len(s)
        for i in range(n):
            x = 0
            for j in range(32):
                if i + j >= n:
                    break
                x = x << 1 | int(s[i + j])
                if x not in d:
                    d[x] = [i, i + j]
                if x == 0:
                    break
        return [d.get(first ^ second, [-1, -1]) for first, second in queries]

Complexity

MeasureComplexity
TimeO(n \times \log M + m)
SpaceO(n \times \log M) auxiliary

Pattern: Bit Manipulation

Use XOR, masks and the low-bit trick to replace whole data structures with an integer. LeetCode 2564. Substring XOR Queries 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 2564. Substring XOR Queries?
LeetCode 2564. Substring XOR Queries is rated Medium on LeetCode.
What is the time complexity of LeetCode 2564. Substring XOR Queries?
The Python solution on this page runs in O(n \times \log M + m).
What is the space complexity of LeetCode 2564. Substring XOR Queries?
The Python solution on this page uses O(n \times \log M) auxiliary space.
What topics does LeetCode 2564. Substring XOR Queries cover?
LeetCode 2564. Substring XOR Queries is tagged Bit Manipulation, Array, 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