logoNEURAL COOK
SearchAll PostsTagsNotesAuthor
instagramtwitterfacebookyoutubelinkedinmailgithubrss
Copyright © 2026 All rights reserved.
•
VIKI
Built with Vikramaditya Singh
Built with
VIKI - A posts created with Next.js and Tailwind.css
About
leetcode
Title
Table Of Contents
easy
13. Roman to Integer
14. Longest Common Prefix
20. Valid Parentheses
26. Remove Duplicates from Sorted Array
35. Search Insert Position
69. Sqrt(x)
70. Climbing Stairs
88. Merge Sorted Array (In-Place)
104. Maximum Depth of Binary Tree
118. Pascal's Triangle
121. Best Time to Buy and Sell Stock
205. Isomorphic Strings
242. Valid Anagram
283. Move Zeroes
345. Reverse Vowels of a String
605. Can Place Flowers
704. Binary Search
796. Rotate String
1071. Greatest Common Divisor of Strings
1299. Replace Elements with Greatest Element on Right Side
1431. Kids With the Greatest Number of Candies
1614. Maximum Nesting Depth of the Parentheses
1752. Check if Array Is Sorted and Rotated
1768. Merge Strings Alternately
1903. Largest Odd Number in String
2965. Find Missing and Repeated Values
hard
25. Reverse Nodes in k-Group
26. Remove Duplicates from Sorted Array
27. Remove Element
42. Trapping Rain Water
51. N-Queens
55. Jump Game
80. Remove Duplicates from Sorted Array II
88. Merge Sorted Array
121. Best Time to Buy and Sell Stock
122. Best Time to Buy and Sell Stock II
189. Rotate Array
274. H-Index
medium
2. Add Two Numbers
3. Longest Substring Without Repeating Characters
5. Longest Palindromic Substring
8. String to Integer (atoi)
11. Container With Most Water
15. 3Sum
17. Letter Combinations of a Phone Number
19. Remove Nth Node From End of List
22. Generate Parentheses
33. Search in Rotated Sorted Array
34. Find First and Last Position of Element in Sorted Array
48. Rotate Image
49. Group Anagrams
50. Pow(x, n)
53. Maximum Subarray
54. Spiral Matrix
56. Merge Intervals
61. Rotate List
73. Set Matrix Zeroes
74. Search a 2D Matrix
75. Sort Colors
78. Subsets
137. Single Number II
138. Copy List with Random Pointer
150. Evaluate Reverse Polish Notation
151. Reverse Words in a String
153. Find Minimum in Rotated Sorted Array
155. Min Stack
162. Find Peak Element
169. Majority Element
198. House Robber
207. Course Schedule
215. Kth Largest Element in an Array
227. Basic Calculator II
236. Lowest Common Ancestor of a Binary Tree
237. Delete Node in a Linked List
238. Product of Array Except Self
451. Sort Characters By Frequency
540. Single Element in a Sorted Array
560. Subarray Sum Equals K
636. Exclusive Time of Functions
875. Koko Eating Bananas
1011. Capacity To Ship Packages Within D Days
1101. The Earliest Moment When Everyone Become Friends
1283. Find the Smallest Divisor Given a Threshold
2140. Solving Questions With Brainpower
3169. Count Days Without Meetings
3481. Apply Substitutions
rotate-array-approach-1
189. Rotate Array (Approach 2 )
189. Rotate Array (Approach 1 )
number-of-islands-approach-1
200. Number of Islands (Approach 2)
200. Number of Islands (Approach 1)
meeting-rooms-ii-approach-1
253. Approach Using Priority Queue
253. Meeting Rooms II
misc
Calculate Floor & Ceiling
Find Nth Root Of M
Flatten A Linked List
Implement Lower Bound
Implement Upper Bound
Number of occurrence
take-u-forward
Recently Solved
arrays
The Ultimate Array Pattern Playbook
faqs-hard
Count Inversions in an Array
Find The Repeating And Missing Number
Majority Element II
Maximum Product Subarray
Merge Sorted Array (In-Place)
Reverse Pairs
faqs-medium
3. 3Sum
4. 4Sum
Maximum Subarray
Leaders in an Array
Majority Element
Next Permutation
Get specific element from Pascal's Triangle
Pascal's Triangle II (Row Generation)
Generate Pascal's Triangle (Full)
Spiral Matrix Traversal
Rearrange Array Elements by Sign
Rotate Image
Sort Colors (Dutch National Flag)
Two Sum
fundamentals
Check if Array is Sorted
Largest Element in an Array
Array Rotation (Left and Right)
Left Rotate Array by One
Linear Search
Max Consecutive Ones
Second Largest Element in an Array
Single Number
logic-building
Missing Number
Intersection of Two Sorted Arrays (with Duplicates)
Move Zeros to End
Remove Duplicates from Sorted Array
Union of Two Sorted Arrays
binary-search
About
d-arrays
Find Row With Maximum 1'S
Search In A 2D Matrix
faqs
Aggressive Cows
Allocate Books
Find Peak Element
Kth Element Of 2 Sorted Arrays
Minimise Max Distance to Gas Stations
Split Array - Largest Sum
fundamentals
Lower Bound
Binary Search
Upper Bound
logic-building
Count Occurrences in a Sorted Array
Find Minimum in Rotated Sorted Array
Find out how many times the array is rotated
Find First and Last Position of Element in Sorted Array
Floor and Ceil in Sorted Array
Kth Missing Positive Number
Search in Rotated Sorted Array
Search in Rotated Sorted Array II (With Duplicates)
Search Insert Position
Single Element in a Sorted Array
on-answers
Capacity To Ship Packages Within D Days
Find Nth Root of M
Find Square Root of a Number
Smallest Divisor Given a Threshold
Koko Eating Bananas (Minimum Rate)
Minimum Days to Make M Bouquets
Painter's Partition Problem
Split Array Largest Sum
hashing
Theory
faqs
Subarray Sum Equals K
Count Subarrays with Given XOR K
Largest Subarray with 0 Sum
Longest Consecutive Sequence
Longest Subarray with Sum K
recursion
faqs-medium
Combination Sum II (Unique Combinations)
Combination Sum (Unbounded)
Subset Sums
hard
Letter Combinations of a Phone Number
implementation-problems
Generate Parentheses
Power Function: pow(x, n)
Subsets (The Power Set)
subsequence-pattern-problems
Subsequence Sum Existence
Count All Subsequences With Sum K
sorting
Bubble Sort
Insertion Sort
Merge Sort
Quick Sort
Selection Sort
string
Isomorphic Strings
Largest Odd Number in String
Longest Common Prefix
Reverse Words in a String
Code Scratch›take u forward›binary search›faqs

