Skip to the solution
MediumDSAAsked in 20245 min read

Binary search implementation

903 views

The problem

Problem, as an interviewer would state it: "Implement binary search on a sorted array, returning the index of the target or -1. Discuss edge cases, runtime, and how you would handle duplicates."

Examples:

Code
binarySearch([1, 3, 5, 7, 9, 11], 7); // 3
binarySearch([1, 3, 5, 7], 4);        // -1

Clarifying questions expected:

  • Is the array guaranteed sorted, and in which order and by what comparison?
  • If the target appears several times, which index should be returned — any, the first, or the last?
  • Should I return -1 on a miss, or the insertion point?

Code / implementation expected: Yes — real, direct proof against a brute-force reference, plus the duplicate-handling variants.

  • js-coding
  • utility
  • algorithm

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

5 min read · 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptReal, direct proof: binary search matches a brute-force reference on random arrays, handles duplicates via lowerBound/upperBound, and fails on unsorted input

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 96 of 154 in JavaScript coding

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextMedium

Implement Promise.any() with AggregateError

Continue