Asked at

Search Insert Position

Easy
Verified
ArrayBinary Search~15 min

Given a sorted array of distinct integers nums (ascending) and an integer target, return the index where target is found. If absent, return the index where it would be inserted to keep the array sorted.

Run in O(log n) time. The input arrives as a single object { nums, target }.

Examples

in{ nums: [1, 3, 5, 6], target: 5 }
out2

5 sits at index 2.

in{ nums: [1, 3, 5, 6], target: 2 }
out1

2 would go between 1 and 3, at index 1.

Constraints

  • 1 ≤ nums.length ≤ 10⁴
  • nums is sorted in ascending order.
  • All integers in nums are unique.
  • Target: O(log n) time.

Get help

🔑

Sign in to solve

Sign in to write, run, and submit your solution — and to pick up where your iOS flow left off.