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

UPDATED on 8/20/2016.

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

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

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>

  1. Kartrace on 2014-3-9

    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.

  2. Guest on 2014-6-1

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

  3. Sureshkumar T on 2014-11-10

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

  4. Swapnil Kumar on 2016-7-10

    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;
    }

  5. ryanlr on 2016-8-6

    Corrected. Thanks!

  6. Sumedha Prathipati on 2017-5-30

    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);
    }
    }
    }
    }
    }

Leave a comment

*