AlgoTales · Roadmap

Peak element

Intermediate · 9 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

A peak is a value bigger than its neighbours. You can find one without checking everything by looking at which direction the values are rising and walking that way, because a hilltop must lie ahead.

Practical use cases

  • Web app: Finding the busiest hour. A traffic chart shows requests per hour that rise to a high point and then fall. Instead of reading all 24 or all 8,760 hourly values, the code probes the middle, sees whether traffic is still rising, and moves toward the top. It lands on the busiest point in a few probes.
  • Web app: Tuning a discount level. A shop tests discounts and finds profit rises, peaks, then falls. Instead of trying every percentage, the team compares two nearby values and follows the rising side. They find the best discount in far fewer experiments.
  • System: Signal strength search. A Wi-Fi tool looks for the strongest signal while an antenna is turned. By checking whether the signal improves in one direction, it homes in on the peak without trying every angle. About ten tries replace a hundred.

The story: Climbing the Tallest Hill

Grandpa Bhaskar took Mira on a trek. The path rose and fell: hills of heights 1, 4, 2, 6, 9, 7, 3 hundred metres. "Find me a hilltop," he said, "any point that is higher than the path just before it and just after it."

Mira thought, "The list is not sorted, so binary search is impossible." But then she stood at a middle hill and looked at the next one. If the next hill was higher, she was walking uphill. And a path that keeps going up must either keep climbing to the end (the end counts as a peak) or turn down somewhere, and that turning point is a peak. So a peak is guaranteed to the right.

If the next hill was lower, she was standing on a downhill slope or on top of a peak, so a peak is guaranteed at her spot or to the left. One comparison with a neighbour gave her a direction, and she discarded half the trail. The path was not sorted, yet halving still worked, because we only need some peak, not a particular one.

How to spot this problem, and where you need it

You want a high point in data that goes up and then down, or any local maximum, and reading every value is wasteful or expensive.

Signs you need it

  • The problem says "peak element", "mountain array", "local maximum" or "bitonic".
  • The data rises and then falls, like speed, sales over a campaign, or signal strength, and you need the top.
  • Each measurement costs time or money, such as running an experiment, so you want the fewest tries.

Where to use it in a project

  • Analytics charts where you highlight the peak hour, day or sales point in large series.
  • Tuning parameters like batch size, cache size or discount rate when results go up then down.

The solution

Check the middle item and the one after it. If the next one is bigger, you are on an uphill slope, so a peak exists to the right; search there. If the next one is smaller, you are on a downhill slope or at the top, so a peak exists at or to the left; search there. Halve the range each time until one position remains.

Payoff: Before: reading all 1 million values. After: about 20 probes to land on a peak.

Explain it like I am 8

You are blindfolded on a hilly field and want to reach any hilltop. You feel with your foot: is the ground going up in front of you? Walk forward, you will reach a top. Going down? Then a top is behind you or right here. You never need a sorted field.

How it works, step by step

  1. Set low = 0 and high = n - 1. Imagine "-infinity" walls on both sides.
  2. While low < high, pick mid and compare a[mid] with a[mid + 1].
  3. If a[mid] < a[mid + 1] (uphill): a peak is to the right, low = mid + 1.
  4. Otherwise (downhill): a peak is at mid or to the left, high = mid.
  5. When low meets high, that index is a peak.

The code in four languages

PHP

<?php
// Return the index of ANY peak: an item bigger than its neighbours (neighbours are distinct).
function findPeak(array $a): int {
    $low = 0;
    $high = count($a) - 1;
    while ($low < $high) {
        $mid = intdiv($low + $high, 2);
        if ($a[$mid] < $a[$mid + 1]) {
            $low = $mid + 1;       // uphill: a peak lies to the right
        } else {
            $high = $mid;          // downhill: a peak is here or to the left
        }
    }
    return $low;
}

$hills = [1, 4, 2, 6, 9, 7, 3];
$i = findPeak($hills);
echo "peak at index $i, height " . $hills[$i], "\n";   // peak at index 4, height 9

JavaScript

// Return the index of ANY peak: an item bigger than its neighbours (neighbours are distinct).
function findPeak(a) {
  let low = 0;
  let high = a.length - 1;
  while (low < high) {
    const mid = Math.floor((low + high) / 2);
    if (a[mid] < a[mid + 1]) {
      low = mid + 1;       // uphill: a peak lies to the right
    } else {
      high = mid;          // downhill: a peak is here or to the left
    }
  }
  return low;
}

const hills = [1, 4, 2, 6, 9, 7, 3];
const i = findPeak(hills);
console.log('peak at index ' + i + ', height ' + hills[i]);   // peak at index 4, height 9

Java

public class Main {
    // Return the index of ANY peak: an item bigger than its neighbours (neighbours are distinct).
    static int findPeak(int[] a) {
        int low = 0;
        int high = a.length - 1;
        while (low < high) {
            int mid = low + (high - low) / 2;
            if (a[mid] < a[mid + 1]) {
                low = mid + 1;       // uphill: a peak lies to the right
            } else {
                high = mid;          // downhill: a peak is here or to the left
            }
        }
        return low;
    }

    public static void main(String[] args) {
        int[] hills = {1, 4, 2, 6, 9, 7, 3};
        int i = findPeak(hills);
        System.out.println("peak at index " + i + ", height " + hills[i]);   // peak at index 4, height 9
    }
}

Go

package main

import "fmt"

// findPeak returns the index of ANY peak: an item bigger than its neighbours (neighbours are distinct).
func findPeak(a []int) int {
	low := 0
	high := len(a) - 1
	for low < high {
		mid := low + (high-low)/2
		if a[mid] < a[mid+1] {
			low = mid + 1 // uphill: a peak lies to the right
		} else {
			high = mid // downhill: a peak is here or to the left
		}
	}
	return low
}

func main() {
	hills := []int{1, 4, 2, 6, 9, 7, 3}
	i := findPeak(hills)
	fmt.Printf("peak at index %d, height %d\n", i, hills[i]) // peak at index 4, height 9
}

Time: O(log n) · Extra space: O(1). Every comparison cuts the trail in half, even though the list is not sorted.

Watch out for

  • Assuming the answer is the single highest hill. Any local peak is valid, not only the maximum.
  • Using while (low <= high) with high = mid, which loops forever.
  • Reading a[mid + 1] when mid is the last index. The low < high loop keeps mid + 1 in range.

Quick check

  1. If a[mid] < a[mid+1], where is a peak guaranteed?
    • To the right
    • To the left
    • Nowhere
  2. Does the array need to be sorted?
    • Yes, ascending
    • Yes, descending
    • No
  3. When downhill we set...
    • high = mid
    • low = mid + 1
    • high = mid - 1