'Leetcode #35 Search Insert Position (list index out of range)

    test=[]     
    for i in range(len(nums)):
        
        if nums[i+1] > target > nums[i]:
            test.append(nums[i])
            test.append(target)
        else:
            test.append(nums[i])
    
    return test.index(target)

I try to create new array sort the value first, then find the index of the target. It get error in index out of range in line nums[i+1]. How can I correct the code without the big change

Question link: https://leetcode.com/problems/search-insert-position/



Solution 1:[1]

What you are doing wrong:

This is because you are using nums[i+1] and since i is in the range 0 to len(nums) it gives index out of range for the last value of i.

You are checking if an element in nums is greater than the previous element or not. This will always be true because nums is sorted. I also don't know why are you appending the nums[i+1] and target to the test list. There's no need to create a new list.

What the question asks you to do

It tells you that the nums is sorted and you need to return the index if target is in nums. If not then return the index where it should be inserted. NOTE: It doesn't ask you to insert the target.

So, the steps which you can follow are:

  1. Loop through nums. You can use for i, num in enumerate(len(nums)):. This will give you the index i.e. i and the value of each element in nums i.e. num.
  2. Take each element to check if the target is greater than or equal to nums[i].
  3. If it is then you need to return that index because that would be the index where the target needs to be inserted. Eg: [1,3,6,8] if target is 5 then it should be inserted at 2 which is the index of nums[i] > target.
  4. If target is greater than the last element of nums then return the last index of nums i.e. len(nums).

Combining all steps. The code we get(Do try it yourself first! Spoiler Alert!):

def searchInsert(self, nums: List[int], target: int) -> int:
for i, num in enumerate(nums): if num >= target: return i
return len(nums)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1