Binary Search - Problem

Given an array of integers nums which is sorted in ascending order, and an integer target, write a function to search target in nums.

If target exists, then return its index. Otherwise, return -1.

You must write an algorithm with O(log n) runtime complexity.

Input & Output

Example 1 — Target Found
$ Input: nums = [-1,0,3,5,9,12], target = 9
Output: 4
💡 Note: 9 exists in nums and its index is 4
Example 2 — Target Not Found
$ Input: nums = [-1,0,3,5,9,12], target = 2
Output: -1
💡 Note: 2 does not exist in nums so return -1
Example 3 — Single Element
$ Input: nums = [5], target = 5
Output: 0
💡 Note: Target found at index 0 in single-element array

Constraints

  • 1 ≤ nums.length ≤ 104
  • -104 < nums[i], target < 104
  • All the integers in nums are unique
  • nums is sorted in ascending order

Visualization

Tap to expand
Binary Search Algorithm INPUT Sorted Array (nums): -1 0 0 1 3 2 5 3 9 4 12 5 (indices shown below) Target Value: 9 Array Length: 6 Initial left: 0 Initial right: 5 Time: O(log n) Space: O(1) ALGORITHM STEPS 1 Initialize Pointers left=0, right=5 mid = (0+5)/2 = 2 2 Compare nums[2]=3 3 < 9, search right half left = mid+1 = 3 3 New mid = (3+5)/2 = 4 Compare nums[4]=9 9 == 9, Found! 4 Return Index Return mid = 4 Search Narrowing: mid FOUND FINAL RESULT Target 9 found at index: 4 Position in array: -1 0 3 5 9 12 index 4 Output: return 4 OK - Found Key Insight: Binary Search achieves O(log n) by eliminating half of the remaining elements with each comparison. If nums[mid] < target, search right half (left = mid + 1). If nums[mid] > target, search left half (right = mid - 1). For n=6 elements, we need at most log2(6) = 3 comparisons. Here we found target in just 2 iterations! TutorialsPoint - Binary Search | Optimal Solution - O(log n) Time Complexity
Asked in
Google 45 Amazon 38 Facebook 32 Microsoft 28
312.7K Views
Very High Frequency
~15 min Avg. Time
8.9K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen