![]() |
VOOZH | about |
Given a positive integer array A[] of size N and Q queries. Given a 2D integer array Queries[][] of length Q where each query has four integers l1, r1, l2, r2, the task is to calculate (Al1 & Al1+1 & Al1+2 ...& Ar1) | (Al2 & Al2+1 & Al2+2....& Ar2) and return an integer array answer of length Q where answer[i] represents the answer for ith query.
Examples:
Input: N = 5, Q = 2, A[] = {2, 3, 7, 11, 15}, Queries[][] = {{2, 4, 3, 5}, {1, 5, 2, 3}}
Output: {3, 3}
Explanation:
- for query 2 4 3 5: answer = (3&7&11) | (7&11&15) = (3) | (3) = 3
- for query 1 5 2 3: answer = (2&3&7&11&15) | (3&7) = (2) | (3) = 3
Input: N = 6, Q = 2, A[] = {3, 7, 13, 12, 14, 15}, Queries[][] = {{1, 4, 2, 5}, {1, 2, 3, 6}}
Output: {4 15}
Explanation:
- for query 1 4 2 5: answer = (3&7&13&12) | (7&13&12&14) = (0) | (4) = 4
- for query 1 2 3 6: answer = (3&7) | (13&12&14&15) = (3) | (12) = 15
Approach: This can be solved with the following idea:
The intuition behind this solution is to utilize bitwise operations efficiently. By pre-calculating the counts of each bit up to a certain index, the code can quickly determine if a particular bit position is set in a given subarray. The final answer is calculated by performing bitwise OR operations for the bits that satisfy the conditions specified in the query.
Below are the steps involved:
Below is the implementation of the code:
3 3
Time Complexity: O(N + Q)
Auxiliary Space: O(N)