Leetcode 35: Search Insert Position

grid47
grid47
Exploring patterns and algorithms
Nov 3, 2024 6 min read

A glowing insertion point in a calm array, gently creating a new position.
Solution to LeetCode 35: Search Insert Position Problem

Given a sorted array of distinct integers and a target value, return the index of the target if it is present. If the target is not in the array, return the index where it should be inserted to maintain the sorted order.
Problem
Approach
Steps
Complexity
Input: A sorted array of distinct integers and a target value.
Example: Input: nums = [1, 2, 4, 5, 7], target = 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
Output: Return the index of the target if found, or the index where it should be inserted to keep the array sorted.
Example: Output: 2
Constraints:
• Return an integer indicating the position of the target or where it should be inserted.
Goal: Find the target's index or the index for insertion using binary search for O(log n) time complexity.
Steps:
• Initialize two pointers, left and right, at the start and end of the array.
• Perform a binary search: calculate mid and compare the value at mid with the target.
• If the target is equal to the value at mid, return mid.
• If the target is greater than the value at mid, move the left pointer to mid + 1.
• If the target is smaller than the value at mid, move the right pointer to mid - 1.
• If the loop ends without finding the target, return the position of left as the index for insertion.
Goal: The array is sorted, and the elements are distinct.
Steps:
• Array length is at most 10^4.
• The array contains distinct integers sorted in ascending order.
Assumptions:
• The input array will always be sorted and contain distinct integers.
• The target value is within the bounds of the given constraints.
Input: Input: nums = [1, 2, 4, 5, 7], target = 4
Explanation: The target is present at index 2, so we return 2.

Input: Input: nums = [1, 2, 4, 5, 7], target = 3
Explanation: The target is not found, but it should be inserted at index 2 to keep the array sorted.

Input: Input: nums = [1, 2, 4, 5, 7], target = 6
Explanation: The target is not found, but it should be inserted at index 4 to keep the array sorted.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus