![]() |
VOOZH | about |
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:
Below is the implementation of the above approach:
4 2 3 4 3 4 5
Time Complexity: O(n)
Auxiliary Space: O(n)