Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Substring XOR Queries

Updated
4 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "2564" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.

Problem Statement

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

Explanation

Here's a breakdown of the solution, followed by the Python code:

  • Precompute Substring Values: Iterate through the string s and calculate the decimal value of all possible substrings. Store these values along with their starting indices in a dictionary or similar data structure for fast lookup. We only need to consider substrings of a reasonable length because the target values are capped at 10^9.
  • Process Queries: For each query [first, second], compute the target decimal value needed (target = first ^ second). Check if this target value exists among the precomputed substring values.
  • Find Optimal Substring: If the target value exists, iterate through the possible substrings (starting from the smallest index) and find the substring with the minimum starting index. If not found, return [-1, -1].

  • Runtime Complexity: O(n*l + q*k), where n is the length of s, l is the maximum substring length we consider, q is the number of queries, and k is the number of matching substrings for a query. In the worst case, the storage complexity is O(n*l).

def solve():
    s = input()
    queries = eval(input())  # Assuming queries are given as a list of lists

    def find_substrings(s, queries):
        n = len(s)
        substring_values = {}
        max_len = 30  # Sufficient length as 2**30 > 10**9

        for i in range(n):
            val = 0
            for j in range(i, min(i + max_len, n)):
                val = (val << 1) + (ord(s[j]) - ord('0'))
                substring_values.setdefault(val, []).append((i, j))

        ans = []
        for first, second in queries:
            target = first ^ second
            if target in substring_values:
                candidates = substring_values[target]
                best_start = float('inf')
                best_end = -1
                for start, end in candidates:
                    if start < best_start:
                        best_start = start
                        best_end = end
                ans.append([best_start, best_end])
            else:
                ans.append([-1, -1])
        return ans

    result = find_substrings(s, queries)
    print(result)

# Example usage (for local testing) - Remove for online submission
# Input:
# 101101
# [[0,5],[1,2]]
#
# Output:
# [[0, 2], [2, 3]]

# Input:
# 0101
# [[12,8]]
#
# Output:
# [[-1, -1]]

# Input:
# 1
# [[4,5]]
#
# Output:
# [[0, 0]]

#Emulate input() calls for testing
class MockInput:
    def __init__(self, inputs):
        self.inputs = inputs
        self.current = 0

    def __call__(self):
        if self.current < len(self.inputs):
            result = self.inputs[self.current]
            self.current += 1
            return result
        else:
            return ""  # Or raise an exception if input is exhausted

# comment out the lines below before submitting to online judges
# input = MockInput(["101101", "[[0,5],[1,2]]"])
# solve()


    # Code
    ```python
    def find_substrings(s, queries):    n = len(s)
    substring_values = {}
    max_len = 30  # Sufficient length as 2**30 > 10**9

    for i in range(n):
        val = 0
        for j in range(i, min(i + max_len, n)):
            val = (val << 1) + (ord(s[j]) - ord('0'))
            substring_values.setdefault(val, []).append((i, j))

    ans = []
    for first, second in queries:
        target = first ^ second
        if target in substring_values:
            candidates = substring_values[target]
            best_start = float('inf')
            best_end = -1
            for start, end in candidates:
                if start < best_start:
                    best_start = start
                    best_end = end
            ans.append([best_start, best_end])
        else:
            ans.append([-1, -1])
    return ans

More from this blog

C

Chatmagic blog

2894 posts