← Home

162. Find Peak Element

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
binary searchC++Markdown
162

A good way into this one is to ask: what do we need to remember so we never redo work blindly? For 162. Find Peak Element, the solution in this repository is mainly a binary search solution.

Guide

What?

The code is easier to read if we treat it as a controlled search through possible states. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: binary search, two pointers, sliding window.

The notes already sitting in the source point us in the right direction:

  • O(N) naive

Guide

When?

Reach for this shape when a direct simulation would work logically but waste time revisiting the same information. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are findPeakElement, search.

Guide

Why?

The code is doing bookkeeping so your brain does not have to keep the entire search space open at once.

  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Read the setup variables first.
  2. Follow the main loop or recursive helper next.
  3. Watch where invalid states get skipped.
  4. Check which value survives to the return statement.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(logN), space: O(1)
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//O(N) naive
02//Runtime: 8 ms, faster than 76.83% of C++ online submissions for Find Peak Element.
03//Memory Usage: 9.1 MB, less than 100.00% of C++ online submissions for Find Peak Element.
04class Solution {
05public:
06    int findPeakElement(vector<int>& nums) {
07        int n = nums.size();
08        // n >= 1
09        // if(n == 1) return 0;
10        // if(n == 2) return (nums[0] > nums[1]) ? 0 : 1;
11        
12        for(int i = 0; i < n; ++i){
13            //to handle the boundary
14            if(nums[i] > max(i == 0 ? LLONG_MIN : nums[i-1], 
15                             i == n-1 ? LLONG_MIN : nums[i+1])) return i;
16        }
17        
18        return -1;
19    }
20};
21
22//cleaner O(N)
23//Approach 1: Linear Scan
24//Runtime: 8 ms, faster than 76.83% of C++ online submissions for Find Peak Element.
25//Memory Usage: 9.1 MB, less than 100.00% of C++ online submissions for Find Peak Element.
26//time: O(N), space: O(1)
27class Solution {
28public:
29    int findPeakElement(vector<int>& nums) {
30        int n = nums.size();
31        
32        for(int i = 0; i+1 < n; ++i){
33            /*
34            when we are at i, nums[i] must > nums[i-1],
35            otherwise it will return at previous step
36            */
37            if(nums[i] > nums[i+1]) return i;
38        }
39        
40        //note this edge case!!
41        return n-1;
42    }
43};
44
45//Approach 3: Iterative Binary Search
46//Runtime: 8 ms, faster than 76.83% of C++ online submissions for Find Peak Element.
47//Memory Usage: 9 MB, less than 100.00% of C++ online submissions for Find Peak Element.
48//time: O(logN), space: O(1)
49class Solution {
50public:
51    int findPeakElement(vector<int>& nums) {
52        int n = nums.size();
53        
54        //use binary search to find local maximum
55        
56        int l = 0, r = n-1;
57        
58        while(l <= r){
59            //stop when the search space contains only one element
60            if(l == r) return l;
61            
62            int mid = l + ((r-l)>>1);
63            
64            // cout << l << ", " << mid << ", " << r << endl;
65            
66            if(nums[mid] > nums[mid+1]){
67                //it's on falling slope
68                //find on the left
69                r = mid;
70            }else{
71                //it's on rising slope
72                //find on the right
73                l = mid+1;
74            }
75        }
76        
77        return -1;
78    }
79};
80
81//official
82//Approach 3: Iterative Binary Search
83//Runtime: 4 ms, faster than 98.84% of C++ online submissions for Find Peak Element.
84//Memory Usage: 9.1 MB, less than 100.00% of C++ online submissions for Find Peak Element.
85class Solution {
86public:
87    int findPeakElement(vector<int>& nums) {
88        int n = nums.size();
89        
90        int l = 0, r = n-1;
91        
92        while(l < r){
93            int mid = l + ((r-l)>>1);
94            
95            // cout << l << ", " << mid << ", " << r << endl;
96            
97            if(nums[mid] > nums[mid+1]){
98                r = mid;
99            }else{
100                l = mid+1;
101            }
102        }
103        
104        //now l is equal to r
105        //return r; //works
106        return l; //works
107    }
108};
109
110//Approach 2: Recursive Binary Search
111//Runtime: 4 ms, faster than 98.84% of C++ online submissions for Find Peak Element.
112//Memory Usage: 9 MB, less than 100.00% of C++ online submissions for Find Peak Element.
113//time: O(logN)
114//space: O(1)
115class Solution {
116public:
117    int search(vector<int>& nums, int l, int r){
118        if(l == r) return l;
119        
120        int mid = l + ((r-l)>>1);
121        
122        if(nums[mid] > nums[mid+1]){
123            return search(nums, l, mid);
124        }
125        
126        return search(nums, mid+1, r);
127    }
128    
129    int findPeakElement(vector<int>& nums) {
130        int n = nums.size();
131        
132        return search(nums, 0, n-1);
133    }
134};

Cost

Complexity

Time
O(logN), space: O(1)
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.