Question Bank

Binary Search Fundamentals

Difficulty: Easy

Lower bound, upper bound, and the off-by-one corners of classic binary search. Code stems are Python.

Question Bank
/

Binary Search Fundamentals

Binary Search Fundamentals

Lower bound, upper bound, and the off-by-one corners of classic binary search. Code stems are Python.

Question Bank
Easy
Python
4 questions
binary-search
binary-search-templates
algorithms
quiz

1,202 views

29

Implement classic binary search over a sorted array. Return the index of target, or -1 if not present.

Examples

Example 1:

Input: nums = [1, 3, 5, 7, 9], target = 5
Output: 2
Explanation: Closed [lo, hi] template. mid = 2, nums[2] = 5, match, return 2. O(log n) because each step halves the active window.

Example 2:

Input: nums = [1, 3, 5, 7, 9], target = 6
Output: -1
Explanation: The pointers converge without ever finding 6, so the function returns -1.