EasyArrayBinary SearchDivide and Conquer

Binary Search

LeetCode
2 approaches, code in all languages

You are given an array of integers arr that is arranged in strictly increasing order, together with a value target. Report the 0-based index at which target appears. When the value does not occur anywhere in the array, return -1 instead.

Because the input is already sorted, you should not scan every element. Aim for a logarithmic-time solution that repeatedly narrows the region under consideration by comparing the target against the middle element and discarding the half that cannot contain it.

Example 1

Input: arr = [-2, 0, 3, 5, 9, 12], target = 9

Output: 4

The value 9 is stored at index 4, so that index is returned.

Example 2

Input: arr = [-2, 0, 3, 5, 9, 12], target = 2

Output: -1

No element equals 2, so the search reports -1.

Constraints

  • 1 <= arr.length <= 10^4
  • -10^4 <= arr[i], target <= 10^4
  • arr is sorted in strictly increasing order with unique values
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now