Range query for count of set bits
Last Updated :
27 Apr, 2023
Given an array of positive integer and q query which contains two integers, L & R. Task is to find the number of set bits for a given range.
Prerequisite : Bitwise Hacks
Examples :
Input : Arr[] = { 1, 5, 6, 10, 9, 4 }
Query : 2
L & R
1 5
2 4
Output : 9
6
Input : Arr[] = { 1, 10, 5, 2, 8, 11, 15 }
Query : 2
L & R
2 4
1 5
Output : 4
9
Simple solution to this problem is to run a loop from L to R and count number of set bits in a Range. This solution take O(nlog(s)) ( where s is bits size ) for each query.
Efficient solution is based on the fact that if we store count of all set bits of numbers in an array "BitCounts", then we answer each query in O(1) time. So, start traversing the elements of array and count set bits for each element and store in array. Now, find cumulative sum of this array. This array will help in answering queries.
BitCount[] that will store the count of set bits
in a number.
Run a Loop from 0 to 31 "for 32 bits size integer "
-> mark elements with i'th bit set
Run an inner Loop from 0 to size of Array "Arr"
-> Check whether the current bit is set or not
-> if it's set then mark it.
long temp = arr[j] >> i;
if (temp %2 != 0)
BitCount[j] += 1
Below is implementation of above idea.
C++
// C++ program to Range query for
// Count number of set bits
#include <bits/stdc++.h>
using namespace std;
// 2-D array that will stored the count
// of bits set in element of array
int BitCount[10000] = { 0 };
// Function store the set bit
// count in BitCount Array
void fillSetBitsMatrix(int arr[], int n)
{
// traverse over all bits
for (int i = 0; i < 32; i++) {
// mark elements with i'th bit set
for (int j = 0; j < n; j++) {
// Check whether the current bit is
// set or not if it's set then mark it.
long temp = arr[j] >> i;
if (temp % 2 != 0)
BitCount[j] += 1;
}
}
// store cumulative sum of bits
for (int i = 1; i < n; i++)
BitCount[i] += BitCount[i - 1];
}
// Function to process queries
void Query(int Q[][2], int q)
{
for (int i = 0; i < q; i++)
cout << (BitCount[Q[i][1]] -
BitCount[Q[i][0] - 1]) << endl;
}
// Driver Code
int main()
{
int Arr[] = { 1, 5, 6, 10, 9, 4, 67 };
int n = sizeof(Arr) / sizeof(Arr[0]);
fillSetBitsMatrix(Arr, n);
int q = 2;
int Q[2][2] = { { 1, 5 }, { 2, 6 } };
Query(Q, q);
return 0;
}
Java
// Java program to Range query for
// Count number of set bits
import java.io.*;
class GFG {
// 2-D array that will stored the count
// of bits set in element of array
static int BitCount[] = new int[10000];
// Function store the set bit
// count in BitCount Array
static void fillSetBitsMatrix(int arr[], int n)
{
// traverse over all bits
for (int i = 0; i < 32; i++) {
// mark elements with i'th bit set
for (int j = 0; j < n; j++) {
// Check whether the current
// bit is set or not if it's
// set then mark it.
long temp = arr[j] >> i;
if (temp % 2 != 0)
BitCount[j] += 1;
}
}
// store cumulative sum of bits
for (int i = 1; i < n; i++)
BitCount[i] += BitCount[i - 1];
}
// Function to process queries
static void Query(int Q[][], int q)
{
for (int i = 0; i < q; i++)
System.out.println( (BitCount[Q[i][1]]
- BitCount[Q[i][0] - 1]));
}
// Driver Code
public static void main (String[] args)
{
int Arr[] = { 1, 5, 6, 10, 9, 4, 67 };
int n = Arr.length;
fillSetBitsMatrix(Arr, n);
int q = 2;
int Q[][] = { { 1, 5 }, { 2, 6 } };
Query(Q, q);
}
}
// This code is contributed by anuj_67.
Python3
# Python3 program to Range query for
# Count number of set bits
# 2-D array that will stored the count
# of bits set in element of array
BitCount = [0] * 10000
# Function store the set bit
# count in BitCount Array
def fillSetBitsmatrix(arr: list, n: int):
global BitCount
# traverse over all bits
for i in range(32):
# mark elements with i'th bit set
for j in range(n):
# Check whether the current bit is
# set or not if it's set then mark it.
temp = arr[j] >> i
if temp % 2 != 0:
BitCount[j] += 1
# store cumulative sum of bits
for i in range(1, n):
BitCount[i] += BitCount[i - 1]
# Function to process queries
def Query(Q: list, q: int):
for i in range(q):
print(BitCount[Q[i][1]] - BitCount[Q[i][0] - 1])
# Driver Code
if __name__ == "__main__":
Arr = [1, 5, 6, 10, 9, 4, 67]
n = len(Arr)
fillSetBitsmatrix(Arr, n)
q = 2
Q = [(1, 5), (2, 6)]
Query(Q, q)
# This code is contributed by
# sanjeev2552
C#
// C# program to Range query for
// Count number of set bits
using System;
class GFG {
// 2-D array that will stored the count
// of bits set in element of array
static int []BitCount = new int[10000];
// Function store the set bit
// count in BitCount Array
static void fillSetBitsMatrix(int []arr, int n)
{
// traverse over all bits
for (int i = 0; i < 32; i++) {
// mark elements with i'th bit set
for (int j = 0; j < n; j++) {
// Check whether the current
// bit is set or not if it's
// set then mark it.
long temp = arr[j] >> i;
if (temp % 2 != 0)
BitCount[j] += 1;
}
}
// store cumulative sum of bits
for (int i = 1; i < n; i++)
BitCount[i] += BitCount[i - 1];
}
// Function to process queries
static void Query(int [,]Q, int q)
{
for (int i = 0; i < q; i++)
Console.WriteLine( (BitCount[Q[i,1]]
- BitCount[Q[i,0] - 1]));
}
// Driver Code
public static void Main ()
{
int []Arr = { 1, 5, 6, 10, 9, 4, 67 };
int n = Arr.Length;
fillSetBitsMatrix(Arr, n);
int q = 2;
int [,]Q = { { 1, 5 }, { 2, 6 } };
Query(Q, q);
}
}
// This code is contributed by anuj_67.
JavaScript
<script>
// Javascript program to Range query for
// Count number of set bits
// 2-D array that will stored the count
// of bits set in element of array
var BitCount = Array.from({length: 10000}, (_, i) => 0);
// Function store the set bit
// count in BitCount Array
function fillSetBitsMatrix(arr, n)
{
// traverse over all bits
for(i = 0; i < 32; i++)
{
// mark elements with i'th bit set
for(j = 0; j < n; j++)
{
// Check whether the current
// bit is set or not if it's
// set then mark it.
var temp = arr[j] >> i;
if (temp % 2 != 0)
BitCount[j] += 1;
}
}
// store cumulative sum of bits
for(i = 1; i < n; i++)
BitCount[i] += BitCount[i - 1];
}
// Function to process queries
function Query(Q, q)
{
for(i = 0; i < q; i++)
document.write((BitCount[Q[i][1]] -
BitCount[Q[i][0] - 1]) + "<br>");
}
// Driver Code
var Arr = [ 1, 5, 6, 10, 9, 4, 67 ];
var n = Arr.length;
fillSetBitsMatrix(Arr, n);
var q = 2;
var Q = [ [ 1, 5 ], [ 2, 6 ] ];
Query(Q, q);
// This code is contributed by Rajput-Ji
</script>
Time Complexity : O(1) for each query.
Auxiliary Space: O(k) where k=10000
Similar Reads
Count set bits in a range Given a non-negative number n and two values l and r. The problem is to count the number of set bits in the range l to r in the binary representation of n, i.e, to count set bits from the rightmost lth bit to the rightmost rth bit. Constraint: 1 <= l <= r <= number of bits in the binary rep
6 min read
Count unset bits in a range Given a non-negative number n and two values l and r. The problem is to count the number of unset bits in the range l to r in the binary representation of n, i.e, to count unset bits from the rightmost lth bit to the rightmost rth bit.Examples: Input : n = 42, l = 2, r = 5 Output : 2 (42)10 = (10101
6 min read
Count unset bits of a number Given a number n, count unset bits after MSB (Most Significant Bit).Examples : Input : 17 Output : 3 Binary of 17 is 10001 so unset bit is 3 Input : 7 Output : 0 A Simple Solution is to traverse through all bits and count unset bits. C++ // C++ program to count unset bits in an integer #include <
7 min read
Count total set bits in all numbers from range L to R Given two positive integers L and R, the task is to count the total number of set bits in the binary representation of all the numbers from L to R. Examples: Input: L = 3, R = 5 Output: 5 Explanation: (3)10 = (11)2, (4)10 = (100)2, (5)10 = (101)2 So, Total set bit in range 3 to 5 is 5 Input: L = 10,
15+ min read
Count set bits in index range [L, R] in given Array for Q queries Given an array arr[] containing N integers and an array queries[] containing Q queries in the form of {L, R}, the task is to count the total number of set bits from L to R in array arr for each query. Example: Input: arr[]={1, 2, 3, 4, 5, 6}, queries[]={{0, 2}, {1, 1}, {3, 5}}Output:425Explanation:Q
6 min read