Sudo Placement | Range Queries
Last Updated :
11 Jul, 2025
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
Basics & Prerequisites
Data Structures
Array Data StructureIn 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
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA 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
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem