Workspace Binary Search
0d
Back to questionsDSA Visualizers: 388 Coding Questions

Binary Search visualizer

Find the target in a sorted array. Return any matching zero-based index, or -1.

EXECUTION LAB

Find the target in a sorted array. Return any matching zero-based index, or -1.

Input and constraints
  • Values must be in nondecreasing order.
  • Use at most 32 integers. Each numeric input is between -1000 and 1000.

Code inspector

def solve(values, target):
left = 0
right = (len(values) - 1)
while (left <= right):
mid = (left + ((right - left) // 2))
if (values[mid] == target):
return mid
if (values[mid] < target):
left = (mid + 1)
else:
right = (mid - 1)
return -1

Visualizer

Step 1 of 6
02left
15
28
312
416mid
523
638
756
872right

Inspect the current state

Inspect midpoint 4 within the remaining bounds.

Variable watch

left 0mid 4right 8target 23

Step explanation

Inspect midpoint 4 within the remaining bounds.

comparisons 1reads 0writes 0swaps 0recursiveCalls 0
Educational simulation · O(log n) time · O(1) space

Worked explanation

A librarian opens the middle of a sorted catalogue and closes an entire half after each comparison.

Guided solution

Check the midpoint of the inclusive range. Sorted order tells you which half cannot contain the target.

O(log n) time · O(1) auxiliary space

Examples

Worked example · {"values":[2,5,8,12,16,23,38,56,72],"target":23} ⇒ 5

Edge case 1 · {"values":[],"target":3} ⇒ -1

Edge case 2 · {"values":[2],"target":3} ⇒ -1

Edge case 3 · {"values":[4],"target":4} ⇒ 0

Progressive hints

Hint 1A librarian opens the middle of a sorted catalogue and closes an entire half after each comparison.
Hint 2Check the midpoint of the inclusive range. Sorted order tells you which half cannot contain the target.
Hint 3Step through the worked example and inspect the highlighted variables before each update.

Common mistake

Updating a boundary to mid instead of moving past it can repeat the same interval forever.

Interview follow-up

How would the boundaries change if you needed the first match?

Continue learning

Practice related DSA questions in the same topic.