Open In App

Generate an Array such with elements maximized through swapping bits

Last Updated : 12 May, 2021
Comments
Improve
Suggest changes
2 Likes
Like
Report

Given an array arr[], the task is to generate a modified array such that all its elements are maximized by swapping of bits.
Examples: 
 

Input: arr[] = {10, 15} 
Output: 12, 15 
Explanation: 
Binary representation of (10)10 = (1010)2. Swap the second and third bit to get the binary representation as (1100)2 = (12)10
For 15, its binary representation is 1111, which can not be further changed to get greater value. 
Input: arr[] = {8, 15, 9, 10, 14} 
Output: 8, 15, 12, 12, 14 
 


 


Approach: 
Follow the steps below to solve the problem: 
 

  • Count the number of set and unset bits in every array element.
  • Shift all the set bits to the left(MSB) and all the unset bits to the right(LSB) to maximize the array elements.
  • If count of set bits or unset bits is equal to the number of bits of the array element, then that element cannot be altered( e.g. (7)10 = (111)2
  • Print the maximized elements in the array


Below is the implementation of the above approach:
 

C++
Java Python3 C# JavaScript

Output: 
8, 15, 12, 12, 14

 

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


Similar Reads