# Sudo Placement | Range Queries

• Difficulty Level : Hard
• Last Updated : 09 Mar, 2022

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 ` `using` `namespace` `std;` `#define LL long long int` `// This function prints the required answer for each query``void` `answerQueries(LL Q, vector > query)``{``    ``// Set of Numbers having at most 3 set bits``    ``// arranged in non-descending order``    ``set 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 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 > query(Q);``    ``query.first = 3;``    ``query.second = 7;``    ``query.first = 10;``    ``query.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 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 queries){``        ``// Set of Numbers having at most 3 set bits``        ``// arranged in non-descending order``        ``Set 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 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 = ``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);``    ``}` `}`

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.

My Personal Notes arrow_drop_up