35.
Search Insert Position
Easy
Problem Description
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.
Examples
Input: [1,3,5,6], 5
Output: 2
Input: [1,3,5,6], 2
Output: 1
Input: [1,3,5,6], 7
Output: 4
Constraints
1 <= nums.length <= 10^4
-10^4 <= nums[i] <= 10^4
nums contains distinct values sorted in ascending order.
-10^4 <= target <= 10^4
Approach to Solve
Use a two-pointer approach to find the target.
Code Implementation
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
left, right = 0, len(nums) - 1
while left <= right:
mid = (left + right) // 2
if nums[mid] == target:
return mid
elif nums[mid] < target:
left = mid + 1
else:
right = mid - 1
return left
Explanation
This solution uses a two-pointer approach to find the target. Here's a detailed explanation of the algorithm:
- Initialize left and right pointers to the start and end of the array, respectively.
- While left is less than or equal to right:
- Calculate the middle index mid.
- If nums[mid] is equal to the target, return mid.
- If nums[mid] is less than the target, move the left pointer to mid + 1.
- Otherwise, move the right pointer to mid - 1.
- If the target is not found, return left.
Complexity
- Time Complexity: O(log n)
- Space Complexity: O(1)
Code copied to clipboard!