Search insert position

Asked atInfoEdge India Ltd
1Give yourself 5 minutes
2Answer out loud, not in your head
3Then compare with the answer below

The problem

Given a sorted array of nums consisting 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.

Input: nums = [1, 3, 5, 6], target = 5 Output: 2 Explanation: The target value 5 is found at index 2 in the sorted array. Hence, the function returns 2.

Input: nums = [1, 3, 5, 6], target = 2 Output: 1 Explanation: The target value 2 is not found in the array. However, it should be inserted at index 1 to maintain the sorted order of the array.

Input: nums = [1, 3, 5, 6], target = 7

  • 1 <= nums.length <= 105
  • -105 <= nums[i] <= 105
  • nums contains distinct values sorted in ascending order.
  • -105<= target <= 105

cpp

class Solution {
public:
    int searchInsert(vector<int> &nums, int target)  {
       
    }
};

java

class Solution {
    public int searchInsert(int[] nums, int target) {
      
    }
}

python

class Solution:
    def searchInsert(self, nums, target):

javascript

class Solution {
    searchInsert(nums, target) {
       
    }
}

csharp

public class Solution {
    public int SearchInsert(int[] nums, int target) {

    }
}

go

func searchInsert(nums []int, target int) int {
	//your code goes here
}
Solve on LeetCode →
Stuck? Show a way to structure it+
  1. 01Use half-open bounds
  2. 02Compare midpoint with target
  3. 03Keep candidate insertion boundary
  4. 04Return left after convergence
  5. 05Test endpoints

Reference answer

Then expect these follow-ups

  • Why is left the insertion position at termination?

    Tests: correctness reasoning

  • How would duplicates change the requested index?

    Tests: constraint adaptation

Hiring now

Get the InfoEdge India Ltd interview, not just the prep

landed applies to roles like these for you, on each company’s own site, with answers written for the role.

Get 5x interviews10 free auto-applies. No card.
Or practice this question first

Next question