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.
Python3
|
Time Complexity: O(N)
Auxiliary Space: O(1)