Data Structures & Algorithms Binary Search
💡
Exercise 48

Binary Search 15 XP Easy

LeetCode Ctrl+Enter Run Ctrl+S Save

Now implement the classic binary search yourself from scratch. Given a sorted array and a target, return the index or -1.

Remember the three steps inside the loop:

  • Compute mid = (left + right) // 2
  • If nums[mid] == target, return mid
  • If nums[mid] < target, search right: left = mid + 1
  • If nums[mid] > target, search left: right = mid - 1

Time: O(log n) — for 1 million elements, at most ~20 comparisons!

📋 Instructions
Implement `search(nums, target)` that returns the index of target or -1. Test with: - `search([-1,0,3,5,9,12], 9)` → 4 - `search([-1,0,3,5,9,12], 2)` → -1 Print both results.
Standard binary search. Make sure the while condition is left <= right (inclusive).
🧪 Test Cases
Input
search([-1,0,3,5,9,12], 9)
Expected
4
Test case 1
Input
search([-1,0,3,5,9,12], 2)
Expected
-1
Boundary value
main.py
Hi! I'm Rex 👋
Output
Ready. Press ▶ Run or Ctrl+Enter.