
Problem Statement
In this task, we are given a non-empty array where each element has a unique value which implies there are no consecutive repetitive elements. The goal is to identify a peak element, which is defined as an element that is greater than both its neighbors. A peak can exist anywhere within the interior of the array or at its edges considering the boundary values outside the array can be thought of as negative infinity (-∞
). This means an element at the beginning or the end can be a peak if it is greater than its single neighbor within the array boundaries.
For efficiency, the solution needs to implement an algorithm with a time complexity of O(log n)
. This stipulation points towards the potential use of binary search or a similar divide-and-conquer strategy, given that a linear scan would take O(n)
time.
Examples
Example 1
Input:
nums = [1,2,3,1]
Output:
2
Explanation:
3 is a peak element and your function should return the index number 2.
Example 2
Input:
nums = [1,2,1,3,5,6,4]
Output:
5
Explanation:
Your function can return either index number 1 where the peak element is 2, or index number 5 where the peak element is 6.
Constraints
1 <= nums.length <= 1000
-231 <= nums[i] <= 231 - 1
nums[i] != nums[i + 1]
for all validi
.
Approach and Intuition
Given the constraints and requirements of the problem, a binary search approach is fitting. Here's a straightforward way to achieve our goal using binary search:
- Initialize two pointers,
left
andright
, to the start and end of the array, respectively. - Continuously narrow down the search space:
- Compute the middle point
mid
usingleft
andright
. - If
mid
is a boundary of the array or ifnums[mid]
is greater than bothnums[mid - 1]
andnums[mid + 1]
, thenmid
is the peak and we can return it. - Otherwise, determine which side to continue the search on by comparing
nums[mid]
with its neighbors:- If
nums[mid]
is less thannums[mid + 1]
, the peak must be to the right; adjustleft
tomid + 1
. - If
nums[mid]
is less thannums[mid - 1]
, the peak must be to the left; adjustright
tomid - 1
.
- If
- Compute the middle point
- Continue the above steps until the peak is located. The binary search ensures only half of the remaining array is searched in each iteration, leading to the required
O(log n)
complexity.
This method leverages the properties of binary search efficiently by reducing the problem space exponentially. Note that the assumption of no consecutive equal nums[i]
is crucial since it guarantees that every movement in the search definitively moves towards a peak, avoiding any ambiguous cases.
Solutions
- C++
- Java
- C
- JavaScript
- Python
class Solution {
public:
int peakIndexInArray(vector<int>& arr) {
int start = 0, end = arr.size() - 1;
while (start < end) {
int middle = (start + end) / 2;
if (arr[middle] > arr[middle + 1])
end = middle;
else
start = middle + 1;
}
return start;
}
};
The provided C++ code is designed to find a peak element's index in a given array. This is achieved with a binary search strategy to efficiently locate a local peak, where an element is greater than its neighbors.
Understanding the Algorithm:
- Initialize
start
to the beginning of the array andend
to the last index. - Use a while loop to continue searching while
start
is less thanend
. - Compute the middle index using
(start + end) / 2
. - If the element at the middle index is greater than the subsequent element (
arr[middle] > arr[middle + 1]
), setend
tomiddle
. This action narrows the potential peak to the left section. - If not, update
start
tomiddle + 1
to focus on the right section. - Eventually,
start
will equalend
, pointing to the peak element.
- Initialize
Return Value:
- The function returns the index of the peak element once identified.
The optimal complexity of this method is O(log n), due to the binary search approach, making it highly efficient for large arrays. This solution assumes the array has a peak, which by problem definition, always exists.
public class Solution {
public int locatePeak(int[] elements) {
int left = 0, right = elements.length - 1;
while (left < right) {
int middle = (left + right) / 2;
if (elements[middle] > elements[middle + 1]) right = middle;
else left = middle + 1;
}
return left;
}
}
This solution provides a method to locate a peak element in an array of integers, defined as an element that is greater than its neighbors. Implement this functionality using a Java method named locatePeak
.
- Input to the method is a single array of integers named
elements
. - The solution employs a binary search approach to efficiently find the peak.
- Initialize two pointers:
left
starts at 0 andright
at the last index of the array. - Continue the search as long as
left
is less thanright
:- Calculate the middle index.
- Compare the middle element with its next element:
- If the middle element is greater, narrow the search to the left of
middle
by settingright
tomiddle
. - Otherwise, focus on the elements right of
middle
by settingleft
tomiddle + 1
.
- If the middle element is greater, narrow the search to the left of
- The peak element's location is determined once
left
equalsright
, indicated by theleft
pointer.
This method is efficient, running in O(log n) due to its binary search nature, and it does not require any modifications to the original array. The return value directly provides the index of a peak element.
int peakIndex(int* elements, int size) {
int left = 0, right = size - 1;
while (left < right) {
int midpoint = (left + right) / 2;
if (elements[midpoint] > elements[midpoint + 1])
right = midpoint;
else
left = midpoint + 1;
}
return left;
}
The given C program defines a function named peakIndex
that finds the peak element in an array. A peak element is defined as an element that is greater than its neighbors or is at the boundary of the array. The function accepts two parameters: a pointer to an array of integers (elements
) and the size of that array (size
).
Here's how the function operates:
- Initialize two variables,
left
andright
, to represent the boundaries of the current section of the array being considered.left
starts at 0 andright
starts atsize - 1
. - Use a while loop to continue searching as long as
left
is less thanright
. - Calculate the midpoint of the current section by averaging
left
andright
. - Compare the element at the midpoint with the element immediately following it.
- If the midpoint element is greater than the next element, adjust the
right
boundary tomidpoint
to focus on the left subarray. - Otherwise, adjust the
left
boundary tomidpoint + 1
to focus on the right subarray.
- If the midpoint element is greater than the next element, adjust the
- Once the while loop completes,
left
will be pointing to the index of the peak element.
The function returns the index of the peak element in the array. The binary search approach ensures that the solution is efficient, with a time complexity of O(log n), where n is the size of the input array. This method leverages the properties of binary search by halving the search space with each iteration, making it significantly faster than a linear search approach.
var locatePeak = function (arr) {
let left = 0,
right = arr.length - 1;
while (left < right) {
let midpoint = Math.floor((left + right) / 2);
if (arr[midpoint] > arr[midpoint + 1]) right = midpoint;
else left = midpoint + 1;
}
return left;
};
The provided JavaScript function locatePeak
efficiently identifies a peak element within an array using a binary search approach. The peak element is defined as an element that is greater than its adjacent elements. Here's a breakdown of how the function accomplishes this:
- Define two pointers,
left
andright
, that represent the bounds of the current search area within the array. - Use a while loop to continue the search as long as
left
is less thanright
. - Calculate the
midpoint
of the current range. - If the element at the
midpoint
is greater than the next element (arr[midpoint + 1]
), adjust theright
pointer tomidpoint
, narrowing the search to the left side. - If not, move the
left
pointer tomidpoint + 1
to focus on the right side of the array. - The search terminates when
left
equalsright
, at which pointleft
(orright
, since they are equal) will be the index of a peak element.
This method leverages the binary search mechanism to efficiently locate a peak in logarithmic time complexity, making it suitable for large arrays. This function returns the index of the found peak which can then be used for further processing or verification.
class Solution:
def peakElementSearch(self, array: List[int]) -> int:
left = 0
right = len(array) - 1
while left < right:
center = (left + right) // 2
if array[center] > array[center + 1]:
right = center
else:
left = center + 1
return left
This summary details the implementation of the peakElementSearch
function in Python, designed to find a peak element in an array. A peak element is defined as an element that is greater than its neighbors.
The function takes a list of integers as input and returns the index of a peak element. It utilizes a binary search approach to optimize the process, making it more efficient than a linear search.
- Initialize
left
to zero andright
to the length of the array minus one. - Enter a loop that continues until
left
is equal toright
. This ensures that the search space is reduced efficiently. - Calculate the
center
index as the average ofleft
andright
indexes. - Compare the element at the
center
index with the element next to it:- If the
center
element is greater than the next element, adjust theright
boundary tocenter
. - Otherwise, move the
left
boundary tocenter + 1
.
- If the
- Return
left
as the index of the peak element once the loop exits.
This method efficiently finds a peak element in O(log n) time complexity due to the halving of the search interval with each iteration of the loop.
No comments yet.