# 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;
    }
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://timmybeeflin.gitbook.io/cracking-leetcode/binary-search/162.-find-peak-element.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
