Binary Search

Search in sorted array of integers and return index if target is found.

Easy

Examples

Example 1: nums = [-1,0,3,5,9,12], target = 9 → 4

Implementation

Ruby
  # 1. Binary Search: Search in Sorted Array
  # Problem Statement:
  # Given a sorted array of integers and a target value, return the index if the target is found.
  # Otherwise, return -1.
  # Input: nums = [-1,0,3,5,9,12], target = 9
  # Output: 4
  # Time Complexity: O(log n)
  def self.binary_search(nums, target)
    left, right = 0, nums.size - 1

    while left <= right
      mid = left + (right - left) / 2
      puts "Debug: left=#{left}, right=#{right}, mid=#{mid}, nums[mid]=#{nums[mid]}"
      if nums[mid] == target
        return mid
      elsif nums[mid] < target
        left = mid + 1
      else
        right = mid - 1
      end
    end

    -1

Complexity Analysis

Time Complexity:
O(log n)?
Why O(log n)?
We halve the search space each iteration
Each comparison eliminates half of the remaining elements. We can eliminate at most log₂(n) halves.
Example: Array of 1000 elements needs max 10 comparisons (2¹⁰ = 1024)
Space Complexity:
O(1)?
Why O(1)?
Only using a few variables
We only store left, right, and mid pointers - constant space regardless of input size.
Example: Same memory usage for array of 10 or 10,000 elements

Patterns & Techniques

Problem Details

Category: Binary Search And Sorting
Difficulty: Easy
Module: BinarySearchAndSorting
Method: self.binary_search
← Back to Binary Search And Sorting