Substring XOR Queries - 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. In other words, val ^ firsti == secondi.

The answer to the ith query is the endpoints (0-indexed) of the substring [lefti, righti] or [-1, -1] if no such substring exists. If there are multiple answers, choose the one with the minimum lefti.

Return an array ans where ans[i] = [lefti, righti] is the answer to the ith query.

A substring is a contiguous non-empty sequence of characters within a string.

Input & Output

Example 1 — Basic Case
$ Input: s = "101101", queries = [[4,7],[2,3]]
Output: [[0,0],[0,0]]
💡 Note: For query [4,7]: target = 4^7 = 3. Substring "11" at indices [2,3] has decimal value 3, but substring "1" at [0,0] is shorter. For query [2,3]: target = 2^3 = 1. Substring "1" at indices [0,0] has decimal value 1 and is the shortest.
Example 2 — No Solution
$ Input: s = "0101", queries = [[5,1]]
Output: [[-1,-1]]
💡 Note: Target = 5^1 = 4. No substring of "0101" has decimal value 4, so return [-1,-1].
Example 3 — Single Character
$ Input: s = "1", queries = [[3,2]]
Output: [[0,0]]
💡 Note: Target = 3^2 = 1. Substring "1" at indices [0,0] has decimal value 1.

Constraints

  • 1 ≤ s.length ≤ 104
  • s[i] is either '0' or '1'
  • 1 ≤ queries.length ≤ 105
  • 0 ≤ firsti, secondi ≤ 109

Visualization

Tap to expand
Substring XOR Queries INPUT Binary String s: 1 0 0 1 1 2 1 3 0 4 1 5 Queries: Query 0: [4, 7] Find val where val ^ 4 = 7 Query 1: [2, 3] Find val where val ^ 2 = 3 XOR Property: val = first ^ second (target value to find) ALGORITHM STEPS 1 Calculate Target target = first ^ second Q0: 4^7=3 Q1: 2^3=1 2 Precompute Map Store shortest substrings for each decimal value 3 Early Termination Limit substring length to ~20 bits (log max) 4 Lookup Results Find target in map Return [left, right] Map Building: "11" at [2,3] --> val=3 "1" at [0] --> val=1 "01" at [1,2] --> val=1 "10" at [0,1] --> val=2 Keep shortest for each val FINAL RESULT Query 0: [4, 7] target = 4 ^ 7 = 3 Find substring = 3 (binary "11") ans[0] = [2,3] Query 1: [2, 3] target = 2 ^ 3 = 1 Find substring = 1 (binary "01") ans[1] = [1,2] OUTPUT: [[2,3], [1,2]] Key Insight: 1. Use XOR property: val = first ^ second to find the target value directly 2. Precompute a hashmap of all substring decimal values with their positions (shortest first) 3. Early termination: limit substring length to ~20 bits since values won't exceed 10^9 TutorialsPoint - Substring XOR Queries | Optimized with Early Termination
Asked in
Microsoft 15 Google 12 Amazon 8
8.5K Views
Medium Frequency
~25 min Avg. Time
245 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen