Queries to minimize sum added to given ranges in an array to make their Bitwise AND non-zero
Last Updated :
10 Jan, 2023
Given an array arr[] consisting of N integers an array Q[][] consisting of queries of the form {l, r}. For each query {l, r}, the task is to determine the minimum sum of all values that must be added to each array element in that range such that the Bitwise AND of all numbers in that range exceeds 0.
Note: Different values can be added to different integers in the given range.
Examples:
Input: arr[] = {1, 2, 4, 8}, Q[][] = {{1, 4}, {2, 3}, {1, 3}}
Output: 3 2 2
Explanation: Binary representation of array elements are as follows:
1 – 0001
2 – 0010
4 – 0100
8 – 1000
For first query {1, 4}, add 1 to all numbers present in the range except the first number. Therefore, Bitwise AND = (1 & 3 & 5 & 9) = 1 and minimum sum of elements added = 3.
For second query {2, 3}, add 2 to 3rd element. Therefore, Bitwise AND = (2 & 6) = 2 and minimum sum of elements added = 2.
For third query {1, 3}, add 1 to 2nd and 3rd elements. Therefore, Bitwise AND = (1 & 3 & 5) = 1 and minimum sum of elements added = 2.
Input: arr[] = {4, 6, 5, 3}, Q[][] = {{1, 4}}
Output: 1
Explanation: Optimal way to make the Bitwise AND non-zero is to add 1 to the last element. Therefore, bitwise AND = (4 & 6 & 5 & 4) = 4 and minimum sum of elements added = 1.
Approach: The idea is to first observe that the Bitwise AND of all the integers in the range [l, r] can only be non-zero if a bit at a particular index is set for each integer in that range.
Follow the steps below to solve the problem:
- Initialize a 2D vector pre where pre[i][j] stores the minimum sum of integers to be added to all integers from index 0 to index i such that, for each of them, their jth bit is set.
- For each element at index i, check for each of its bit from j = 0 to 31.
- Initialize a variable sum with 0.
- If jth bit is set, update pre[i][j] as pre[i][j]=pre[i-1][j] and increment sum by 2j. Otherwise, update pre[i][j] = pre[i-1][j] + 2j - sum where (2j-sum) is the value that must be added to set the jth bit of arr[i].
- Now, for each query {l, r}, the minimum sum required to set jth bit of all elements in the given range is pre[r][j] - pre[l-1][j].
- For each query {l, r}, find the answer for each bit from j = 0 to 31 and print the minimum amongst them.
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to find the min sum required
// to set the jth bit of all integer
void processing(vector<int> v,
vector<vector<long long int> >& pre)
{
// Number of elements
int N = v.size();
// Traverse all elements
for (int i = 0; i < N; i++) {
// Binary representation
bitset<32> b(v[i]);
long long int sum = 0;
// Take previous values
if (i != 0) {
pre[i] = pre[i - 1];
}
// Processing each bit and
// store it in 2d vector
for (int j = 0; j < 32; j++) {
if (b[j] == 1) {
sum += 1ll << j;
}
else {
pre[i][j]
+= (1ll << j) - sum;
}
}
}
}
// Function to print the minimum
// sum for each query
long long int
process_query(vector<vector<int> > Q,
vector<vector<long long int> >& pre)
{
// Stores the sum for each query
vector<int> ans;
for (int i = 0; i < Q.size(); i++) {
// Update wrt 0-based index
--Q[i][0], --Q[i][1];
// Initizlize answer
long long int min1 = INT_MAX;
// Find minimum sum for each bit
if (Q[i][0] == 0) {
for (int j = 0; j < 32; j++) {
min1 = min(pre[Q[i][1]][j], min1);
}
}
else {
for (int j = 0; j < 32; j++) {
min1 = min(pre[Q[i][1]][j]
- pre[Q[i][0] - 1][j],
min1);
}
}
// Store the answer for
// each query
ans.push_back(min1);
}
// Print the answer vector
for (int i = 0; i < ans.size(); i++) {
cout << ans[i] << " ";
}
}
// Driver Code
int main()
{
// Given array
vector<int> arr = { 1, 2, 4, 8 };
// Given Queries
vector<vector<int> > Q
= { { 1, 4 }, { 2, 3 }, { 1, 3 } };
// 2d Prefix vector
vector<vector<long long int> > pre(
100001, vector<long long int>(32, 0));
// Preprocessing
processing(arr, pre);
// Function call for queries
process_query(Q, pre);
return 0;
}
Java
// Java code to implement the approach
import java.util.Arrays;
class Main {
public static void main(String[] args)
{
// Given array
long[] arr = { 1, 2, 4, 8 };
// Given Queries
long[][] Q = { new long[] { 1, 4 }, new long[] { 2, 3 }, new long[] { 1, 3 } };
// 2d Prefix vector
long[][] pre = new long[100001][];
Arrays.setAll(pre, i -> new long[32]);
// Preprocessing
processing(arr, pre);
// Function call for queries
long[] ans = processQuery(Q, pre);
// Print the answer vector
System.out.println(String.join(", ", Arrays.toString(ans)));
}
private static void processing(long[] v, long[][] pre) {
// Number of elements
long N = v.length;
// Traverse all elements
for (long i = 0; i < N; i++) {
// Binary representation
String b = Long.toBinaryString(v[(int) i]);
b = "0".repeat((int) (32 - b.length())) + b;
b = new StringBuilder(b).reverse().toString();
long sum = 0;
// Take previous values
if (i != 0) {
pre[(int) i] = Arrays.copyOf(pre[(int) (i - 1)], pre[(int) (i - 1)].length);
}
// Processing each bit and store it in 2d vector
for (int j = 0; j < 32; j++) {
if (b.charAt(j) == '1') {
sum += (long) Math.pow(2, j);
} else {
pre[(int) i][j] += (long) Math.pow(2, j) - sum;
}
}
}
}
private static long[] processQuery(long[][] Q, long[][] pre) {
// Stores the sum for each query
long[] ans = new long[Q.length];
for (long i = 0; i < Q.length; i++) {
// Update wrt 0-based index
Q[(int) i][0] -= 1;
Q[(int) i][1] -= 1;
// Initialize answer
long min1 = Long.MAX_VALUE;
// Find minimum sum for each bit
if (Q[(int) i][0] == 0) {
for (long j = 0; j < 32; j++) {
min1 =(long) Math.min(pre[(int) Q[(int) i][1]][(int) j], min1);
}
} else {
for (long j = 0; j < 32; j++) {
min1 =(long) Math.min(
pre[(int) Q[(int) i][1]][(int) j] - pre[(int) (Q[(int) i][0] - 1)][(int) j], min1);
}
}
// Store the answer for each query
ans[(int)i] = min1;
}
return ans;
}
}
// This code is contributed by phasing17
Python3
from typing import List, Tuple
def processing(v: List[int], pre: List[List[int]]) -> None:
# Number of elements
N = len(v)
# Traverse all elements
for i in range(N):
# Binary representation
b = bin(v[i])[2:]
b = "0"*(32-len(b)) + b
b = b[::-1]
sum = 0
# Take previous values
if i != 0:
pre[i] = pre[i-1][:]
# Processing each bit and store it in 2d vector
for j in range(32):
if b[j] == "1":
sum += 1 << j
else:
pre[i][j] += (1 << j) - sum
def process_query(Q: List[Tuple[int, int]], pre: List[List[int]]) -> List[int]:
# Stores the sum for each query
ans = []
for i in range(len(Q)):
# Update wrt 0-based index
Q[i] = (Q[i][0]-1, Q[i][1]-1)
# Initialize answer
min1 = float("inf")
# Find minimum sum for each bit
if Q[i][0] == 0:
for j in range(32):
min1 = min(pre[Q[i][1]][j], min1)
else:
for j in range(32):
min1 = min(pre[Q[i][1]][j] - pre[Q[i][0]-1][j], min1)
# Store the answer for each query
ans.append(min1)
return ans
# Given array
arr = [1, 2, 4, 8]
# Given Queries
Q = [(1, 4), (2, 3), (1, 3)]
# 2d Prefix vector
pre = [[0]*32 for _ in range(100001)]
# Preprocessing
processing(arr, pre)
# Function call for queries
ans = process_query(Q, pre)
# Print the answer vector
print(ans)
# This code is contributed by phasing17.
C#
// C# code to implement the approach
using System;
using System.Linq;
class Program {
static void Main(string[] args)
{
// Given array
long[] arr = { 1, 2, 4, 8 };
// Given Queries
long[][] Q
= { new long[] { 1, 4 }, new long[] { 2, 3 },
new long[] { 1, 3 } };
// 2d Prefix vector
long[][] pre = new long[100001][]
.Select(x => new long[32])
.ToArray();
// Preprocessing
Processing(arr, pre);
// Function call for queries
long[] ans = ProcessQuery(Q, pre);
// Prlong the answer vector
Console.WriteLine(string.Join(", ", ans));
}
private static void Processing(long[] v, long[][] pre)
{
// Number of elements
long N = v.Length;
// Traverse all elements
for (long i = 0; i < N; i++) {
// Binary representation
string b = Convert.ToString(v[i], 2);
b = "0".PadLeft(32 - b.Length, '0') + b;
b = new string(b.Reverse().ToArray());
long sum = 0;
// Take previous values
if (i != 0) {
pre[i] = pre[i - 1].ToArray();
}
// Processing each bit and store it in 2d vector
for (int j = 0; j < 32; j++) {
if (b[j] == '1') {
sum += (long)Math.Pow(2, j);
}
else {
pre[i][j] += (long)Math.Pow(2, j) - sum;
}
}
}
}
private static long[] ProcessQuery(long[][] Q,
long[][] pre)
{
// Stores the sum for each query
long[] ans = new long[Q.Length];
for (long i = 0; i < Q.Length; i++) {
// Update wrt 0-based index
Q[i][0] -= 1;
Q[i][1] -= 1;
// Initialize answer
long min1 = long.MaxValue;
// Find minimum sum for each bit
if (Q[i][0] == 0) {
for (long j = 0; j < 32; j++) {
min1 = Math.Min(pre[Q[i][1]][j], min1);
}
}
else {
for (long j = 0; j < 32; j++) {
min1 = Math.Min(
pre[Q[i][1]][j]
- pre[Q[i][0] - 1][j],
min1);
}
}
// Store the answer for each query
ans[i] = min1;
}
return ans;
}
}
// This code is contributed by phasing17
JavaScript
// JS program to implement the above approach
const processing = (v, pre) => {
// Number of elements
const N = v.length;
// Traverse all elements
for (let i = 0; i < N; i++) {
// Binary representation
let b = v[i].toString(2);
b = "0".repeat(32 - b.length) + b;
b = b.split("").reverse().join("");
let sum = 0;
// Take previous values
if (i !== 0) {
pre[i] = pre[i - 1].slice();
}
// Processing each bit and store it in 2d vector
for (let j = 0; j < 32; j++) {
if (b[j] === "1") {
sum += 2 ** j;
} else {
pre[i][j] += 2 ** j - sum;
}
}
}
};
const processQuery = (Q, pre) => {
// Stores the sum for each query
const ans = [];
for (let i = 0; i < Q.length; i++) {
// Update wrt 0-based index
Q[i] = [Q[i][0] - 1, Q[i][1] - 1];
// Initialize answer
let min1 = Number.POSITIVE_INFINITY;
// Find minimum sum for each bit
if (Q[i][0] === 0) {
for (let j = 0; j < 32; j++) {
min1 = Math.min(pre[Q[i][1]][j], min1);
}
} else {
for (let j = 0; j < 32; j++) {
min1 = Math.min(pre[Q[i][1]][j] - pre[Q[i][0] - 1][j], min1);
}
}
// Store the answer for each query
ans.push(min1);
}
return ans;
};
// Given array
const arr = [1, 2, 4, 8];
// Given Queries
const Q = [[1, 4], [2, 3], [1, 3]];
// 2d Prefix vector
const pre = new Array(100001).fill(0).map(() => new Array(32).fill(0));
// Preprocessing
processing(arr, pre);
// Function call for queries
const ans = processQuery(Q, pre);
// Print the answer vector
console.log(ans);
// This code is implemented by Phasing17
Time Complexity: O(N*32 + sizeof(Q)*32)
Auxiliary Space: O(N*32)
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Array Data Structure Guide In this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
4 min read
Sorting Algorithms A Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read