Drill

ProblemsJavaScript › patterns

Where the climb turns into a descent

mediumpatternsBinary searchArraysJavaScript

A pressure trace rises to a single peak and then falls away. The analysis wants the position of the peak, and the traces are long.

peakPosition(trace: list<int>) → int

Solve it in the editor →

Where you start

function peakPosition(trace) {
  
}

Worked examples

CallResult
peakPosition([1,3,5,4,2])2
peakPosition([1,2,3])2
peakPosition([9,5,1])0
peakPosition([7])0

Hint

Compare a reading with the one after it. Still climbing means the peak is further right; already falling means it is here or to the left.

Reference solution in JavaScript
function peakPosition(trace) {
  if (trace.length === 0) return -1;
  let lo = 0;
  let hi = trace.length - 1;
  while (lo < hi) {
    const mid = Math.floor((lo + hi) / 2);
    if (trace[mid] < trace[mid + 1]) lo = mid + 1;
    else hi = mid;
  }
  return lo;
}

The same problem in another language

More patterns problems in JavaScript