g2501_2600.s2564_substring_xor_queries.Solution Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of leetcode-in-java21 Show documentation
Show all versions of leetcode-in-java21 Show documentation
Java-based LeetCode algorithm problem solutions, regularly updated
package g2501_2600.s2564_substring_xor_queries;
// #Medium #Array #String #Hash_Table #Bit_Manipulation
// #2023_08_21_Time_26_ms_(95.83%)_Space_84.1_MB_(80.56%)
import java.util.HashMap;
import java.util.Map;
/**
* 2564 - Substring XOR Queries\.
*
* Medium
*
* 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
**/
public class Solution {
public int[][] substringXorQueries(String s, int[][] queries) {
int[][] ans = new int[queries.length][2];
Map map = new HashMap<>();
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '0') {
map.putIfAbsent(0, new int[] {i, i});
continue;
}
int value = 0;
for (int j = i; j <= Math.min(i + 30, s.length() - 1); j++) {
value = (value << 1) + (s.charAt(j) - '0');
map.putIfAbsent(value, new int[] {i, j});
}
}
int i = 0;
for (int[] q : queries) {
ans[i++] = map.getOrDefault(q[0] ^ q[1], new int[] {-1, -1});
}
return ans;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy