Substring XOR Queries - Problem
Substring XOR Queries - Find the shortest binary substring that satisfies XOR conditions
You're given a binary string
For each query, you need to find the shortest substring of
Goal: Return the start and end indices
Example: If
You're given a binary string
s and an array of queries. Each query contains two integers [first, second].For each query, you need to find the shortest substring of
s whose decimal value, when XORed with first, equals second. In mathematical terms: substring_value ^ first == second.Goal: Return the start and end indices
[left, right] of the shortest valid substring for each query. If no such substring exists, return [-1, -1]. When multiple substrings have the same length, choose the one with the smallest starting index.Example: If
s = "101101" and query is [4, 5], we need to find a substring whose decimal value XORed with 4 gives 5. Since 4 ^ 5 = 1, we're looking for a substring with decimal value 1, which is "1" at index 0. Input & Output
example_1.py โ Basic Case
$
Input:
s = "101101", queries = [[4,5]]
โบ
Output:
[[0,0]]
๐ก Note:
For query [4,5], we need to find substring whose value XORed with 4 equals 5. Since 4 ^ 5 = 1, we need substring with decimal value 1. The substring "1" at index [0,0] has decimal value 1.
example_2.py โ Multiple Queries
$
Input:
s = "101101", queries = [[0,5],[1,2]]
โบ
Output:
[[0,2],[2,3]]
๐ก Note:
For [0,5]: target = 0^5 = 5, found "101" at [0,2]. For [1,2]: target = 1^2 = 3, found "11" at [2,3].
example_3.py โ No Solution
$
Input:
s = "101", queries = [[5,1]]
โบ
Output:
[[-1,-1]]
๐ก Note:
For query [5,1], target = 5^1 = 4. No substring in "101" has decimal value 4, so return [-1,-1].
Visualization
Tap to expand
Understanding the Visualization
1
Index Building
Scan through the binary code book and catalog every possible sequence with its shortest occurrence
2
Query Processing
For each decoding request, calculate what code value would produce the desired result
3
Instant Lookup
Use your pre-built index to instantly find the shortest sequence with the target value
4
Result Delivery
Return the position of the shortest matching sequence, or indicate if impossible
Key Takeaway
๐ฏ Key Insight: By preprocessing all substring values into a hash map and using XOR's inverse property (A ^ B = C โน A ^ C = B), we can answer each query in O(1) time after O(nยฒ) preprocessing!
Time & Space Complexity
Time Complexity
O(nยฒ + q)
O(nยฒ) to preprocess all substrings and build hash map, then O(1) per query for q queries
โ Quadratic Growth
Space Complexity
O(nยฒ)
Hash map can store up to O(nยฒ) different substring values in worst case
โ Quadratic Space
Constraints
- 1 โค s.length โค 104
- s consists only of '0' and '1'
- 1 โค queries.length โค 105
- 0 โค firsti, secondi โค 109
- Important: Substring values can be very large, handle overflow carefully
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code