Coders Crushby Napplied AI
Back to DSA Problems
EasyLeetCode #704Binary Search

Binary Search

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.

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
Coders Crushby Napplied AI

The ultimate interview preparation platform. Master System Design, DSA, and tackle community challenges to crush your FAANG interviews.

System Design

  • All Problems
  • Easy
  • Hard

DSA

  • All Problems
  • Dynamic Programming
  • Graphs

More

  • Problems Arena
  • Growth Paths
  • AI Discovery

Coders Crush by Napplied AI - Built for engineers preparing for FAANG/MAANG interviews

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

Approach

Classic binary search: repeatedly divide search space in half by comparing middle element with target.

def search(nums, target):
    left, right = 0, len(nums) - 1
    while left <= right:
        mid = (left + right) // 2
        if nums[mid] == target:
            return mid
        elif nums[mid] < target:
            left = mid + 1
        else:
            right = mid - 1
    return -1
Complexity
Time:O(log n)
Space:O(1)
Hints
  • 1.Array is sorted, use binary search
  • 2.Compare middle element with target
  • 3.Adjust left or right pointer accordingly
Asked at
GoogleAmazonMetaMicrosoft