Similar Problems

Similar Problems not available

Search Insert Position - Leetcode Solution

Companies:

LeetCode:  Search Insert Position Leetcode Solution

Difficulty: Easy

Topics: binary-search array  

The Search Insert Position problem on Leetcode requires to find the index of the target element in a sorted array. If the target element is not present in the array, then find the index where it would be inserted to maintain the sorted order of the array.

Solution:

The simplest approach for solving this problem is to iterate through the sorted array and compare each element to the target element. If the target element is present in the array, return its index. If it is not present in the array, return the index where it would be inserted based on the sorted order of the array.

Let's look at the implementation of this algorithm.

def searchInsert(nums, target):
    for i in range(len(nums)):
        if nums[i] == target:
            return i
        elif nums[i] > target:
            return i
    return len(nums)

In this solution, we iterate through the array using a for loop. At each index, we check if the element is equal to the target element. If it is equal, we return the index. If the element is greater than the target element, this means that the current index is where the target element would be inserted to maintain the sorted order of the array. Thus, we return the current index. If we reach the end of the array and the target element is not found, this means that the target element would be inserted at the end of the array. Thus, we return the length of the array.

Let's test our function with some sample inputs.

nums = [1, 3, 5, 6]
target = 5
print(searchInsert(nums, target)) # Output: 2

nums = [1, 3, 5, 6]
target = 2
print(searchInsert(nums, target)) # Output: 1

nums = [1, 3, 5, 6]
target = 7
print(searchInsert(nums, target)) # Output: 4

nums = [1, 3, 5, 6]
target = 0
print(searchInsert(nums, target)) # Output: 0

In this way, we can solve the Search Insert Position problem on Leetcode using a simple linear search approach.

Search Insert Position Solution Code

1