1. Linear Scan (Brute Force)
Intuition
Iterate through the array and return the first element that is strictly greater than its successor.
Algorithm
- 1. Loop i from 0 to N-2: - If nums[i] > nums[i+1], return i.
- 2. If no such index found, return N-1 (the last element is the peak).
Brute Force Linear Scan Gradient Peak Search
2 of 2 questions left todayPhase 1 — Not a peak Advance i to 1: Step 1: nums[0] < nums[1]
Phase 1 — Not a peak Advance i to 1: Step 1: nums[0] < nums[1]. Moving uphill, so index 0 is not a peak. Advance i.
#include <iostream>#include <vector>using namespace std; // Brute Force Approach: Linear Scanint findPeakElement(const vector<int>& nums) { int n = nums.size(); for (int i = 0; i < n - 1; i++) { if (nums[i] > nums[i + 1]) { return i; } } return n - 1;} int main() { vector<int> nums = {1, 2, 3, 1}; int peakIndex = findPeakElement(nums); cout << "Output: " << peakIndex << " (Value: " << nums[peakIndex] << ")" << endl; return 0;}Time & Space Complexity
- Time complexity:
O(N)— Single scan visits at most N elements. - Space complexity:
O(1)— No extra data structures used.
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.