EasyArrayBinary Search

2 approaches, code in every language

Problem description

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

After the pattern

Now solve one you haven't seen.

Threshold Insert Slot is our own problem on the technique behind Search Insert Position: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.

1,194 problems · 15,062 graded tests · free