VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-minimum-value-of-arrj-absj-i-for-all-indices/

⇱ Find minimum value of arr[j] + abs(j - i) for all indices - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find minimum value of arr[j] + abs(j - i) for all indices

Last Updated : 28 May, 2024

Given an array arr[] of size N, the task is for each index i (1≤i≤n) find it's minimum value, that can be calculated by the formula (arr[j] + abs(j−i)), for 0<=j<n and j != i.

Examples:

Input: arr = { 1, 3, 11, 2, 15, 7, 5 }
Output: 4 2 3 4 3 4 5
Explanation:

  • For i = 0, the minimum value is for j = 1, arr[1] + abs(1 - 0) = 3 + 1 = 4
  • For i = 1, the minimum value is for j = 0, arr[0] + abs(0 - 1) = 1 + 1 = 2
  • For i = 2, the minimum value is for j = 3, arr[3] + abs(3 - 2) = 2 + 1 = 3
  • For i = 3, the minimum value is for j = 1, arr[1] + abs(1 - 3) = 2 + 2 = 4
  • For i = 4, the minimum value is for j = 3, arr[3] + abs(3 - 4) = 2 + 1 = 3
  • For i = 5, the minimum value is for j = 3, arr[3] + abs(3 - 5) = 2 + 2 = 4
  • For i = 6, the minimum value is for j = 3, arr[3] + abs(3 - 6) = 2 + 3 = 5.

Input: arr = { 1, 1}
Output: 2 2

Approach: To solve the problem, follow the below idea:

Let assume if jth element is on right of ith element then the equation would be (aj + j) - i, if the jth element is on left of ith element then the equation would be (aj - j) + i. So, to compute the minimum value of these two cases, we need to precompute the value in following way:

  • for case j > i: we need to keep track of all the element which are on the right side in such a way that we can get minimum value of (aj + j) in O(1) time. So, we can use prefix sum technique to keep track of minimum value at each index.
  • for case i > j: we need to keep track of all the element which are on the left side in such a way that we can get minimum value of (aj - j) in O(1) time. So, we can use prefix sum technique to keep track of minimum value at each index.

Finally, we would minimize the result of both cases and add into our result for each value of i.

Step-by-step algorithm:

  • Initialize two vectors addSet and diffSet to store the minimum differences for each element based on the two possible rotations.
  • Calculate the minimum differences for the addSet vector by traversing the array from the end.
  • Calculate the minimum differences for the diffSet vector by traversing the array from the beginning.
  • Create a result vector and add the minimum difference for the first element.
  • Calculate the minimum difference for the remaining elements by taking the minimum of the difference between the current element and the previous element, and the difference between the next element and the current element.
  • Add the minimum difference for the last element to the result vector.

Below is the implementation of the above approach:


Output
4 2 3 4 3 4 5 

Time Complexity: O(n)
Auxiliary Space: O(n)

Comment
Article Tags: