Python Program to Find Peak Element in Array
for i in range(len(arr)): if (i == 0 or arr[i] > arr[i-1]) and (i == len(arr)-1 or arr[i] > arr[i+1]): return arr[i].Examples
How to Think About It
Algorithm
Code
def find_peak(arr): n = len(arr) for i in range(n): if (i == 0 or arr[i] > arr[i-1]) and (i == n-1 or arr[i] > arr[i+1]): return arr[i] return None # Example usage arr = [1, 3, 20, 4, 1, 0] print(find_peak(arr))
Dry Run
Let's trace the array [1, 3, 20, 4, 1, 0] through the code to find the peak element.
Check element at index 0
arr[0] = 1, left neighbor does not exist, right neighbor = 3; 1 > 3? No, so not peak.
Check element at index 1
arr[1] = 3, left neighbor = 1, right neighbor = 20; 3 > 1? Yes, 3 > 20? No, so not peak.
Check element at index 2
arr[2] = 20, left neighbor = 3, right neighbor = 4; 20 > 3? Yes, 20 > 4? Yes, so peak found.
| Index | Element | Left Neighbor | Right Neighbor | Is Peak? |
|---|---|---|---|---|
| 0 | 1 | None | 3 | No |
| 1 | 3 | 1 | 20 | No |
| 2 | 20 | 3 | 4 | Yes |
Why This Works
Step 1: Check neighbors
The code compares each element with its neighbors using arr[i] > arr[i-1] and arr[i] > arr[i+1] to find if it is a peak.
Step 2: Handle edges
For the first and last elements, the code only compares with the one neighbor they have by checking i == 0 or i == n-1.
Step 3: Return peak
Once a peak is found, the function returns it immediately, ensuring the first peak is returned quickly.
Alternative Approaches
def find_peak_binary(arr): low, high = 0, len(arr) - 1 while low < high: mid = (low + high) // 2 if arr[mid] < arr[mid + 1]: low = mid + 1 else: high = mid return arr[low] print(find_peak_binary([1, 3, 20, 4, 1, 0]))
def find_peak_simple(arr): for i in range(len(arr)): left = arr[i-1] if i > 0 else float('-inf') right = arr[i+1] if i < len(arr)-1 else float('-inf') if arr[i] > left and arr[i] > right: return arr[i] return None print(find_peak_simple([1, 3, 20, 4, 1, 0]))
Complexity: O(n) time, O(1) space
Time Complexity
The simple loop checks each element once, so it takes linear time O(n). The binary search alternative takes O(log n) time.
Space Complexity
The solution uses only a few variables and no extra space proportional to input size, so space is O(1).
Which Approach is Fastest?
Binary search is fastest for large arrays but more complex. The simple loop is easier to understand and fine for small to medium arrays.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Simple Loop | O(n) | O(1) | Small to medium arrays, easy to understand |
| Binary Search | O(log n) | O(1) | Large arrays, performance critical |
| Max with Condition | O(n) | O(1) | Readable code with clear edge handling |