Monday, January 15, 2018

Leetcode solution 162 Find Peak Element

Problem Statement 

A peak element is an element that is greater than its neighbors. Given an input array where num[i] ≠ num[i+1], find a peak element and return its index. The array may contain multiple peaks, in that case return the index to any one of the peaks is fine. You may imagine that num[-1] = num[n] = -∞. For example, in array [1, 2, 3, 1], 3 is a peak element and your function should return the index number 2.

Problem link

You can find the detailed video tutorial here:

A few edge cases to think about

  • Null array, one element array 
  • Strictly increasing array 
  • Strictly decreasing array 
  • Array with all same element (won't happen in this case)

Here is an example:


Code Sample

A few follow up
  • Use first and last element as negative infinite (Solution: just skip the first and last then)
  • There could be same elements and they can be equal. (Solution: same thing, just need to change your comparison logic in this case)

References

  • https://www.youtube.com/watch?v=NFvAD5na5oU
  • https://www.tangjikai.com/algorithms/leetcode-162-find-peak-element
  • https://leetcode.com/problems/find-peak-element/solution/