Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
[ad_1]
Given an array A[] having N non-negative integers, find a pair of indices i and j such that the absolute difference between them is same as the sum of differences of those with any other array element i.e., | A[i] − A[k] | + | A[k]− A[j] | = | A[i] − A[j] |, where k can be any index.
Examples:
Input: N = 3, A[] = {2, 7, 5}
Output: 0 1
Explanation:
For k = 0:
|A[0] – A[0]| + |A[0] – A[1]|
= |2 − 2| + |2 – 7| = 0 + 5 = 5
= |A[0] – A[1]|
For k = 1:
|A[0] – A[1]| + |A[1] – A[1]|
= |2 − 7| + |7 – 7| = 5 + 0 = 5
= |A[0] – A[1]|
For k = 2:
|A[0] – A[2]| + |A[2] – A[1]|
= |2 − 5| + |5 – 7| = 3 + 2 = 5
= |A[0] – A[1]|Input: N = 4, arr[] = {5, 9, 1, 3}
Output: 1 2
Explanation:
For k = 0:
|A[1] – A[0]| + |A[0] – A[2]|
= |9 − 5| + |5 – 1| = 4 + 4 = 8
= |A[1] – A[2]|
For k = 1:
|A[1] – A[1]| + |A[1] – A[2]|
= |9 − 9| + |9 – 1| = 0 + 8 = 8
= |A[1] – A[2]|
For k = 2:
|A[1] – A[2]| + |A[2] – A[2]|
= |9 − 1| + |1 – 1| = 8 + 0 = 8
= |A[1] – A[2]|
For k = 3:
|A[1] – A[3]| + |A[3] – A[2]|
= |9 − 3| + |3 – 1| = 6 + 2 = 8
= |A[1] – A[2]|
Approach: The problem can be solved with the below mathematical observation:
Depending on the realtion between A[i], A[j] and A[k], the inequality can be writtten in the following 4 ways:
When A[i] ≥ A[k] ≥ A[j]:
A[i] − A[k] + A[k]− A[j] = A[i] − A[j]
=> A[i] – A[j] = A[i] − A[j]When A[k] ≥ A[i], A[k] ≥ A[j]:
A[k] − A[i] + A[k]− A[j] = |A[i] − A[j]|
=> 2*A[k] – A[i] – A[j] = |A[i] − A[j]|When A[i] ≥ A[k], A[j] ≥ A[k]:
A[i] − A[k] – A[k]+ A[j] = |A[i] − A[j]|
=> A[i] + A[j] – 2*A[k] = |A[i] − A[j]|When A[j] ≥ A[k] ≥ A[i]:
– A[i] + A[k] – A[k] + A[j] = – A[i] + A[j]
=> A[j] – A[i] = A[j] − A[i].From the above equations, it is clear that if value of A[i] and A[j] are not the extreme values of the array then the probability of the equation being satisfied depends on the value of A[k] and will not hold true when A[k] lies outside the range of [A[i], A[j]].
Based on the above observation it is clear that the value of A[i] and A[j] should be the maximum and the minimum among the array elements. Follow the below steps to solve the problem:
Below is the implementation of the above approach.
|
Time Complexity: O(N)
Auxiliary Space: O(1)
[ad_2]