LeetCode – Search Insert Position (Java)

Given a sorted array 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. You may assume no duplicates in the array.

Here are few examples.

[1,3,5,6], 5 -> 2
[1,3,5,6], 2 -> 1
[1,3,5,6], 7 -> 4
[1,3,5,6], 0 -> 0

Java Solution

This is a binary search problem. The complexity should be O(log(n)).

public int searchInsert(int[] nums, int target) {
    if(target>nums[nums.length-1]){
        return nums.length;
    }
 
    int l=0;
    int r=nums.length-1;
 
    while(l<r){
        int m = l+(r-l)/2;
        if(target>nums[m]){
            l=m+1;
        }else{
            r=m;
        }
    }
 
    return l;
}

Or similarly, we can write the solution like the following:

public int searchInsert(int[] nums, int target) {
    int i=0; 
    int j=nums.length-1;
 
    while(i<=j){
        int mid = (i+j)/2;
 
        if(target > nums[mid]){
            i=mid+1;
        }else if(target < nums[mid]){
            j=mid-1;
        }else{
            return mid;
        }
    }
 
    return i;
}
Category >> Algorithms  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code> 
String foo = "bar";
</code></pre>
  • tpark

    thank you for the reply, but my question probably wasn’t clear enough.

    my question is that when the stopping condition in the while loop is not met ( i.e. i==j or l==r) then
    the last line is return i or return l. Here is my question. Why does it return i or l at the end ?
    why can’t it return j or r?

  • ryanlr

    In the first version, the stop condition is l==r, so l and r are the same.

    In the second version, the stop condition is i==j+1, so i is used as j is already on the left of i.

  • tpark

    If the number is not found why does it have to return l or i? why not r or j?

  • Ferdaous


    public int searchInsert(int []a, int l, int r, int x){
    if(lx)
    return searchInsert(a,l,mid-1,x);
    if(a[mid]<x)
    return searchInsert(a,mid+1,r,x);

    }
    return r+1;
    }
    }

  • Sumedha Prathipati

    This is my take on the problem !

    import java.util.*;
    class Fifteen
    {
    public static void main(String args[])
    {
    Scanner sc=new Scanner(System.in);
    int n=sc.nextInt();
    int arr[]=new int[n];
    for(int i=0;i<n;i++)
    {
    int x=sc.nextInt();
    arr[i]=x;
    }
    int target=sc.nextInt();
    for(int i=0;i<n;i++)
    {
    if(arr[i]==target)
    System.out.println(i);
    else
    {
    try
    {
    if(arr[i]<target && target<arr[i+1])
    System.out.println(i+1);
    else if(target<arr[0])
    {
    System.out.println("0");
    break;
    }
    }
    catch(Exception e)
    {
    System.out.println(i+1);
    }
    }
    }
    }
    }

  • ryanlr

    Corrected. Thanks!

  • Swapnil Kumar

    Can some one review my code –
    public int searchInsert(int[] nums, int target) {
    int low = 0;
    int high = nums.length – 1;

    while(low <= high){
    int mid = (high + low)/2 ;
    if(nums[mid] == target){
    return mid;
    }
    else if(target nums[high]){
    return high + 1;
    }
    return high;
    }else if(low > high){
    return low;
    }
    }

    return -1;
    }

  • Sureshkumar T

    for midpoint method the complexity is O(ln(n)) where n is size of the array..

  • Guest

    For the binary search method the runtime is incorrectly stated to O(nlogn) it should be O(log n)

  • Kartrace

    the mid can be calculated as mid = start + (end-start)/2 to avoid start+end integer overflow if both start and end are big numbers.