Search⌘ K
AI Features

Solution: Search Insert Position

Understand how to implement a modified binary search algorithm that returns the index of a target element or the correct insertion position in a sorted array. Learn to use two pointers to narrow the search range and maintain O(log n) time and O(1) space complexity, a crucial skill for coding interviews.

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 ...