#2564

Substring XOR Queries

Medium
ArrayHash TableStringBit ManipulationHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n + q)
Space
O(1)
O(n)
💡

Intuition

Time O(n + q)Space O(n)

The optimal solution preprocesses all substrings of length up to 30 and stores their decimal values in a dictionary. This allows for quick lookups during query processing, significantly reducing time complexity.

⚙️

Algorithm

3 steps
  1. 1Step 1: Preprocess all substrings of s with lengths up to 30 and store their decimal values along with their starting and ending indices in a dictionary.
  2. 2Step 2: For each query, calculate the target value as target = second[i] ^ first[i].
  3. 3Step 3: Check if the target exists in the preprocessed dictionary; if it does, return the corresponding indices; otherwise, return [-1, -1].
solution.py14 lines
1def substring_xor_queries(s, queries):
2    n = len(s)
3    substrings = {}
4    for i in range(n):
5        num = 0
6        for j in range(i, min(n, i + 30)):
7            num = (num << 1) | (int(s[j]))
8            if num not in substrings:
9                substrings[num] = (i, j)
10    results = []
11    for first, second in queries:
12        target = first ^ second
13        results.append(substrings.get(target, (-1, -1)))
14    return results

Complexity note: The preprocessing step takes O(n) time to build the dictionary, and each query can be answered in O(1) time, leading to a total of O(n + q) for n substrings and q queries.

  • 1Preprocessing substrings allows for efficient query resolution.
  • 2Only substrings of length up to 30 need to be considered due to the constraints.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.