15% off all plans & roadmaps Use code
See plansLeetCode 35 · Solution & editorial
Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
Search Insert Position is a Binary Search Patterns problem, in the On Sorted Array/List subpattern. The pattern covers standard binary search, rotated arrays, first/last occurrence, and search on answer space
Master standard binary search on sorted arrays. Learn search insert position, sqrt calculation, and 2D matrix search.
The reference solution runs in O(logn) time and O(1) space.
Search Insert Position has been reported in interviews at Apple, Amazon.
The full editorial is part of Pro
It explains the core insight, the complexity analysis and the common mistakes, with a worked solution.
Search Insert Position is a Binary Search Patterns problem, in the On Sorted Array/List subpattern. Once the approach above makes sense, write it yourself and then work through the neighbouring problems that reuse it.