Tuesday, July 25th

 Finding the peak in a mountain array is today's problem

An array is designed like a mountain, where values increase from beginning to a peak, when values decline to the end of the array.  We are tasked with finding the peak of the mountain.  The solution must be logarithmic time, because finding the max in an array is a trivial linear time one-liner

Locating a value in logarithmic time beckons binary search

Instead of using binary search to look for a target value, we are looking for a peak.  The peak, which is guaranteed to exist, occurs when a value has both a right and left neighbor with a smaller value.  So we modify binary search to test for the peak condition

Initialize variables to represent the indices of the middle value, left of middle, and right of middle

    int m; // middle
    int mr; // middle right
    int ml; // middle left

Set the index variables to the middle value, left and right.   l and r variables are left and right indices from vanilla binary search

    m=(l+r)/2;
    mr=m+1;
    ml=m-1;

With the middle, middle right, and middle left indices, we test for a peak.  We find the array values at m, ml, and mr, and test if the middle value is greater than the values to the immediate left and right.  If the conditions are met, were return m, the index of the peak;

if( arr[m]>arr[ml] && arr[m]>arr[mr] ) return m; 

The full algorithm is below:

int peakIndexInMountainArray(vector<int>& arr) {
        int l=0;
        int r=arr.size();
        int m; // middle
        int mr; // middle right
        int ml; // middle left
        while (l<r) {
            m=(l+r)/2;
            mr=m+1;
            ml=m-1;
            if( arr[m]>arr[ml] && arr[m]>arr[mr] ) return m;
            else if ( arr[ml]<arr[m]) {
                l=m;
            } else {
                r=m;
            }
        }
        return -1;
    }

The algorithm returns -1 at the end because it was required by the compiler, but since a peak is guaranteed to exist, and the array is of at least length 3 so we don't need to test boundary conditions, the return -1 should never occur, which held up for all test cases

The problem is listed as a medium, but can be solved with binary search by basically modifying one line

Comments

Popular posts from this blog

Wednesday, September 20th

Monday, September 11th

Tuesday, September 19th