59. Binary Search

59. Binary Search

Easy
58.0%
3.4k
arraybinary-search
Google, Amazon, Netflix, Meta (Facebook), Apple, Microsoft, Uber, Bloomberg, Airbnb, Stripe, Adobe, Salesforce, LinkedIn, Oracle

A large-scale platform stores massive sorted datasets such as:

  • user IDs
  • product prices
  • log timestamps

To ensure fast lookups, the system relies on an efficient searching technique instead of scanning every element.

The data is always sorted in ascending order, and the system needs to quickly determine whether a specific value exists and where it is located.

A naive linear scan would take O(n) time, which is too slow for large datasets. Instead, the system uses Binary Search, which repeatedly divides the search space in half.

This is one of the most fundamental and commonly asked problems in coding interviews across Google, Amazon, Microsoft, Meta, and other top companies.

Your Task

Given a sorted array of integers nums and an integer target:

  • Return the index of target if it exists
  • Otherwise, return -1

Input Format

  • nums: sorted integer array (ascending order)
  • target: integer value to search

Output Format

  • Integer index of target, or -1 if not found

Examples

Example 1:

Input: nums = [-1,0,3,5,9,12], target = 9
Output: 4
Explanation: nums[4] = 9

Example 2:

Input: nums = [-1,0,3,5,9,12], target = 2
Output: -1
Explanation: 2 does not exist in array

Example 3:

Input: nums = [5], target = 5
Output: 0

Constraints

  • 1 ≤ nums.length ≤ 100,000
  • -10^9 ≤ nums[i], target ≤ 10^9
  • All elements in nums are unique

Loading editor...

[-1,0,3,5,9,12], target = 9
4

Console Output

Click "Run Code" or "Submit" to see results

Your code will be evaluated by AI with instant feedback