Magicsheet logo

Find the Peaks

Easy
100%
Updated 8/1/2025

Asked by 2 Companies

Find the Peaks

1. What is this problem about?

The Find the Peaks interview question is an introductory array traversal task. You are given an array of integers representing heights (mountain ranges). A "peak" is an element that is strictly greater than its immediate left neighbor and its immediate right neighbor. Your goal is to return a list containing the indices of all such peaks. Note that elements at the very beginning and end of the array cannot be peaks because they lack two neighbors.

2. Why is this asked in interviews?

Companies like Meta ask the Find the Peaks coding problem as a warm-up to verify basic programming skills. It tests your ability to handle array indexing safely, implement conditional logic, and manage boundaries. It evaluations your proficiency in Enumeration and simple linear scans within an Array interview pattern.

3. Algorithmic pattern used

This problem uses a simple Linear Scan (One-pass) pattern.

  • Iteration: Start the loop from index 1 and end at index n2n-2 (inclusive).
  • Comparison: For each index ii, check if mountain[i] > mountain[i-1] AND mountain[i] > mountain[i+1].
  • Collection: If both conditions are true, add index ii to the result list.

4. Example explanation

mountain = [0, 1, 4, 2, 5, 3]

  • Index 0: Boundary, skip.
  • Index 1: 1>01 > 0 (True), 1>41 > 4 (False).
  • Index 2: 4>14 > 1 (True), 4>24 > 2 (True). Peak Found! (Index 2).
  • Index 3: 2>42 > 4 (False).
  • Index 4: 5>25 > 2 (True), 5>35 > 3 (True). Peak Found! (Index 4).
  • Index 5: Boundary, skip. Result: [2, 4].

5. Common mistakes candidates make

  • Boundary Errors: Including index 0 or n1n-1 in the search, which leads to IndexOutOfBoundsException when checking neighbors.
  • Incorrect Comparison: Using >= instead of >, failing to handle the "strictly greater" requirement.
  • Sorting: Trying to sort the array, which destroys the positional information needed to identify peaks.

6. Interview preparation tip

Always check the "neighborhood" constraints in array problems. If a definition depends on i1i-1 and i+1i+1, your loop range should be restricted to [1, n-2]. This is a fundamental safe-coding practice in Array interview patterns.

Similar Questions