FrontendInterviews.dev

Loading problem…

78. Binary Search - Efficient Search

Easy•
Acceptance: 100.00%
•
🔓3/3 Pro unlocks today

You're building a search feature that needs to find an element in a sorted array efficiently. Binary search is the optimal algorithm for sorted arrays.

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, return its index. Otherwise, return -1.

Requirements

1. Basic Functionality

  • Search for target in sorted array
  • Return index if found, -1 if not found
  • Array is sorted in ascending order
  • O(log n) time complexity

Example Usage

binarySearch([-1,0,3,5,9,12], 9); // 4
binarySearch([-1,0,3,5,9,12], 2); // -1

Real-World Context

This problem models real search scenarios:

  • Search functionality: Find items in sorted lists
  • Database queries: Efficient lookup in sorted data
  • Autocomplete: Search in sorted suggestions
  • Performance: O(log n) vs O(n) linear search

Constraints

  • 1 <= nums.length <= 10^4
  • -10^4 < nums[i], target < 10^4
  • All integers in nums are unique
  • nums is sorted in ascending order