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: [[2,3],[1,2]]
💡 Note: For query [4,7]: target = 4^7 = 3. Substring "11" at indices [2,3] has decimal value 3. For query [2,3]: target = 2^3 = 1. Substring "01" at indices [1,2] has decimal value 1.
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: Find Matching Decimal ValuesInput: s = "101101", query = [4, 7]101101012345Step 1: Calculate target = 4 ^ 7 = 3Step 2: Find substring with decimal value = 3Step 3: "11" at indices [2,3] has value 3Binary "11" = 1×2¹ + 1×2⁰ = 2 + 1 = 3Output: [2, 3]
Understanding the Visualization
1
Input
Binary string and query pairs [first, second]
2
Process
Find substring where decimal_value ^ first == second
3
Output
Return [start, end] indices of shortest leftmost match
Key Takeaway
🎯 Key Insight: XOR relationship means target = first ^ second, then find substring with that decimal value
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