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 atmost three set bits in their binary representation.
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.
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 atmost 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.
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.
- Sudo Placement[1.5] | Second Smallest in Range
- Sudo Placement | Placement Tour
- Queries to check whether a given digit is present in the given Range
- Queries for number of array elements in a range with Kth Bit Set
- Queries for counts of array elements with values in given range
- Sudo Placement[1.4] | K Sum
- Sudo Placement[1.5] | Partition
- Sudo Placement[1.4] | BST Traversal
- Sudo Placement[1.5] | Wolfish
- Sudo Placement[1.4] | Jumping the Subtree
- Sudo Placement | Beautiful Pairs
- Sudo Placement[1.3] | Stack Design
- Sudo Placement | Palindrome Family
- Sudo Placement | Special Subsequences
- Sudo Placement 2 | Matrix Series
This article is contributed by Team GeeksforGeeks. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.