Bitwise AND of sub-array closest to K
Last Updated : 17 May, 2024
Given an integer array arr[] of size N and an integer K, the task is to find the sub-array arr[i….j] where i ? j and compute the bitwise AND of all sub-array elements say X then print the minimum value of |K – X| among all possible values of X.
Example:
Input: arr[] = {1, 6}, K = 3
Output: 2
Sub-array | Bitwise AND | |K – X| |
---|
{1} | 1 | 2 |
{6} | 6 | 3 |
{1, 6} | 1 | 2 |
Input: arr[] = {4, 7, 10}, K = 2
Output: 0
Method 1:
Find the bitwise AND of all possible sub-arrays and keep track of the minimum possible value of |K – X|.
Below is the implementation of the above approach:
C++ // C++ implementation of the approach #include <bits/stdc++.h> using namespace std; // Function to return the minimum possible value // of |K - X| where X is the bitwise AND of // the elements of some sub-array int closetAND(int arr[], int n, int k) { int ans = INT_MAX; // Check all possible sub-arrays for (int i = 0; i < n; i++) { int X = arr[i]; for (int j = i; j < n; j++) { X &= arr[j]; // Find the overall minimum ans = min(ans, abs(k - X)); } } return ans; } // Driver code int main() { int arr[] = { 4, 7, 10 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 2; cout << closetAND(arr, n, k); return 0; }
Java // Java implementation of the approach import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.io.*; class GFG { // Function to return the minimum possible value // of |K - X| where X is the bitwise AND of // the elements of some sub-array static int closetAND(int arr[], int n, int k) { int ans = Integer.MAX_VALUE; // Check all possible sub-arrays for (int i = 0; i < n; i++) { int X = arr[i]; for (int j = i; j < n; j++) { X &= arr[j]; // Find the overall minimum ans = Math.min(ans, Math.abs(k - X)); } } return ans; } // Driver code public static void main(String[] args) { int arr[] = { 4, 7, 10 }; int n = arr.length; int k = 2; System.out.println(closetAND(arr, n, k)); } } // This code is contributed by jit_t
Python # Python implementation of the approach # Function to return the minimum possible value # of |K - X| where X is the bitwise AND of # the elements of some sub-array def closetAND(arr, n, k): ans = 10**9 # Check all possible sub-arrays for i in range(n): X = arr[i] for j in range(i,n): X &= arr[j] # Find the overall minimum ans = min(ans, abs(k - X)) return ans # Driver code arr = [4, 7, 10] n = len(arr) k = 2; print(closetAND(arr, n, k)) # This code is contributed by mohit kumar 29
C# // C# implementation of the approach using System; class GFG { // Function to return the minimum possible value // of |K - X| where X is the bitwise AND of // the elements of some sub-array static int closetAND(int []arr, int n, int k) { int ans = int.MaxValue; // Check all possible sub-arrays for (int i = 0; i < n; i++) { int X = arr[i]; for (int j = i; j < n; j++) { X &= arr[j]; // Find the overall minimum ans = Math.Min(ans, Math.Abs(k - X)); } } return ans; } // Driver code public static void Main() { int []arr = { 4, 7, 10 }; int n = arr.Length; int k = 2; Console.WriteLine(closetAND(arr, n, k)); } } // This code is contributed by AnkitRai01
JavaScript <script> // Javascript implementation of the approach // Function to return the minimum possible value // of |K - X| where X is the bitwise AND of // the elements of some sub-array function closetAND(arr, n, k) { let ans = Number.MAX_VALUE; // Check all possible sub-arrays for(let i = 0; i < n; i++) { let X = arr[i]; for(let j = i; j < n; j++) { X &= arr[j]; // Find the overall minimum ans = Math.min(ans, Math.abs(k - X)); } } return ans; } // Driver code let arr = [4, 7, 10 ]; let n = arr.length; let k = 2; document.write(closetAND(arr, n, k)); // This code is contributed by sravan kumar </script>
PHP <?php // PHP implementation of the approach // Function to return the minimum possible value // of |K - X| where X is the bitwise AND of // the elements of some sub-array function closetAND(&$arr, $n, $k) { $ans = PHP_INT_MAX; // Check all possible sub-arrays for ($i = 0; $i < $n; $i++) { $X = $arr[$i]; for ($j = $i; $j < $n; $j++) { $X &= $arr[$j]; // Find the overall minimum $ans = min($ans, abs($k - $X)); } } return $ans; } // Driver code $arr = array( 4, 7, 10 ); $n = sizeof($arr) / sizeof($arr[0]); $k = 2; echo closetAND($arr, $n, $k); return 0; // This code is contributed by ChitraNayal ?>
Time complexity: O(n2)
Auxiliary Space: O(1), as no extra space is required.
Method 2:
It can be observed that while performing AND operation in the sub-array, the value of X can remain constant or decrease but will never increase.
Hence, we will start from the first element of a sub-array and will be doing bitwise AND and comparing the |K – X| with the current minimum difference until X ? K because after that |K – X| will start increasing.
Below is the implementation of the above approach:
C++ // C++ implementation of the approach #include <bits/stdc++.h> using namespace std; // Function to return the minimum possible value // of |K - X| where X is the bitwise AND of // the elements of some sub-array int closetAND(int arr[], int n, int k) { int ans = INT_MAX; // Check all possible sub-arrays for (int i = 0; i < n; i++) { int X = arr[i]; for (int j = i; j < n; j++) { X &= arr[j]; // Find the overall minimum ans = min(ans, abs(k - X)); // No need to perform more AND operations // as |k - X| will increase if (X <= k) break; } } return ans; } // Driver code int main() { int arr[] = { 4, 7, 10 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 2; cout << closetAND(arr, n, k); return 0; }
Java // Java implementation of the approach class GFG { // Function to return the minimum possible value // of |K - X| where X is the bitwise AND of // the elements of some sub-array static int closetAND(int arr[], int n, int k) { int ans = Integer.MAX_VALUE; // Check all possible sub-arrays for (int i = 0; i < n; i++) { int X = arr[i]; for (int j = i; j < n; j++) { X &= arr[j]; // Find the overall minimum ans = Math.min(ans, Math.abs(k - X)); // No need to perform more AND operations // as |k - X| will increase if (X <= k) break; } } return ans; } // Driver code public static void main(String[] args) { int arr[] = { 4, 7, 10 }; int n = arr.length; int k = 2; System.out.println(closetAND(arr, n, k)); } } // This code is contributed by Princi Singh
Python # Python implementation of the approach import sys # Function to return the minimum possible value # of |K - X| where X is the bitwise AND of # the elements of some sub-array def closetAND(arr, n, k): ans = sys.maxsize; # Check all possible sub-arrays for i in range(n): X = arr[i]; for j in range(i,n): X &= arr[j]; # Find the overall minimum ans = min(ans, abs(k - X)); # No need to perform more AND operations # as |k - X| will increase if (X <= k): break; return ans; # Driver code arr = [4, 7, 10 ]; n = len(arr); k = 2; print(closetAND(arr, n, k)); # This code is contributed by PrinciRaj1992
C# // C# implementation of the approach using System; class GFG { // Function to return the minimum possible value // of |K - X| where X is the bitwise AND of // the elements of some sub-array static int closetAND(int []arr, int n, int k) { int ans = int.MaxValue; // Check all possible sub-arrays for (int i = 0; i < n; i++) { int X = arr[i]; for (int j = i; j < n; j++) { X &= arr[j]; // Find the overall minimum ans = Math.Min(ans, Math.Abs(k - X)); // No need to perform more AND operations // as |k - X| will increase if (X <= k) break; } } return ans; } // Driver code public static void Main(String[] args) { int []arr = { 4, 7, 10 }; int n = arr.Length; int k = 2; Console.WriteLine(closetAND(arr, n, k)); } } // This code has been contributed by 29AjayKumar
JavaScript <script> // Javascript implementation of the approach // Function to return the minimum possible value // of |K - X| where X is the bitwise AND of // the elements of some sub-array function closetAND(arr, n, k) { let ans = Number.MAX_VALUE; // Check all possible sub-arrays for (let i = 0; i < n; i++) { let X = arr[i]; for (let j = i; j < n; j++) { X &= arr[j]; // Find the overall minimum ans = Math.min(ans, Math.abs(k - X)); // No need to perform more AND operations // as |k - X| will increase if (X <= k) break; } } return ans; } let arr = [ 4, 7, 10 ]; let n = arr.length; let k = 2; document.write(closetAND(arr, n, k)); </script>
Time complexity: O(n2)
Auxiliary Space: O(1)
Method 3: Method 3: Using Segment Trees and Binary Search
The time complexity of the brute force approach is O(n^2) because we’re checking the bitwise AND for all possible sub-arrays. We can speed up the process by adopting two new strategies:
1. Segment trees to retrieve the bitwise AND operation result in logarithmic time.
2. Binary search to find the value closest to K in logarithmic time.
Here’s a step-by-step explanation of the approach:
- Create a segment tree to store the bitwise AND of a range of elements in the array. Each node in the segment tree represents the bitwise AND of a range of elements in the array.
- Since the bitwise AND operation is associative, the operation result of a range `[a, b]` can be calculated from the operation results of sub-ranges `[a, k]` and `[k+1, b]` where `a <= k < b`, which enables the efficiency of segment trees for range queries.
- Iterate through the elements of the array, treating each successive element as the starting point of a potential sub-array. For every starting position, we leverage the non-increasing nature of the bitwise AND of an expanding sub-array.
- Implement a binary search for the ending position that maximizes the bitwise AND of that subarray while remaining larger than or equal to K. We check the midpoint for feasibility and, based on that, decide whether to move the endpoint or the starting point of the search.
- As the ending position expands while maintaining the bitwise AND larger than or equal to K, it forms an interval. The largest value of the bitwise AND operation in the interval gives the closest value to K achievable by any sub-array that begins at the current starting position.
- Calculate the absolute difference between K and this maximal bitwise AND, and keep track of the minimum difference achieved over all starting positions.
Below is the implementation of above approach:
C++ #include <algorithm> #include <iostream> #include <vector> using namespace std; #define INF INT32_MAX // Segment Tree class to perform task optimally class SegmentTree { public: vector<int> tree; int n; // Constructor SegmentTree(vector<int>& arr) { n = arr.size(); tree.resize(4 * n); build(arr, 0, 0, n - 1); } // Function to build the Segment Tree void build(vector<int>& arr, int node, int start, int end) { if (start == end) { tree[node] = arr[start]; } else { int mid = (start + end) / 2; build(arr, 2 * node + 1, start, mid); build(arr, 2 * node + 2, mid + 1, end); // bitwise AND of the children nodes tree[node] = tree[2 * node + 1] & tree[2 * node + 2]; } } // Overloading query function to be used recursively int query(int l, int r) { return query(0, 0, n - 1, l, r); } // query function to get bitwise AND of the range int query(int node, int start, int end, int l, int r) { if (r < start || end < l) { return INF; } if (l <= start && end <= r) { return tree[node]; } int mid = (start + end) / 2; int p1 = query(2 * node + 1, start, mid, l, r); int p2 = query(2 * node + 2, mid + 1, end, l, r); // bitwise AND operation result return p1 & p2; } }; int closestAND(vector<int> arr, int k) { int n = arr.size(); SegmentTree st(arr); int ans = INF; for (int i = 0; i < n; i++) { int l = i - 1, r = n - 1, mid; // binary search implementation while (r - l > 1) { mid = (l + r) / 2; if (st.query(i, mid) >= k) l = mid; else r = mid; } if (l != i - 1) ans = min(ans, abs(st.query(i, l) - k)); ans = min(ans, abs(k - st.query(i, r))); } return ans; } int main() { vector<int> arr = { 4, 7, 10 }; int k = 2; cout << closestAND(arr, k); }
Java import java.util.Arrays; // Segment Tree class to perform task optimally class SegmentTree { int[] tree; int n; // Constructor public SegmentTree(int[] arr) { n = arr.length; tree = new int[4 * n]; build(arr, 0, 0, n - 1); } // Function to build the Segment Tree public void build(int[] arr, int node, int start, int end) { if (start == end) { tree[node] = arr[start]; } else { int mid = (start + end) / 2; build(arr, 2 * node + 1, start, mid); build(arr, 2 * node + 2, mid + 1, end); tree[node] = tree[2 * node + 1] & tree[2 * node + 2]; } } // Overloading query function to be used recursively public int query(int l, int r) { return query(0, 0, n - 1, l, r); } // query function to get bitwise AND of the range public int query(int node, int start, int end, int l, int r) { if (r < start || end < l) { return Integer .MAX_VALUE; // Return maximum value if // outside the range } if (l <= start && end <= r) { return tree[node]; // Return node value if range // is completely within the // query range } int mid = (start + end) / 2; int p1 = query(2 * node + 1, start, mid, l, r); int p2 = query(2 * node + 2, mid + 1, end, l, r); return p1 & p2; // Return bitwise AND of children nodes } } public class Main { // Function to find the closest AND value public static int closestAND(int[] arr, int k) { int n = arr.length; SegmentTree st = new SegmentTree(arr); int ans = Integer.MAX_VALUE; for (int i = 0; i < n; i++) { int l = i - 1, r = n - 1, mid; // Binary search implementation while (r - l > 1) { mid = (l + r) / 2; if (st.query(i, mid) >= k) l = mid; else r = mid; } if (l != i - 1) ans = Math.min( ans, Math.abs(st.query(i, l) - k)); ans = Math.min(ans, Math.abs(k - st.query(i, r))); } return ans; } public static void main(String[] args) { int[] arr = { 4, 7, 10 }; int k = 2; System.out.println(closestAND(arr, k)); } } // This code is contributed by shivamgupta0987654321
Python import sys class SegmentTree: def __init__(self, arr): self.n = len(arr) self.tree = [0] * (4 * self.n) self.build(arr, 0, 0, self.n-1) def build(self, arr, node, start, end): if start == end: self.tree[node] = arr[start] else: mid = (start + end) // 2 self.build(arr, 2 * node + 1, start, mid) self.build(arr, 2 * node + 2, mid + 1, end) self.tree[node] = self.tree[2 * node + 1] & self.tree[2 * node + 2] def query(self, l, r): return self._query(0, 0, self.n - 1, l, r) def _query(self, node, start, end, l, r): if r < start or end < l: return sys.maxsize if l <= start and end <= r: return self.tree[node] mid = (start + end) // 2 p1 = self._query(2 * node + 1, start, mid, l, r) p2 = self._query(2 * node + 2, mid + 1, end, l, r) return p1 & p2 def closest_and(arr, k): n = len(arr) st = SegmentTree(arr) ans = sys.maxsize for i in range(n): l, r = i - 1, n - 1 while r - l > 1: mid = (l + r) // 2 if st.query(i, mid) >= k: l = mid else: r = mid if l != i - 1: ans = min(ans, abs(st.query(i, l) - k)) ans = min(ans, abs(k - st.query(i, r))) return ans if __name__=="__main__": arr = [4, 7, 10] k = 2 print(closest_and(arr, k))
JavaScript class SegmentTree { constructor(arr) { this.n = arr.length; this.tree = new Array(4 * this.n).fill(0); this.build(arr, 0, 0, this.n - 1); } build(arr, node, start, end) { if (start === end) { // Leaf node will have a single element this.tree[node] = arr[start]; } else { let mid = Math.floor((start + end) / 2); // Recursively build the segment tree for the left child this.build(arr, 2 * node + 1, start, mid); // Recursively build the segment tree for the right child this.build(arr, 2 * node + 2, mid + 1, end); // Internal node will have the AND of both of its children this.tree[node] = this.tree[2 * node + 1] & this.tree[2 * node + 2]; } } query(l, r) { // Public method to start the query from the root of the segment tree return this._query(0, 0, this.n - 1, l, r); } _query(node, start, end, l, r) { if (r < start || end < l) { // If the range is completely outside the node range, return a large number return Number.MAX_SAFE_INTEGER; } if (l <= start && end <= r) { // If the range is completely inside the node range, return the node value return this.tree[node]; } // If the range is partially inside and partially outside the node range let mid = Math.floor((start + end) / 2); // Query the left child let p1 = this._query(2 * node + 1, start, mid, l, r); // Query the right child let p2 = this._query(2 * node + 2, mid + 1, end, l, r); // Return the AND of both parts return p1 & p2; } } function closestAnd(arr, k) { let n = arr.length; let st = new SegmentTree(arr); let ans = Number.MAX_SAFE_INTEGER; for (let i = 0; i < n; i++) { let l = i - 1; let r = n - 1; while (r - l > 1) { let mid = Math.floor((l + r) / 2); // Perform a binary search to find the appropriate range if (st.query(i, mid) >= k) { l = mid; } else { r = mid; } } if (l !== i - 1) { // Update the answer if a valid range is found ans = Math.min(ans, Math.abs(st.query(i, l) - k)); } // Update the answer with the value from the current range ans = Math.min(ans, Math.abs(k - st.query(i, r))); } // Return the closest AND result to k return ans; } // Example usage: let arr = [4, 7, 10]; let k = 2; console.log(closestAnd(arr, k)); // This code is contributed by shivamgupta0987654321
Time complexity: O(n*log(n)*log(n))
Auxiliary Space: O(n)
Similar Reads
Bitwise AND of all the elements of array
Given an array, arr[] of N integers, the task is to find out the bitwise AND(&) of all the elements of the array. Examples: Input: arr[] = {1, 3, 5, 9, 11} Output: 1 Input: arr[] = {3, 7, 11, 19, 11} Output: 3 Approach: The idea is to traverse all the array elements and compute the bitwise AND f
4 min read
Numbers that are bitwise AND of at least one non-empty sub-array
Given an array 'arr', the task is to find all possible integers each of which is the bitwise AND of at least one non-empty sub-array of 'arr'. Examples: Input: arr = {11, 15, 7, 19} Output: [3, 19, 7, 11, 15] 3 = arr[2] AND arr[3] 19 = arr[3] 7 = arr[2] 11 = arr[0] 15 = arr[1] Input: arr = {5, 2, 8,
12 min read
Bitwise OR of Bitwise AND of all subarrays of an array
Given an array arr[] consisting of N positive integers, the task is to find the Bitwise OR of Bitwise AND of all subarrays of the given arrays. Examples: Input: arr[] = {1, 2, 3}Output: 3Explanation:The following are Bitwise AND of all possible subarrays are: {1}, Bitwise AND is 1.{1, 2}, Bitwise AN
7 min read
Queries to calculate Bitwise AND of an array with updates
Given an array arr[] consisting of N positive integers and a 2D array Q[][] consisting of queries of the type {i, val}, the task for each query is to replace arr[i] by val and calculate the Bitwise AND of the modified array. Examples: Input: arr[] = {1, 2, 3, 4, 5}, Q[][] = {{0, 2}, {3, 3}, {4, 2}}O
15+ min read
Find bitwise OR of all possible sub-arrays
Given an array A of size N where, [Tex]1\leq N \leq 10^{5} [/Tex]. The task is to find the OR of all possible sub-arrays of A and then the OR of all these results. Examples: Input : 1 4 6 Output : 7 All possible subarrays are {1}, {1, 4}, {4, 6} and {1, 4, 6} ORs of these subarrays are 1, 5, 6 and 7
9 min read
Find bitwise AND (&) of all possible sub-arrays
Given an array A of size N where [Tex]1\leq N \leq 10^{5} [/Tex]. The task is to find the AND of all possible sub-arrays of A and then the AND of all these results. Examples: Input : 1 2 3 Output : 0 All possible subarrays are {1}, {2}, {3}, {1, 2}, {2, 3} and {1, 2, 3} ANDs of these subarrays are 1
8 min read
Closest value to K from an unsorted array
Given an array arr[] consisting of N integers and an integer K, the task is to find the array element closest to K. If multiple closest values exist, then print the smallest one. Examples: Input: arr[]={4, 2, 8, 11, 7}, K = 6Output: 7Explanation:The absolute difference between 4 and 6 is |4 â 6| = 2
5 min read
Count pairs from given array with Bitwise OR equal to K
Given an array arr[] consisting of N positive integers and an integer K, the task is to count all pairs possible from the given array with Bitwise OR equal to K. Examples: Input: arr[] = {2, 38, 44, 29, 62}, K = 46Output: 2Explanation: Only the following two pairs are present in the array whose Bitw
5 min read
Sum of bitwise AND of all subarrays
Given an array consisting of N positive integers, find the sum of bit-wise and of all possible sub-arrays of the array. Examples: Input : arr[] = {1, 5, 8} Output : 15 Bit-wise AND of {1} = 1 Bit-wise AND of {1, 5} = 1 Bit-wise AND of {1, 5, 8} = 0 Bit-wise AND of {5} = 5 Bit-wise AND of {5, 8} = 0
8 min read
Greatest contiguous sub-array of size K
Given an array arr[] of integers and an integer K, the task is to find the greatest contiguous sub-array of size K. Sub-array X is said to be greater than sub-array Y if the first non-matching element in both the sub-arrays has a greater value in X than in Y. Examples: Input: arr[] = {1, 4, 3, 2, 5}
6 min read