Count of elements which are power of 2 in a given range subarray for Q queries

Given an array arr[] consisting of N positive numbers and Q queries of the form [L, R], the task is to find the number of elements which are a power of two in a subarray [L, R] for each query.Â
Examples:Â
Input: arr[] = { 3, 8, 5, 2, 5, 10 }, Q = {{0, 4}, {3, 5}}Â
Output:Â
2Â
1Â
Explanation:Â
For Query 1, the subarray [3, 8, 5, 2, 5] has 2 elements which are a power of two, 8 and 2.Â
For Query 2, the subarray {2, 5, 10} has 1 element which are a power of two, 2.
Input: arr[] = { 1, 2, 3, 4, 5, 6 }, Q = {{0, 4}, {1, 5}}Â
Output:Â
3Â
2Â Â
Naive Approach: To solve the problem mentioned above the naive approach is that for all the Q queries, we can iterate through each L and R in the array and find the number of elements which are a power of two in a subarray [L, R].Â
Time Complexity: O(N * Q)
Efficient Approach:Â
To optimize the above method the idea here is to use a prefix sum array. Â
- Initially, the prefix sum array contains 0 for all indices.
- Iterate through the given array and set the prefix array for this index to 1 if the current array element is a power of two else leave it 0.
- Now, obtain the prefix sum by adding the previous index prefix array value to compute the current index’s prefix sum. the prefix[i] will store the number of elements which are a power of two from 1 to i.
- Once we have prefix array, We just need to return prefix[r] – prefix[l-1] for each query.
Below is the implementation of the above approach,Â
C++
// C++ implementation to find// elements that are a power of twoÂ
#include <bits/stdc++.h>using namespace std;const int MAX = 10000;Â
// prefix[i] is going to store the// number of elements which are a// power of two till i (including i).int prefix[MAX + 1];Â
bool isPowerOfTwo(int x){Â Â Â Â if (x && (!(x & (x - 1))))Â Â Â Â Â Â Â Â return true;Â Â Â Â return false;}Â
// Function to find the maximum range// whose sum is divisible by M.void computePrefix(int n, int a[]){Â
    // Calculate the prefix sum    if (isPowerOfTwo(a[0]))        prefix[0] = 1;    for (int i = 1; i < n; i++) {        prefix[i] = prefix[i - 1];Â
        if (isPowerOfTwo(a[i]))            prefix[i]++;    }}Â
// Function to return the number of elements// which are a power of two in a subarrayint query(int L, int R){Â Â Â Â return prefix[R] - prefix[L - 1];}Â
// Driver codeint main(){Â Â Â Â int A[] = { 3, 8, 5, 2, 5, 10 };Â Â Â Â int N = sizeof(A) / sizeof(A[0]);Â Â Â Â int Q = 2;Â
    computePrefix(N, A);    cout << query(0, 4) << "\n";    cout << query(3, 5) << "\n";Â
    return 0;} |
Java
// Java implementation to find// elements that are a power of twoimport java.util.*;class GFG{Â Â Â Â Â static final int MAX = 10000;Â
// prefix[i] is going to store the// number of elements which are a// power of two till i (including i).static int[] prefix = new int[MAX + 1];Â
static boolean isPowerOfTwo(int x){Â Â Â Â if (x != 0 && ((x & (x - 1)) == 0))Â Â Â Â Â Â Â Â return true;Â Â Â Â return false;}Â
// Function to find the maximum range// whose sum is divisible by M.static void computePrefix(int n, int a[]){Â
    // Calculate the prefix sum    if (isPowerOfTwo(a[0]))        prefix[0] = 1;    for (int i = 1; i < n; i++)     {        prefix[i] = prefix[i - 1];Â
        if (isPowerOfTwo(a[i]))            prefix[i]++;    }}Â
// Function to return the number of elements// which are a power of two in a subarraystatic int query(int L, int R){Â Â Â Â if (L == 0)Â Â Â Â Â Â Â Â return prefix[R];Â
    return prefix[R] - prefix[L - 1];}Â
