You are given an array Arr[1 .. n] with the special property that Arr[1] ≥ Arr[2] and Arr[n − 1] ≤ Arr[n]. We say that an element Arr[x] is a local minimum if it is less than or equal to both its neighbors. Derive an algorithm in O(log n)
For example in the array 9,6,2,14,5,7,4 – 2 is a local minima as it is smaller than its left and right number 6 and 14. Similarly 5 is another local minima as it is between 14 and 7, both larger than 5. You need to find any one of the local minima.
Solution:
If the array elements are not guaranteed to be distinct, then it’s not possible to do this in O(log n) time. The reason for this is the following: suppose that you have an array where all n > 1 values are the same. In this case, none of the elements can be local minima, because no element is less than its neighbors. However, in order to determine that all values are the same, you will have to look at all the array elements, which takes O(n) time. If you use less than O(n) time, you can’t necessarily look at all the array elements.
If, on the other hand, the array elements are guaranteed to be distinct and with the given properties, you can solve this in O(log n) time using the following observations:
- If there is just one array element, it’s a local minimum.
- If there are two array elements, check each. One must be a local minimum.
- Otherwise, look at the middle element of the array. If it’s a local minimum, return it. Otherwise, at least one adjacent value must be smaller than this one. Recurs in the half of the array containing that smaller element (but not the middle).
int findLocalMinima( int [] arr, int start, int end) |
int mid = (start + end) / 2; |
if (mid - 2 < 0 && mid + 1 >= arr.length) |
if (arr[mid - 2] > arr[mid - 1] && arr[mid - 1] < arr[mid]) |
if (arr[mid - 1] > arr[mid - 2]) |
return findLocalMinima(arr, start, mid); |
return findLocalMinima(arr, mid, end); |
Complexity O(log N)
The 1D case is solved by binary search:
If a[1] < a[2], a[1] is an LM.
Otherwise, if a[n-1] > a[n], a[n] is an LM.
Otherwise, the array entries start out descending (going from a[1] to a[2]) and ends up ascending (going from a[n-1] to a[n]). It follows that an LM must exist somewhere in between. Examine a[n/2]. If a[n/2] > a[n/2+1], then by the same reasoning there is an LM in the upper half of the array. Similarly, if a[n/2] < a[n/2+1] there is an LM in the lower half of the array. Solve recursively in the appropriate half.