1. Linear Scan for Peak (Brute Force)
Intuition
By the mountain array definition, the array strictly increases up to the peak index i, and strictly decreases afterwards. A linear scan finds the first index i where arr[i] > arr[i + 1]. This index i is guaranteed to be the peak.
When to apply: Use to verify the mountain array property definition before optimizing to binary search.
Brute force — inspect every value
2 of 2 questions left todayA peak is greater than its immediate neighbors
A peak is greater than its immediate neighbors.
public class Main { public static class Solution { public int peakIndexInMountainArray(int[] arr) { int i = 0; while (arr[i] < arr[i + 1]) { i++; } return i; } } public static void main(String[] args) { Solution sol = new Solution(); int[] arr = {0, 2, 5, 10, 4, 1}; System.out.println("Peak Index: " + sol.peakIndexInMountainArray(arr)); }}Time & Space Complexity
- Time complexity:
O(n)— In the worst case, the peak is near the end, scanning up to n elements. - Space complexity:
O(1)— No additional memory allocated.
Why Brute Force Doesn't Scale:
For N = 105, quadratic O(N2) approaches require ~1010 operations, exceeding the standard 1-second CPU budget.
The optimal approach processes N elements in a single or logarithmic pass, completing in under 10ms with minimal memory footprint.