Substring XOR Queries Problem
Description
LeetCode Problem 2564.
You are given a binary string s, and a 2D integer array queries where queries[i] = [first_i, second_i].
For the i^th query, find the shortest substring of s whose decimal value, val, yields second_i when bitwise XORed with first_i. In other words, val ^ first_i == second_i.
The answer to the i^th query is the endpoints (0-indexed) of the substring [left_i, right_i] or [-1, -1] if no such substring exists. If there are multiple answers, choose the one with the minimum left_i.
Return an array ans where ans[i] = [left_i, right_i] is the answer to the i^th query.
A substring is a contiguous non-empty sequence of characters within a string.
Example 1:
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.
Example 2:
Input: s = "0101", queries = [[12,8]]
Output: [[-1,-1]]
Explanation: In this example there is no substring that answers the query, hence [-1,-1] is returned.
Example 3:
Input: s = "1", queries = [[4,5]]
Output: [[0,0]]
Explanation: For this example, the substring in range [0,0] has a decimal value of 1, and 1 ^ 4 = 5. So, the answer is [0,0].
Constraints:
1 <= s.length <= 10^4s[i]is either'0'or'1'.1 <= queries.length <= 10^50 <= first_i, second_i <= 10^9
Solution
Approach: Precompute All Short Substrings
For a query [first, second], we need a substring whose value v satisfies v ^ first = second, which means v = first ^ second. Values fit in 32 bits, so a binary substring of that value has at most 32 characters (no leading zeros, except the single string "0").
Scan the string once and, for every start position, build the value of each substring of length up to 32. Store in a hash map, for each value, the first (leftmost) start and its end; the first occurrence is also the shortest for that start. Stop extending at a start that begins with 0 after recording the value 0. Each query is then a lookup of first ^ second, returning [-1, -1] if it is missing.
Complexity: O(n log M + q) time and O(n log M) extra space, where M is the largest query value.
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]