Search⌘ K
AI Features

Solution: Search Insert Position

Explore how to use binary search to find the index of a target in a sorted array or determine where it should be inserted to maintain order. This lesson teaches the step-by-step approach with pointers for an efficient O(log n) solution and constant space usage.

Statement

Given a sorted array of distinct integers, nums, and an integer, target, return the index of target if it exists in the array.
If the target is not present, return the index where it should be inserted to maintain the sorted order.

Your algorithm must run in the O(logn)O(\log n) time.

Constraints:

  • 11 \leq nums.length 103\leq 10^3 ...