Tuesday, 26 Oct 2021

# Modify array by replacing elements with the nearest power of its previous or next element

Modify array by replacing elements with the nearest power of its previous or next elementGiven a circular array arr[] consisting of N positive integers, the task is to modify the array by replacing each array element with the nearest power of its previous or next array element.Examples:Input: arr[] = {2, 3, 4, 1, 2}Output: {2, 4, 3, 1, 2}Explanation:For arr(= 2): The previous and the next array elements are 2 and 3 respectively. Therefore, nearest power is 21.For arr(= 3): The previous and the next elements are 2 and 4 respectively. Therefore, the nearest power is 41.For arr(= 4): The previous and the next elements are 3 and 1 respectively. Therefore, the nearest power is 31.For arr(= 1): The previous and the next elements are 4, and 2. Therefore, the nearest power is 40.For arr(= 2): The previous and the next elements are 1, and 2. Therefore, the nearest power of 1 is 21.Input: arr[] = {21, 3, 54, 78, 9}Output: {27, 1, 78, 81, 1}Approach: The idea is to traverse the array and replace each array element with the nearest power of its previous element or next array element.Follow the steps below to solve this problem:Traverse the array arr[] and perform the following steps:Find the value of K for which XK will be closest to Y.For calculating K, take the floor value of logx(Y).Therefore, K and K + 1 will be the two integers for which the nearest power is the closest.Calculate YK and Y(K + 1) and check which is closest to X and update the array element arr[i] with the closest value.After completing the above steps, print the array arr[] as the modified array.Below is the implementation of the above approach:Python3  import math  def nearestPow(x, y):            if y == 1:        return 1              k = int(math.log(x, y))      if abs(y**k – x) < abs(y**(k + 1) - x):        return y**k      return y**(k + 1)  def replacebyNearestPower(arr):                prev = arr[-1]    lastNext = arr              for i in range(len(arr)):          temp = arr[i]        if i == len(arr)-1:            next = lastNext        else:            next = arr[(i + 1) % len(arr)]                          prevPow = nearestPow(arr[i], prev)        nextPow = nearestPow(arr[i], next)                  if abs(arr[i]-prevPow) < abs(arr[i]-nextPow):            arr[i] = prevPow        else:            arr[i] = nextPow        prev = temp          print(arr)    arr = [2, 3, 4, 1, 2]  replacebyNearestPower(arr)Output: [2, 4, 3, 1, 2] Time Complexity: O(N)Auxiliary Space: O(1)