Stack Bash - Master data structures and algorithms

Implement binary search

Easy
Given a sorted array of integers and a target value, write a function that returns the index of the target if it exists, or -1 if it does not.
For example, given the following inputs:
nums = [1, 3, 5, 7, 9, 11]
target = 7
Your function should return 3 since the target 7 is at index 3.
Binary search visualization showing left, mid, and right pointers on a sorted array
Binary search works by maintaining two pointers, left and right, that define the search range. On each step, we check the middle element. If it matches the target, we return its index. If the target is smaller, we search the left half. If larger, we search the right half.

Try it first

Solution

6 Essential Sorting & Searching Coding Interview Problems

Master Sorting & Searching by trying the coding challenges below.
  1. 1.Implement binary searchEasy
  2. 2.Merge intervalsMedium
  3. 3.Kth largest in arrayMedium
  4. 4.Intersection of ArraysMedium
  5. 5.Search sorted matrixHard
  6. 6.Search row & col sorted matrixHard