|
| 1 | +# 35 - Search Insert Position |
| 2 | + |
| 3 | +Difficulty: easy |
| 4 | +Done: Yes |
| 5 | +Last edited: February 16, 2022 5:09 PM |
| 6 | +Link: https://leetcode.com/problems/search-insert-position/ |
| 7 | +Topic: array, binary search |
| 8 | + |
| 9 | +## Problem |
| 10 | + |
| 11 | +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. |
| 12 | + |
| 13 | +You must write an algorithm with `O(log n)` runtime complexity. |
| 14 | + |
| 15 | +## Solution |
| 16 | + |
| 17 | +Straight away we can say this will require a **binary search** approach to accomplish a runtime complexity of $O(log*n)$. Three pointer approach to keep track of left, right, and midpoint elements of sorted array. |
| 18 | + |
| 19 | +We want to return index of target, which will be tracked by midpoint value. Only constraint is if target is not in array, then we want to return the index of where it would be inserted |
| 20 | + |
| 21 | +## Whiteboard |
| 22 | + |
| 23 | + |
| 24 | + |
| 25 | +solution if target in array |
| 26 | + |
| 27 | + |
| 28 | + |
| 29 | +target = 7, not in array, return left ptr |
| 30 | + |
| 31 | +## Code |
| 32 | + |
| 33 | +```python |
| 34 | +class Solution: |
| 35 | + def searchInsert(self, nums: List[int], target: int) -> int: |
| 36 | + |
| 37 | + left, right = 0, len(nums)-1 |
| 38 | + |
| 39 | + while left <= right: |
| 40 | + mid = (left+right) // 2 |
| 41 | + if target == nums[mid]: |
| 42 | + return mid |
| 43 | + elif target > nums[mid]: |
| 44 | + # search right |
| 45 | + left = mid + 1 |
| 46 | + elif target < nums[mid]: |
| 47 | + # search left |
| 48 | + right = mid - 1 |
| 49 | + |
| 50 | + return left |
| 51 | +``` |
0 commit comments