Search code examples
arraysalgorithmbinary-search

Peak element in an array


So I was trying to solve the following problem:

Given an array of integers. Find a peak element in it. An array element is peak if it is NOT smaller than its neighbors. For corner elements, we need to consider only one neighbor. For example, for input array {5, 10, 20, 15}, 20 is the only peak element. For input array {10, 20, 15, 2, 23, 90, 67}, there are two peak elements: 20 and 90. Note that we need to return any one peak element.

from the following link: http://www.geeksforgeeks.org/find-a-peak-in-a-given-array/

At one point they say

If the middle element is smaller than the its left neighbor, then there is always a peak in left half.

I get confused at this point, how do we know for sure that there will be a peak element in left half? All i can conclude from this is that there's atleast 1 element for sure that is bigger than its right neighbour (i.e a[m-1]) so there's a chance it could be the peak element) I have researched on stackoverflow and other sites but couldn't find a good explanation for the above stated conclusion

Thank you for your help!


Solution

  • Suppose you're standing on a middle element lower than its left neighbor:

                element
                             you
                           element
    

    You look to your left. It looks like a hill.

    Suppose you climb that hill. What do you see? Well, there are three possibilities:

    1.
      element
                  you
                element
    
                           element
    
    2.
                  you
      element   element
    
                           element
    
    3.
                  you
                element
    
      element              element
    

    In cases 2 and 3, hooray! You've found a peak. In case 1, you keep climbing. Eventually, either you see an element that isn't higher than you, or you hit the left wall. In either case, you've found a peak.