Taro Logo

Substring XOR Queries

Medium
Asked by:
Trilogy
0 views
Topics:
ArraysStringsBit Manipulation

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.

Example 1:

Input: s = "101101", queries = [[0,5],[1,2]]
Output: [[0,2],[2,3]]
Explanation: For the first query the substring in range [0,2] is "101" which has a decimal value of 5, and 5 ^ 0 = 5, hence the answer to the first query is [0,2]. In the second query, the substring in range [2,3] is "11", and has a decimal value of 3, and 3 ^ 1 = 2. So, [2,3] is returned for the second query. 

Example 2:

Input: s = "0101", queries = [[12,8]]
Output: [[-1,-1]]
Explanation: In this example there is no substring that answers the query, hence [-1,-1] is returned.

Example 3:

Input: s = "1", queries = [[4,5]]
Output: [[0,0]]
Explanation: For this example, the substring in range [0,0] has a decimal value of 1, and 1 ^ 4 = 5. So, the answer is [0,0].

Constraints:

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

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What format should the invalid indicators take if no matching substring exists for a query (e.g., `[-1, -1]`, `[null, null]`, or something else)?
  2. If there are multiple substrings that satisfy the XOR condition for a given query, how should we choose between them—does 'shortest' mean minimum length, and in the case of a tie, do we prefer the one with the smaller starting index?
  3. How are the values in the `queries` array represented? Are the first and second values given as standard integers, and can they be up to what maximum numerical value?
  4. Can the binary string `s` contain leading zeros for a substring (e.g., does the binary string '01' represent the value 1, and is '0' considered a valid substring for the value 0)?
  5. What are the maximum lengths of the binary string `s` and the `queries` array?

Brute Force Solution

Approach

The problem asks for the shortest substring whose decimal value equals first XOR second. Since each query value is bounded by 10^9, the target value requires at most 30 bits. We can precompute the best substring for each possible decimal value by checking all substrings up to length 30.

Here's how the algorithm would work step-by-step:

  1. Initialize a dictionary to store the best interval for each encountered integer value.
  2. Iterate over possible substring lengths from 1 to 30 in increasing order.
  3. For each length, slide through the string to compute the decimal value of each substring.
  4. Record the starting and ending indices for a value if it has not been recorded yet.
  5. Process each query by calculating first XOR second as the target value.
  6. Retrieve and append the stored indices for the target value, or default to [-1, -1].

Code Implementation

def substring_xor_queries(binary_string: str, queries: list[list[int]]) -> list[list[int]]:
    best_substrings = {}
    string_length = len(binary_string)
    # Precompute the shortest occurrences of binary values up to 30 bits.
    for length in range(1, 31):
        for start_index in range(string_length - length + 1):
            end_index = start_index + length - 1
            sub_str = binary_string[start_index : end_index + 1]
            decimal_val = int(sub_str, 2)
            # Keep the shortest substring, or the one with minimum left index for ties.
            if decimal_val not in best_substrings:
                best_substrings[decimal_val] = [start_index, end_index]
    query_results = []
    # Resolve each query using the target decimal value.
    for first_val, second_val in queries:
        target_val = first_val ^ second_val
        query_results.append(best_substrings.get(target_val, [-1, -1]))
    return query_results

Big(O) Analysis

Time Complexity
O(N * W + Q) – Here N is the length of binary_string (up to 10^4), W is the maximum bit length (30), and Q is the number of queries. Precomputing all substrings of length up to 30 takes O(N * W) time, and answering each query takes O(1) time.
Space Complexity
O(N * W + Q) – The hash map stores at most N * W unique values and their coordinates, and the results array stores Q query answers.

Optimal Solution

Approach

The problem asks us to find the shortest substring whose binary representation represents the decimal value equal to first XOR second. Since the query values are up to 10^9, any relevant decimal value fits within 30 bits. We can precompute the best substring intervals for all unique decimal values appearing in the binary string and quickly answer each query using a hash map.

Here's how the algorithm would work step-by-step:

  1. Create a hash map to store the best interval coordinates for each decimal value.
  2. Iterate over every possible starting index in the binary string.
  3. Extend substrings up to a length of 30 characters, calculating the decimal value on the fly.
  4. Store or update the shortest range with the earliest start index for each observed decimal value, breaking early if leading zeros are encountered.
  5. Process each query by calculating the target decimal value using bitwise XOR.
  6. Look up the target value in the hash map and append the result or [-1, -1] if not found.

Code Implementation

def substring_xor_queries(binary_string: str, queries: list[list[int]]) -> list[list[int]]:
    # Map each decimal value to its best substring range [start, end]
    val_to_range = {}
    string_length = len(binary_string)
    
    # Precompute all possible values represented by substrings up to length 32
    for start_index in range(string_length):
        current_val = 0
        for length in range(1, min(31, string_length - start_index + 1)):
            current_val = (current_val << 1) | int(binary_string[start_index + length - 1])
            if current_val not in val_to_range:
                val_to_range[current_val] = [start_index, start_index + length - 1]
            elif (val_to_range[current_val][1] - val_to_range[current_val][0] + 1) > length:
                val_to_range[current_val] = [start_index, start_index + length - 1]
            if binary_string[start_index] == '0':
                break
                
    # Resolve each query by looking up the target value formed by first ^ second
    results = []
    for first_val, second_val in queries:
        target_val = first_val ^ second_val
        results.append(val_to_range.get(target_val, [-1, -1]))
        
    return results

Big(O) Analysis

Time Complexity
O(N * B + Q) – N is the length of the binary string, B is the maximum number of bits (around 30), and Q is the number of queries. Precomputing all substrings takes O(N * B) operations, and each query is answered in O(1) time.
Space Complexity
O(N * B + Q) – The hash map stores at most O(N * B) unique decimal values along with their ranges, and the output array stores Q query answers.

Edge Cases

String s consists of all zeros
How to Handle:
Valid substrings will evaluate to zero, and the XOR lookup must match the query values accordingly.
No valid substring exists for a given query
How to Handle:
Return negative one, negative one as the default invalid boundary indicator for that query.
Multiple valid substrings match a query
How to Handle:
Prioritize and track the shortest length substring by updating boundaries when a smaller valid range is found.
Query values are very large integers exceeding standard integer limits
How to Handle:
Precompute and store decimal values of substrings up to thirty bits since larger binary values exceed query bounds.
String s is very long up to ten to the fifth power characters
How to Handle:
Precompute all unique substring decimal values and store their leftmost and rightmost indices in a hash map to ensure efficient O(1) query time.
Query first and second values are identical resulting in an XOR target of zero
How to Handle:
Search for a substring whose binary representation evaluates to zero, such as a single zero character.
Substring has leading zeros like zero zero one
How to Handle:
Treat leading zeros carefully since standard integer parsing evaluates it as one unless explicitly handled as a specific substring range.
Queries array is empty
How to Handle:
Return an empty output array immediately without executing any search logic.