
Replace all array elements with the nearest power of its previous element
Given a circular array arr[] consisting of N integers, the task is to replace all the array elements with the nearest possible power of its previous adjacent element
Examples:
Input: arr[] = {2, 4, 6, 3, 11}
Output: 1 4 4 6 9
Explanation:
Power of 11 which is nearest to 2 —> 110 = 1
Power of 2 which is nearest to 4 —> 22 = 4
Power of 4 which is nearest to 6 —> 41 = 4
Power of 6 which is nearest to 3 —> 61 = 6
Power of 3 which is nearest to 11—> 32 = 9Input: arr[] = {3, 2, 4, 3}
Output: 3 3 4 4
Explanation:
Power of 3 which is nearest to 3 —> 31 = 3
Power of 3 which is nearest to 2 —> 31 = 3
Power of 2 which is nearest to 4 —> 22 = 4
Power of 4 which is nearest to 3 —> 41 = 4
Approach: The idea to solve this problem is to traverse the array and for each array element arr[i], find the power of the previous element, say X, which is nearest to arr[i], i.e. XK which is closest to arr[i]. Follow the steps:
- Calculate the value of K, which is equal to the floor value of logx(Y).
- Therefore, K and (K + 1) will be the two integers for which the power could be nearest.
- Calculate XK and X(K + 1) and check which is nearer to Y. Then, print that value.
Below is the implementation of the above approach:
Python3
|
[1, 4, 4, 1, 9]
Time Complexity: O(N)
Auxiliary Space: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
0 comments:
Post a Comment