Skip to interview prep
Apexed

31. Search Insert Position

EasySearching

Given a sorted array of distinct integers and a target, return the index of target if it is present; otherwise return the index where it would be inserted to keep the array sorted.

Example 1

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

Example 2

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

Constraints

  • 0 ≤ nums.length ≤ 10⁴

Tab indents · Ctrl/⌘ + Enter runs · Esc then Tab leaves the editor

Run checks these cases; the expected output comes from the reference solution. Submit judges all 5 hidden and sample tests.

Code runs only in your browser in an isolated sandbox. Progress and submissions are saved on this device.

Search Insert Position — coding interview practice — Apexed