Practice
JavaScriptData StructuresReactConcepts
Sign in
← Back to problems

Search Insert Position

Searchingeasy

Given a sorted array `nums` and a `target`, implement `searchInsert(nums, target)` returning the index where target is, or where it would be inserted to keep the array sorted.

Sample tests

Input: searchInsert([1,3,5,6], 5)
Output: 2
Input: searchInsert([1,3,5,6], 2)
Output: 1

+ 1 hidden test run on Submit.

Hints

Common pitfalls
  • Returning mid instead of the converged low for the insert position.

Learning resources

  • Wikipedia: Binary search
Approach & explanation (try first)

A lower-bound binary search finds the index or insertion point in O(log n).

Loading...
⌘/Ctrl + Enter

Run your code to see results.