Skip to content
Related Articles

Related Articles

Minimize steps to create given Array by adding powers of 2

View Discussion
Improve Article
Save Article
  • Last Updated : 20 Jun, 2022

Given an array A[] having N positive integers, the task is to find the minimum number of steps to build this array from an initial array of size N having all 0s following the below operations:

  • Select any subsequence of the array.
  • Add any power of 2 to each element of the subsequence.

Examples:

Input: A = {5, 5, 5}, N = 3
Output: 2
Explanation: Initially, A = {0, 0, 0}
First, add 4 (22) to all elements of A.
A becomes {4, 4, 4}.
Then, add 1  (20) to all elements of A.
A now becomes {5, 5, 5}
Therefore, two operations were required to equalize A2 and A1.

Input: A1 = [5, 2, 1], N  = 3
Output: 3

 

Approach: The solution to the problem is based on the following mathematical concept:

Each number can be expressed as the sum of exponents of 2, i.e., the binary representation.
To get a number in minimum steps by adding powers of 2 to 0, we need to add only the powers of set bits.
To minimize the step for forming the array, the optimal choice is to select all the elements having set bit in the same position at once and perform the operation in all of them.

Therefore, the problem reduces to finding the total number of unique set bit positions in all the array elements.

Follow the steps mentioned below to implement the idea:

  • As we need the unique set bits among all the array elements, we should perform the bitwise OR of all the elements and count the set bits of that value.
  • Initialize a variable (say X) to store the bitwise OR of all the array elements.
  • Iterate through all the array elements:
    • Perform the bitwise OR operation with X.
  • Calculate the set bits in X.
  • The count of set bits is the required answer.

Below is the implementation of the above approach.

C++




// C++ code for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to calculate the minimum steps
int  minimumOperations(int A[],int n){
     
    // Initially, bitwise Or is
    // equal to first element of the array
    int bitwiseOr = A[0];
     
    // Calculating the bitwise OR
    // with each element in the array
    for(int i=1;i<n;i++)
        bitwiseOr |= A[i];
         
    // Calculating the number of set
    // bits in the bitwise OR
    int ans = __builtin_popcount(bitwiseOr);
     
    // Return the number of set bits
    // as the required answer
    return ans;
}
// Driver Code
int main()
{
    int A[]= {5, 2, 1};
    int N = 3;
     
    //Function Call
    cout<<(minimumOperations(A, N));
}
// This code is contributed by Potta Lokesh

Java




// Java code for the above approach
public class GFG {
     
    // recursive function to count set bits
    public static int countSetBits(int n)
    {
   
        // base case
        if (n == 0)
            return 0;
   
        else
   
            // if last bit set add 1 else add 0
            return (n & 1) + countSetBits(n >> 1);
    }
     
    // Function to calculate the minimum steps
    static int  minimumOperations(int A[],int n){
         
        // Initially, bitwise Or is
        // equal to first element of the array
        int bitwiseOr = A[0];
         
        // Calculating the bitwise OR
        // with each element in the array
        for(int i=1;i<n;i++)
            bitwiseOr |= A[i];
             
        // Calculating the number of set
        // bits in the bitwise OR
        int ans = countSetBits(bitwiseOr);
         
        // Return the number of set bits
        // as the required answer
        return ans;
    }
 
    // Driver Code
    public static void main (String[] args)
    {
        int A[]= {5, 2, 1};
        int N = 3;
         
        //Function Call
        System.out.println(minimumOperations(A, N));
    }
     
}
 
// This code is contributed by AnkThon

Python3




# Python3 code to implement the approach
 
# Function to calculate the minimum steps
def minimumOperations(A, n):
     
    # Initially, bitwise Or is
    # equal to first element of the array
    bitwiseOr = A[0]
     
    # Calculating the bitwise OR
    # with each element in the array
    for i in range(1, n):
        bitwiseOr |= A[i]
         
    # Calculating the number of set
    # bits in the bitwise OR
    ans = bin(bitwiseOr).count("1")
     
    # Return the number of set bits
    # as the required answer
    return ans
 
#Driver Code
if __name__ == '__main__':
    A = [5, 2, 1]
    N = 3
     
    #Function Call
    print(minimumOperations(A, N))

C#




// C# program to implement above approach
using System;
using System.Collections;
using System.Collections.Generic;
 
class GFG
{
 
  // recursive function to count set bits
  static int countSetBits(int n)
  {
 
    // base case
    if (n == 0)
      return 0;
 
    else
 
      // if last bit set add 1 else add 0
      return (n & 1) + countSetBits(n >> 1);
  }
 
  // Function to calculate the minimum steps
  static int minimumOperations(int[] A, int n)
  {
 
    // Initially, bitwise Or is
    // equal to first element of the array
    int bitwiseOr = A[0];
 
    // Calculating the bitwise OR
    // with each element in the array
    for(int i = 1 ; i < n ; i++){
      bitwiseOr |= A[i];
    }
 
    // Calculating the number of set
    // bits in the bitwise OR
    int ans = countSetBits(bitwiseOr);
 
    // Return the number of set bits
    // as the required answer
    return ans;
  }
 
  public static void Main(string[] args){
 
    int[] A = new int[]{5, 2, 1};
    int N = 3;
 
    //Function Call
    Console.WriteLine(minimumOperations(A, N));
 
  }
}
 
// This code is contributed by entertain2022.

Javascript




<script>
 
// JavaScript code for the above approach
     
    // recursive function to count set bits
    function countSetBits(n)
    {
   
        // base case
        if (n == 0)
            return 0;
   
        else
   
            // if last bit set add 1 else add 0
            return (n & 1) + countSetBits(n >> 1);
    }
     
    // Function to calculate the minimum steps
    function minimumOperations(A,n){
         
        // Initially, bitwise Or is
        // equal to first element of the array
        let bitwiseOr = A[0];
         
        // Calculating the bitwise OR
        // with each element in the array
        for(let i=1;i<n;i++)
            bitwiseOr |= A[i];
             
        // Calculating the number of set
        // bits in the bitwise OR
        let ans = countSetBits(bitwiseOr);
         
        // Return the number of set bits
        // as the required answer
        return ans;
    }
 
// Driver Code
 
let A = [5, 2, 1];
let N = 3;
 
//Function Call
document.write(minimumOperations(A, N),"</br>");
 
// This code is contributed by shinjanpatra
 
</script>

Output

3

Time Complexity: O(N)
Auxiliary Space: O(1) 


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!