// Driver codepublic static void main(String[] args){Â Â Â Â int A[] = { 3, 8, 5, 2, 5, 10 };Â Â Â Â int N = A.length;Â Â Â Â int Q = 2;Â
    computePrefix(N, A);    System.out.println(query(0, 4));    System.out.println(query(3, 5));}}Â
// This code is contributed by offbeat |
Python3
# Python3 implementation to find# elements that are a power of twoMAX = 10000Â
# prefix[i] is going to store the# number of elements which are a# power of two till i (including i).prefix = [0] * (MAX + 1)Â
def isPowerOfTwo(x):         if (x and (not (x & (x - 1)))):        return True    return FalseÂ
# Function to find the maximum range# whose sum is divisible by M.def computePrefix(n, a):Â
    # Calculate the prefix sum    if (isPowerOfTwo(a[0])):        prefix[0] = 1             for i in range(1, n):        prefix[i] = prefix[i - 1]Â
        if (isPowerOfTwo(a[i])):            prefix[i] += 1Â
# Function to return the number of elements# which are a power of two in a subarraydef query(L, R):Â Â Â Â Â Â Â Â Â return prefix[R] - prefix[L - 1]Â
# Driver codeif __name__ == "__main__":Â Â Â Â Â Â Â Â Â A = [ 3, 8, 5, 2, 5, 10 ]Â Â Â Â N = len(A)Â Â Â Â Q = 2Â
    computePrefix(N, A)    print(query(0, 4))    print(query(3, 5))Â
# This code is contributed by chitranayal |
C#
// C# implementation to find// elements that are a power of twousing System;class GFG{Â Â Â Â Â static int MAX = 10000;Â
// prefix[i] is going to store the// number of elements which are a// power of two till i (including i).static int[] prefix = new int[MAX + 1];Â
static bool isPowerOfTwo(int x){Â Â Â Â if (x != 0 && ((x & (x - 1)) == 0))Â Â Â Â Â Â Â Â return true;Â Â Â Â return false;}Â
// Function to find the maximum range// whose sum is divisible by M.static void computePrefix(int n, int []a){Â
    // Calculate the prefix sum    if (isPowerOfTwo(a[0]))        prefix[0] = 1;    for (int i = 1; i < n; i++)     {        prefix[i] = prefix[i - 1];Â
        if (isPowerOfTwo(a[i]))            prefix[i]++;    }}Â
// Function to return the number of elements// which are a power of two in a subarraystatic int query(int L, int R){Â Â Â Â if (L == 0)Â Â Â Â Â Â Â Â return prefix[R];Â
    return prefix[R] - prefix[L - 1];}Â
// Driver codepublic static void Main(){Â Â Â Â int []A = { 3, 8, 5, 2, 5, 10 };Â Â Â Â int N = A.Length;Â
    computePrefix(N, A);    Console.WriteLine(query(0, 4));    Console.WriteLine(query(3, 5));}}Â
// This code is contributed by Code_Mech |
Javascript
<script>Â
// Javascript implementation to find// elements that are a power of twoÂ
let MAX = 10000;   // prefix[i] is going to store the// number of elements which are a// power of two till i (including i).let prefix = Array.from({length: MAX + 1}, (_, i) => 0);    function isPowerOfTwo(x){    if (x != 0 && ((x & (x - 1)) == 0))        return true;    return false;}   // Function to find the maximum range// whose sum is divisible by M.function computePrefix(n, a){       // Calculate the prefix sum    if (isPowerOfTwo(a[0]))        prefix[0] = 1;    for (let i = 1; i < n; i++)     {        prefix[i] = prefix[i - 1];           if (isPowerOfTwo(a[i]))            prefix[i]++;    }}   // Function to return the number of elements// which are a power of two in a subarrayfunction query(L, R){    if (L == 0)        return prefix[R];       return prefix[R] - prefix[L - 1];}Â
// Driver Code         let A = [ 3, 8, 5, 2, 5, 10 ];    let N = A.length;       computePrefix(N, A);    document.write(query(0, 4) + "<br/>");    document.write(query(3, 5));     </script> |
2 1
Â
Time Complexity: O(max(Q, N))
Â
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



