EasyArrayBinary Search

Search Insert Position

LeetCode
2 approaches, code in all languages

You are given an array of distinct integers sorted in ascending order along with a target value. If the target already lives in the array, return the index where it sits. If it is absent, return the index it would occupy if it were dropped into the array while keeping everything in order.

The interesting part of this task is the runtime bound: the search has to finish in logarithmic time, so a plain left-to-right scan is off the table for the intended solution and a halving strategy is expected instead.

Example 1

Input: nums = [1,3,5,6], target = 5

Output: 2

The value 5 is already present at index 2.

Example 2

Input: nums = [1,3,5,6], target = 2

Output: 1

2 belongs between 1 and 3, so it would slot in at index 1.

Constraints

  • 1 ≤ nums.length ≤ 10^4
  • -10^4 ≤ nums[i] ≤ 10^4
  • nums is sorted in strictly ascending order with no duplicates
  • -10^4 ≤ target ≤ 10^4
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