Find Peak Element

# Question

A peak element is an element strictly greater than its neighbors. Given a 0-indexed integer array nums, find a peak element and return its index. You may imagine that nums[−1]=nums[n]=−∞nums[-1] = nums[n] = -\inftynums[−1]=nums[n]=−∞. You must write an algorithm that runs in O(log⁡n)O(\log n)O(logn) time.

# Solution

# Pattern

Binary Search on Gradient (Slope) Even though the array is unsorted, we can use Binary Search by evaluating the local derivative (slope) at any point. Because the array is bounded by −∞-\infty−∞ on both sides, any rising slope guarantees a peak to the right, and any falling slope guarantees a peak to the left.

# How to Identify

  • The required time complexity is O(log⁡N)O(\log N)O(logN), but the array is explicitly not sorted.
  • You are looking for a local maximum/minimum (Peak/Valley).
  • The array has virtual ±∞\pm \infty±∞ boundaries.

# Description

Step-by-step explanation:

  1. Initialize left = 0 and right = nums.length - 1.
  2. Loop while left &lt; right. Using strictly < is critical. It guarantees that the search window has at least 2 elements, meaning mid will never equal the last index, ensuring mid + 1 is always perfectly safe to access without IndexOutOfBounds exceptions.
  3. Calculate mid = left + (right - left) / 2.
  4. Compare nums[mid] with nums[mid + 1] to determine the local slope.
    • If nums[mid] < nums[mid + 1]: The slope is rising. Because the array eventually drops to −∞-\infty−∞ at the far right edge, a rising slope means a peak must mathematically exist somewhere to the right. We discard the left half: left = mid + 1.
    • If nums[mid] &gt; nums[mid + 1]: The slope is falling. Because the array dropped from −∞-\infty−∞ on the far left edge, a falling slope right now means we just passed a peak. The peak must mathematically exist somewhere to the left, or mid itself is the peak. We discard the right half: right = mid. (Do not use mid - 1, as mid is still a candidate).
  5. When the loop terminates, left and right will converge exactly on a peak index. Return left.

# The Intuition

Imagine you are blindfolded and dropped onto a mountain range. You take one step to your right.

  • If your foot steps UP, you know that if you keep walking right, you will eventually hit a peak (because the world ends in a bottomless cliff −∞-\infty−∞).
  • If your foot steps DOWN, you know you are walking away from a peak. The peak must be behind you (to your left), or you were just standing exactly on it. Because you only need to find any peak, you just follow the upward slope. By repeatedly dropping yourself in the middle of the remaining mountain range and checking the slope, you cut the search space in half every time.

