Find Peak Element

Algorithms
Medium
Salesforce
32.9K views

A peak element is an element that is strictly greater than its neighbors. Find a peak element and return its index. Use a modified Binary Search.

Why Interviewers Ask This

Salesforce asks this to evaluate a candidate's ability to optimize time complexity beyond linear scanning. They specifically test if you can apply binary search logic to non-sorted data by recognizing that local gradients guarantee a peak exists, demonstrating strong algorithmic intuition and problem-solving under constraints.

How to Answer This Question

1. Clarify Requirements: Confirm edge cases like single elements or peaks at boundaries where only one neighbor exists. 2. Analyze Constraints: Note the O(log n) requirement implies binary search is mandatory, not linear iteration. 3. Define Logic: Explain the core insight that if nums[mid] < nums[mid+1], a peak must exist in the right half; otherwise, it is in the left half including mid. 4. Draft Code: Implement the modified binary search with low, high, and mid pointers, ensuring strict inequality checks. 5. Trace Example: Walk through an array like [1, 2, 3, 1] to show how the search space halves each step until convergence. 6. Validate Complexity: Explicitly state why this achieves O(log n) time and O(1) space, aligning with Salesforce's focus on scalable solutions.

Key Points to Cover

  • Recognizing that global sorting is unnecessary due to local gradient properties
  • Explicitly stating the O(log n) time complexity constraint early in the discussion
  • Correctly handling boundary conditions without separate if-statements for every edge case
  • Demonstrating the logic of eliminating half the array based on a single comparison
  • Providing a clear trace of the algorithm with a concrete numerical example

Sample Answer

To solve the Peak Element problem efficiently, I first clarify that we need any valid peak index, not necessarily all of them, and handle boundary conditions where the array has one element. Since the interviewer request…

Common Mistakes to Avoid

  • Attempting a linear scan which results in O(n) time complexity and fails the optimization requirement
  • Forgetting to check strictly greater neighbors, leading to incorrect identification of plateaus as peaks
  • Failing to handle the case where the peak is at the very beginning or end of the array
  • Confusing the condition for moving left versus right, causing the binary search to miss the peak

Sound confident on this question in 5 minutes

Answer once and get a 30-second AI critique of your structure, content, and delivery. First attempt is free — no signup needed.

Try it free

Related Interview Questions

Browse all 145 Algorithms questionsBrowse all 49 Salesforce questions