EasyBinary SearchFree practice
Binary Search
Asked atgoogleamazonmicrosoftapplebloomberg
01 · Problem
Given a sorted array of integers nums in ascending order and an integer target, write a function to search target in nums. If target exists, return its index. Otherwise, return -1.
You must write an algorithm with O(log n) runtime complexity.
02 · Examples
Example 01
Input
nums = [-1,0,3,5,9,12], target = 9
Output
4
9 exists in nums and its index is 4.
Example 02
Input
nums = [-1,0,3,5,9,12], target = 2
Output
-1
2 does not exist in nums so return -1.
Example 03
Input
nums = [5], target = 5
Output
0
5 exists in nums and its index is 0.
03 · Constraints
- 011 <= nums.length <= 104
- 02-104 < nums[i], target < 104
- 03All the integers in nums are unique.
- 04nums is sorted in ascending order.
04 · Optimal complexity
- Time
- O(log n)
- Space
- O(1)
05 · Two ways to work on it
Practice it alone or rehearse it as an interview.
Practice Mode gives you an editor and test runs, nothing else. AI Interview Mode puts a voice interviewer on the other side, adds a clock, and ends with a scored summary of the round.