> For the complete documentation index, see [llms.txt](https://timmybeeflin.gitbook.io/cracking-leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://timmybeeflin.gitbook.io/cracking-leetcode/binary-search/162.-find-peak-element.md).

# 162. Find Peak Element

![](/files/-Mg65xxgFpWDyftTQ2JT)

idea - compare with neighbor

time: O(logn)

space: O(1)

```java
class Solution {
    public int findPeakElement(int[] nums) {
        // 1 2 1 3 1
        // nums[i] != nums[i + 1] for all valid i.
        // why comare your neighbor is the ans?
        
        int left = 0;
        int right = nums.length - 1;
        while (left < right) {
            int mid = left + (right - left)/2;
            if (nums[mid] < nums[mid+1]) {
                left = mid + 1;
            } else {
                right = mid;
            }
        }
        return left;
    }
}
```

## kotlin

```kotlin
class Solution {
    fun findPeakElement(nums: IntArray): Int {
        var left = 0;
        var right = nums.size - 1;
        while (left < right) {
            var mid = left + (right - left)/2;
            if (nums[mid] < nums[mid+1]) {
                left = mid + 1;
            } else {
                right = mid;
            }
        }
        return left;
    }
}
```