# Complexity

LabelWorstAverage
Time ComplexityO(log⁡N)O(\log N)O(logN)O(log⁡N)O(\log N)O(logN)
Space ComplexityO(1)O(1)O(1)O(1)O(1)O(1)

# Time Complexity

The search space is halved in every iteration of the while loop based on a constant-time comparison. For an array of size NNN, this takes at most log⁡2(N)\log_2(N)log2​(N) iterations.

# Space Complexity

The algorithm uses only primitive pointers (left, right, mid), operating entirely in place. Auxiliary space is strictly O(1)O(1)O(1).

# Code

class Solution {
    public int findPeakElement(int[] nums) {
        if (nums == null || nums.length == 0) return -1;
        
        int left = 0;
        int right = nums.length - 1;
 
        // left &lt; right ensures we always have at least 2 elements in the window.
        // Therefore, mid + 1 will never go out of bounds.
        while (left < right) {
            int mid = left + (right - left) / 2;
 
            if (nums[mid] < nums[mid + 1]) {
                // We are on an upward slope. A peak must be to the right.
                left = mid + 1;
            } else {
                // We are on a downward slope. A peak must be at mid or to the left.
                right = mid;
            }
        }
 
        return left;
    }
}

# Caveats

  • left <= right Template Trap: If you try to use while (left <= right) and right = mid - 1, you will be forced to check mid - 1 and mid + 1 simultaneously to identify the exact peak inside the loop. This requires extremely messy boundary padding (like checking for index 0, index N−1N-1N−1, or using Long.MIN_VALUE). The left < right convergence template completely bypasses this headache.
  • Multiple Peaks: The algorithm is greedy. It just follows the first upward slope it finds. If there are multiple peaks (e.g., [1, 5, 2, 7, 3]), it will zero in on one of them deterministically based on how the array halves, ignoring the others. This satisfies the problem constraints.
  • Adjacent Duplicates: This specific O(log⁡n)O(\log n)O(logn) logic assumes arr[i]≠arr[i+1]arr[i] \neq arr[i+1]arr[i]=arr[i+1]. If duplicates are allowed and a peak is defined as arr[i−1]≤arr[i]≥arr[i+1]arr[i-1] \le arr[i] \ge arr[i+1]arr[i−1]≤arr[i]≥arr[i+1], the problem may require O(n)O(n)O(n) in the worst case.
  • Strict Peak: The definition arr[i-1] < arr[i] &gt; arr[i+1] means a plateau (e.g., [1, 2, 2, 2, 1]) technically has no peak under strict rules.

# Concepts to Think About

  • Unsorted Binary Search: This problem is the canonical proof that Binary Search does not require a sorted array. It only requires a property that allows you to definitively discard half the search space.
  • Gradient Descent: This logic is the 1-dimensional discrete equivalent of Gradient Ascent/Descent, a foundational algorithm in Machine Learning for finding local minima/maxima in error functions.
  • Why it works on unsorted data: We don't need the whole array to be sorted; we only need a "gradient" to guide the binary search.
  • Binary Search on Answer: This is a subset of a broader pattern where we search for a value/index that satisfies a specific condition in a search space.
  • Local vs. Global Optima: This algorithm finds a local maximum, not necessarily the global maximum.

# Logical Follow-up

Question: What if the array is a 2D matrix (a grid of mountains), and a peak is strictly greater than its top, bottom, left, and right neighbors? Find any peak in O(Mlog⁡N)O(M \log N)O(MlogN) time. (LeetCode 1901: Find a Peak Element II) Solution: You binary search on the columns (or rows). Pick the middle column mid. Linearly scan this single column to find its maximum element. Let's say the max is at (row, mid). Now, compare matrix[row][mid] to its left and right neighbors matrix[row][mid-1] and matrix[row][mid+1]. If the right neighbor is larger, a 2D peak must exist in the right half of the matrix. If the left is larger, it must be in the left half. Discard the other half of the columns. Because we do an O(M)O(M)O(M) scan at each of the log⁡N\log NlogN binary search steps, the total time is O(Mlog⁡N)O(M \log N)O(MlogN).

Question: What if there are multiple peaks and you need to find the highest one?

Solution: Binary Search will no longer work. You must perform a linear scan O(n)O(n)O(n) because a local peak found by binary search could be much lower than the global maximum.

PreviousAllocate BooksNextKth Element Of 2 Sorted Arrays
CONTENTS
QuestionSolutionPatternHow to IdentifyDescriptionThe IntuitionComplexityCodeCaveatsConcepts to Think AboutLogical Follow-up