Drill

ProblemsTypeScript › warmup

Find a value in a sorted list

mediumwarmupTypeScript

A lookup runs against a sorted index, so scanning from the front would be wasteful when halving the range each time works.

findSorted(values: list<int>, target: int) → int

Solve it in the editor →

Where you start

function findSorted(values: number[], target: number): number {
  
}

Worked examples

CallResult
findSorted([1,3,5,7], 5)2
findSorted([1,3,5,7], 1)0
findSorted([1,3,5,7], 7)3
findSorted([1,3,5,7], 4)-1

Hint

Two bounds that close in on each other. Watch that the loop condition includes the case where they meet.

Reference solution in TypeScript
function findSorted(values: number[], target: number): number {
  let lo = 0;
  let hi = values.length - 1;
  while (lo <= hi) {
    const mid = Math.floor((lo + hi) / 2);
    if (values[mid] === target) return mid;
    if (values[mid] < target) lo = mid + 1;
    else hi = mid - 1;
  }
  return -1;
}

The same problem in another language

More warmup problems in TypeScript