Sudo Placement | Range Queries
Last Updated :
22 Feb, 2023
Given Q queries, with each query consisting of two integers L and R, the task is to find the total numbers between L and R (Both inclusive), having almost three set bits in their binary representation.
Examples:
Input : Q = 2
L = 3, R = 7
L = 10, R = 16
Output : 5
6
For the first query, valid numbers are 3, 4, 5, 6, and 7.
For the second query, valid numbers are 10, 11, 12, 13, 14 and 16.
Prerequisites : Bit Manipulation and Binary Search
Method 1 (Simple): A naive approach is to traverse all the numbers between L and R and find the number of set bits in each of those numbers. Increment a counter variable if a number does not have more than 3 set bits. Return answer as counter. Note : This approach is very inefficient since the numbers L and R may have large values (upto 1018).
Method 2 (Efficient) : An efficient approach required here is precomputation. Since the values of L and R lie within the range [0, 1018] (both inclusive), thus their binary representation can have at most 60 bits. Now, since the valid numbers are those having almost 3 set bits, find them by generating all bit sequences of 60 bits with less than or equal to 3 set bits. This can be done by fixing, ith, jth and kth bits for all i, j, k from (0, 60). Once, all the valid numbers are generated in sorted order, apply binary search to find the count of those numbers that lie within the given range.
Below is the implementation of above approach.
C++
// CPP program to find the numbers
// having atmost 3 set bits within
// a given range
#include <bits/stdc++.h>
using namespace std;
#define LL long long int
// This function prints the required answer for each query
void answerQueries(LL Q, vector<pair<LL, LL> > query)
{
// Set of Numbers having at most 3 set bits
// arranged in non-descending order
set<LL> s;
// 0 set bits
s.insert(0);
// Iterate over all possible combinations of
// i, j and k for 60 bits
for (int i = 0; i <= 60; i++) {
for (int j = i; j <= 60; j++) {
for (int k = j; k <= 60; k++) {
// 1 set bit
if (j == i && i == k)
s.insert(1LL << i);
// 2 set bits
else if (j == k && i != j) {
LL x = (1LL << i) + (1LL << j);
s.insert(x);
}
else if (i == j && i != k) {
LL x = (1LL << i) + (1LL << k);
s.insert(x);
}
else if (i == k && i != j) {
LL x = (1LL << k) + (1LL << j);
s.insert(x);
}
// 3 set bits
else {
LL x = (1LL << i) + (1LL << j) + (1LL << k);
s.insert(x);
}
}
}
}
vector<LL> validNumbers;
for (auto val : s)
validNumbers.push_back(val);
// Answer Queries by applying binary search
for (int i = 0; i < Q; i++) {
LL L = query[i].first;
LL R = query[i].second;
// Swap both the numbers if L is greater than R
if (R < L)
swap(L, R);
if (L == 0)
cout << (upper_bound(validNumbers.begin(), validNumbers.end(),
R) - validNumbers.begin()) << endl;
else
cout << (upper_bound(validNumbers.begin(), validNumbers.end(),
R) - upper_bound(validNumbers.begin(), validNumbers.end(),
L - 1)) << endl;
}
}
// Driver Code
int main()
{
// Number of Queries
int Q = 2;
vector<pair<LL, LL> > query(Q);
query[0].first = 3;
query[0].second = 7;
query[1].first = 10;
query[1].second = 16;
answerQueries(Q, query);
return 0;
}
Java
// Java program to find the numbers
// having atmost 3 set bits within
// a given range
import java.util.*;
import java.io.*;
public class RangeQueries {
//Class to store the L and R range of a query
static class Query {
long L;
long R;
}
//It returns index of first element which is greater than searched value
//If searched element is bigger than any array element function
// returns first index after last element.
public static int upperBound(ArrayList<Long> validNumbers,
Long value)
{
int low = 0;
int high = validNumbers.size()-1;
while(low < high){
int mid = (low + high)/2;
if(value >= validNumbers.get(mid)){
low = mid+1;
} else {
high = mid;
}
}
return low;
}
public static void answerQueries(ArrayList<Query> queries){
// Set of Numbers having at most 3 set bits
// arranged in non-descending order
Set<Long> allNum = new HashSet<>();
//0 Set bits
allNum.add(0L);
//Iterate over all possible combinations of i, j, k for
// 60 bits. And add all the numbers with 0, 1 or 2 set bits into
// the set allNum.
for(int i=0; i<=60; i++){
for(int j=0; j<=60; j++){
for(int k=0; k<=60; k++){
//For one set bit, check if i, j, k are equal
//if yes, then set that bit and add it to the set
if(i==j && j==k){
allNum.add(1L << i);
}
//For two set bits, two of the three variable i,j,k
//will be equal and the third will not be. Set both
//the bits where two variables are equal and the bit
//which is not equal, and add it to the set
else if(i==j && j != k){
long toAdd = (1L << i) + (1L << k);
allNum.add(toAdd);
}
else if(i==k && k != j){
long toAdd = (1L << i) + (1L << j);
allNum.add(toAdd);
}
else if(j==k && k != i){
long toAdd = (1L << j) + (1L << i);
allNum.add(toAdd);
}
//Setting all the 3 bits
else {
long toAdd = (1L << i) + (1L << j) + (1L << k);
allNum.add(toAdd);
}
}
}
}
//Adding all the numbers to an array list so that it can be sorted
ArrayList<Long> validNumbers = new ArrayList<>();
for(Long num: allNum){
validNumbers.add(num);
}
Collections.sort(validNumbers);
//Answer queries by applying binary search
for(int i=0; i<queries.size(); i++){
long L = queries.get(i).L;
long R = queries.get(i).R;
//Swap L and R if R is smaller than L
if(R < L){
long temp = L;
L = R;
R = temp;
}
if(L == 0){
int indxOfLastNum = upperBound(validNumbers, R);
System.out.println(indxOfLastNum+1);
}
else {
int indxOfFirstNum = upperBound(validNumbers, L);
int indxOfLastNum = upperBound(validNumbers, R);
System.out.println((indxOfLastNum - indxOfFirstNum +1));
}
}
}
public static void main(String[] args){
int Q = 2;
ArrayList<Query> queries = new ArrayList<>();
Query q1 = new Query();
q1.L = 3;
q1.R = 7;
Query q2 = new Query();
q2.L = 10;
q2.R = 16;
queries.add(q1);
queries.add(q2);
answerQueries(queries);
}
}
Python3
#Python3 program to find the numbers
# having atmost 3 set bits within
# a given range
import bisect
# This function prints the required answer for each query
def answerQueries(Q, query):
# Set of Numbers having at most 3 set bits
# arranged in non-descending order
s = set()
# 0 set bits
s.add(0)
# Iterate over all possible combinations of
# i, j and k for 60 bits
for i in range(61):
for j in range(i, 61):
for k in range(j, 61):
# 1 set bit
if (j == i and i == k):
s.add(1 << i)
# 2 set bits
elif (j == k and i != j):
x = (1 << i) + (1 << j)
s.add(x)
elif (i == j and i != k):
x = (1 << i) + (1 << k)
s.add(x)
elif (i == k and i != j):
x = (1 << k) + (1 << j)
s.add(x)
# 3 set bits
else:
x = (1 << i) + (1 << j) + (1 << k)
s.add(x);
validNumbers = []
for val in sorted(s):
validNumbers.append(val)
# Answer Queries by applying binary search
for i in range(Q):
L = query[i][0]
R = query[i][1]
# Swap both the numbers if L is greater than R
if (R < L):
L, R = R, L
if (L == 0):
print(bisect.bisect_right(validNumbers, R))
else:
print(bisect.bisect_right(validNumbers, R) - bisect.bisect_right(validNumbers, L - 1))
# Driver Code
#Number of Queries
Q = 2
query = [[3, 7], [10, 16]]
answerQueries(Q, query)
#This code is contributed by phasing17
C#
// C# program to find the numbers
// having atmost 3 set bits within
// a given range
using System;
using System.Collections.Generic;
// Class to store the L and R range of a query
public class Query {
public long L;
public long R;
}
public class RangeQueries {
// It returns index of first element which is greater
// than searched value If searched element is bigger
// than any array element function returns first index
// after last element.
public static int upperBound(List<long> validNumbers,
long value)
{
int low = 0;
int high = validNumbers.Count - 1;
while (low < high) {
int mid = (low + high) / 2;
if (value >= validNumbers[mid]) {
low = mid + 1;
}
else {
high = mid;
}
}
return low;
}
public static void answerQueries(List<Query> queries)
{
// Set of Numbers having at most 3 set bits
// arranged in non-descending order
HashSet<long> allNum = new HashSet<long>();
// 0 Set bits
allNum.Add(0L);
// Iterate over all possible combinations of i, j, k
// for
// 60 bits. And add all the numbers with 0, 1 or 2
// set bits into the set allNum.
for (int i = 0; i <= 60; i++) {
for (int j = 0; j <= 60; j++) {
for (int k = 0; k <= 60; k++) {
// For one set bit, check if i, j, k are
// equal if yes, then set that bit and
// add it to the set
if (i == j && j == k) {
allNum.Add(1L << i);
}
// For two set bits, two of the three
// variable i,j,k will be equal and the
// third will not be. Set both the bits
// where two variables are equal and the
// bit which is not equal, and add it to
// the set
else if (i == j && j != k) {
long toAdd = (1L << i) + (1L << k);
allNum.Add(toAdd);
}
else if (i == k && k != j) {
long toAdd = (1L << i) + (1L << j);
allNum.Add(toAdd);
}
else if (j == k && k != i) {
long toAdd = (1L << j) + (1L << i);
allNum.Add(toAdd);
}
// Setting all the 3 bits
else {
long toAdd = (1L << i) + (1L << j)
+ (1L << k);
allNum.Add(toAdd);
}
}
}
}
// Adding all the numbers to an array list so that
// it can be sorted
List<long> validNumbers = new List<long>();
foreach(long num in allNum)
{
validNumbers.Add(num);
}
validNumbers.Sort();
// Answer queries by applying binary search
for (int i = 0; i < queries.Count; i++) {
long L = queries[i].L;
long R = queries[i].R;
// Swap L and R if R is smaller than L
if (R < L) {
long temp = L;
L = R;
R = temp;
}
if (L == 0) {
int indxOfLastNum
= upperBound(validNumbers, R);
Console.WriteLine(indxOfLastNum + 1);
}
else {
int indxOfFirstNum
= upperBound(validNumbers, L);
int indxOfLastNum
= upperBound(validNumbers, R);
Console.WriteLine(
(indxOfLastNum - indxOfFirstNum + 1));
}
}
}
// Driver code
public static void Main(string[] args)
{
List<Query> queries = new List<Query>();
Query q1 = new Query();
q1.L = 3;
q1.R = 7;
Query q2 = new Query();
q2.L = 10;
q2.R = 16;
queries.Add(q1);
queries.Add(q2);
// Function call
answerQueries(queries);
}
}
// This code is contributed by phasing.
JavaScript
//javascript equivalent
class Query {
constructor(L, R) {
this.L = L;
this.R = R;
}
}
//It returns index of first element which is greater than searched value
//If searched element is bigger than any array element function
// returns first index after last element.
function upperBound(validNumbers, value) {
let low = 0;
let high = validNumbers.length - 1;
while (low < high) {
let mid = Math.floor((low + high) / 2);
if (value >= validNumbers[mid]) {
low = mid + 1;
} else {
high = mid;
}
}
return low;
}
function answerQueries(queries) {
// Set of Numbers having at most 3 set bits
// arranged in non-descending order
let allNum = new Set();
//0 Set bits
allNum.add(0);
//Iterate over all possible combinations of i, j, k for
// 60 bits. And add all the numbers with 0, 1 or 2 set bits into
// the set allNum.
for (let i = 0; i <= 60; i++) {
for (let j = 0; j <= 60; j++) {
for (let k = 0; k <= 60; k++) {
//For one set bit, check if i, j, k are equal
//if yes, then set that bit and add it to the set
if (i == j && j == k) {
allNum.add(1 << i);
}
//For two set bits, two of the three variable i,j,k
//will be equal and the third will not be. Set both
//the bits where two variables are equal and the bit
//which is not equal, and add it to the set
else if (i == j && j != k) {
let toAdd = (1 << i) + (1 << k);
allNum.add(toAdd);
} else if (i == k && k != j) {
let toAdd = (1 << i) + (1 << j);
allNum.add(toAdd);
} else if (j == k && k != i) {
let toAdd = (1 << j) + (1 << i);
allNum.add(toAdd);
}
//Setting all the 3 bits
else {
let toAdd = (1 << i) + (1 << j) + (1 << k);
allNum.add(toAdd);
}
}
}
}
//Adding all the numbers to an array list so that it can be sorted
let validNumbers = Array.from(allNum);
validNumbers.sort((a, b) => a - b); // sort by ascending order
//Answer queries by applying binary search
for (let i = 0; i < queries.length; i++) {
let L = queries[i].L;
let R = queries[i].R;
//Swap L and R if R is smaller than L
if (R < L) {
let temp = L;
L = R;
R = temp;
}
if (L == 0) {
let indxOfLastNum = upperBound(validNumbers, R);
console.log(indxOfLastNum + 1);
} else {
let indxOfFirstNum = upperBound(validNumbers, L);
let indxOfLastNum = upperBound(validNumbers, R);
console.log(indxOfLastNum - indxOfFirstNum + 1);
}
}
}
let Q = 2;
let queries = [];
let q1 = new Query(3, 7);
let q2 = new Query(10, 16);
queries.push(q1);
queries.push(q2);
answerQueries(queries);
Time Complexity : O((Maximum Number of Bits)3 + Q * logN), where Q is the number of queries and N is the size of set containing all valid numbers. l valid numbers.
Similar Reads
Range LCM Queries Given an array arr[] of integers of size N and an array of Q queries, query[], where each query is of type [L, R] denoting the range from index L to index R, the task is to find the LCM of all the numbers of the range for all the queries.Examples: Input: arr[] = {5, 7, 5, 2, 10, 12 ,11, 17, 14, 1, 4
15+ min read
Array Range Queries The array range query problem can be defined as follows: Given an array of numbers, the array range query problem is to build a data structure that can efficiently answer queries of a particular type mentioned in terms of an interval of the indices. The specific query can be of type - maximum elemen
3 min read
CSES Solutions â Static Range Sum Queries Given an array arr[] of N integers, your task is to process Q queries of the form: what is the sum of values in range [a,b]? Examples Input: arr[] = {1, 3, 4, 8, 6, 1, 4, 2}, Queries: {{2, 5}, {1, 3}}Output: 21 8Explanation: Query 1: Sum of elements from index 2 to 5 = 3 + 4 + 8 + 6 = 21Query 2: Sum
5 min read
Sudo Placement[1.5] | Second Smallest in Range Given an array of N integers and Q queries. Every query consists of L and R. The task is to print the second smallest element in range L-R. Print -1 if no second smallest element exists. Examples: Input: a[] = {1, 2, 2, 4} Queries= 2 L = 1, R = 2 L = 0, R = 1Output: -1 2 Approach: Process every quer
6 min read
Sudo Placement 2 | Course Structure Course Home Page Week Aptitude Verbal Ability Logical Reasoning Basic Programming Week 1 Ratio, Proportion, and Progressions Basic Grammar Number Series, Symbol Series Operators, DataTypes, Loops & Control Structure Week 2 Percentages, Profit and Loss Spotting Errors Verbal Classification, Essential
1 min read