VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-the-nearest-power-of-2-for-every-array-element/

⇱ Find the nearest power of 2 for every array element - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find the nearest power of 2 for every array element

Last Updated : 23 Jul, 2025

Given an array arr[] of size N, the task is to print the nearest power of 2 for each array element. 
Note: If there happens to be two nearest powers of 2, consider the larger one.

Examples:

Input: arr[] = {5, 2, 7, 12} 
Output: 4 2 8 16 
Explanation: 
The nearest power of arr[0] ( = 5) is 4. 
The nearest power of arr[1] ( = 2) is 2. 
The nearest power of arr[2] ( = 7) is 8. 
The nearest power of arr[3] ( = 12) are 8 and 16. Print 16, as it is the largest.

Input: arr[] = {31, 13, 64} 
Output: 32 16 64

Approach: Follow the steps below to solve the problem:

  • Traverse the array from left to right.
  • For every array element, find the nearest powers of 2 greater and smaller than it, i.e. calculate pow(2, log2(arr[i])) and pow(2, log2(arr[i]) + 1).
  • Calculate difference of these two values from the current array element and print the nearest as specified in the problem statement.

Below is the implementation of the above approach:


Output: 
4 2 8 16

 


 

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


 

Comment