# 162. Find Peak Element

## Intitution

A *peak* is an element that is greater than its immediate neighbors. Because we can assume `nums[-1]` and `nums[n]` are `-∞`, the array is guaranteed to have at least one peak.

To find a peak in **O(log n)** time, we can use **binary search**:

* If `nums[mid]` is greater than both neighbors → it's a peak.
* If the right neighbor is greater → the peak lies to the right.
* Else → the peak lies to the left.

This works because in a unimodal-like structure, there's always a path toward a peak.

## Complexity

| Space Complexity | Time Complexity       |
| ---------------- | --------------------- |
| $$\text{O}(1)$$  | $$\text{O}(\log{N})$$ |

## Code

```java
public int findPeakElement(int[] nums) {
    int left = 0, right = nums.length - 1;

    while (left <= right) {
        int mid = (left + right) >> 1;

        // Check if nums[mid] is greater than its left and right neighbors
        boolean isGreaterThanLeft = (mid - 1 < 0 || nums[mid] > nums[mid - 1]);
        boolean isGreaterThanRight = (mid + 1 >= nums.length || nums[mid] > nums[mid + 1]);

        // If both conditions hold, we found a peak
        if (isGreaterThanLeft && isGreaterThanRight) {
            return mid;
        }

        // If increasing toward the right, move right
        if (!isGreaterThanRight) {
            left = mid + 1;
        } else { // Else move left
            right = mid - 1;
        }
    }

    // Should never reach here if input is valid
    return -1;
}

```


---

# 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://private-26.gitbook.io/notes/coding/medium/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.
