Leetcode 2564: Substring XOR Queries

grid47
grid47
Exploring patterns and algorithms
Feb 24, 2024 9 min read

You are given a binary string s and a 2D array of queries. Each query is represented as [firsti, secondi], where firsti and secondi are integers. For each query, you need to find the shortest substring of s whose decimal value XORed with firsti equals secondi.

In other words, find a substring whose decimal value, when XORed with firsti, results in secondi. If such a substring exists, return its starting and ending indices (0-indexed). If no such substring exists, return [-1, -1].

If there are multiple valid substrings, return the one with the smallest starting index.

Problem
Approach
Steps
Complexity
Input: You are given a binary string `s` and a list of queries where each query consists of two integers `firsti` and `secondi`.
Example: s = '101101', queries = [[0,5], [1,2]]
Constraints:
• 1 <= s.length <= 10^4
• 1 <= queries.length <= 10^5
• 0 <= firsti, secondi <= 10^9
Output: For each query, return the starting and ending indices of the shortest valid substring or [-1, -1] if no valid substring exists.
Example: Output: [[0,2], [2,3]]
Constraints:
• The output should be a list of pairs of integers where each pair corresponds to the indices of the valid substring or [-1, -1] if no valid substring is found.
Goal: To efficiently find the shortest valid substring for each query.
Steps:
• Convert the binary string into decimal values of substrings.
• For each query, calculate the XOR of `firsti` and `secondi` to get the target value.
• Check if the target value can be found as a decimal value of a substring of `s`.
• Return the indices of the substring if it exists, otherwise return [-1, -1].
Goal: The problem constraints are manageable for optimized solutions that leverage precomputation and binary search.
Steps:
• 1 <= s.length <= 10^4
• 1 <= queries.length <= 10^5
• 0 <= firsti, secondi <= 10^9
Assumptions:
• The input binary string is valid and consists only of '0' and '1'.
• The queries array contains valid integer pairs within the specified range.
Input: Example 1:
Explanation: Given the string s = '101101' and queries = [[0,5], [1,2]], we can find the following substrings: For the first query, the substring '101' (indices 0 to 2) has a decimal value of 5, and 5 XOR 0 equals 5, so the answer is [0, 2]. For the second query, the substring '11' (indices 2 to 3) has a decimal value of 3, and 3 XOR 1 equals 2, so the answer is [2, 3].

Input: Example 2:
Explanation: Given the string s = '0101' and queries = [[12,8]], there is no substring whose decimal value XORed with 12 equals 8, so the answer is [-1, -1].

Input: Example 3:
Explanation: Given the string s = '1' and queries = [[4,5]], the substring '1' (indices 0 to 0) has a decimal value of 1, and 1 XOR 4 equals 5, so the answer is [0, 0].

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus