Problem Description
Given a binary string s and an array of queries where each query is of the form [first, second], we need to find for each query the shortest substring of s whose decimal interpretation, when XORed with first, equals second. That is, if the decimal value of the substring is val, then it must satisfy val ^ first = second. If multiple valid substrings exist, return the one with the smallest left index; if none exist, return [-1, -1].
Key Insights
- We can transform the query requirement to: find a substring whose decimal value val is equal to target where target = first ^ second.
- The maximum target is 10^9, so its binary representation uses at most 30 bits. Therefore, when scanning s, we only need to consider substrings with length up to 31.
- Precompute and map each possible substring value (obtained from s) along with its earliest occurrence (with minimal left) in s.
- For substrings that start with '0', only the single-character substring "0" should be considered in order to avoid duplicates and to guarantee the shortest substring.
- After building the mapping from value to its (left, right) indices, answer each query by checking if target exists in the map.
Space and Time Complexity
Time Complexity: O(n * L + Q) where n is length of s, L is at most 31 (the maximum substring length processed per index), and Q is the number of queries. Space Complexity: O(n * L) for the dictionary storing candidate substrings, which is acceptable given the constraints.
Solution
We precompute a dictionary mapping each possible substring’s decimal value to its earliest occurrence [left, right] from the string s. For each starting index i, we iterate j from i to min(i + 31, n) and update the running value. We skip extended substrings that start with '0' (after processing the single '0') since they would not be minimal. Once the map is built, each query [first, second] is answered by computing target = first XOR second and looking up the result in our mapping. If found, return the stored indices; otherwise return [-1, -1].