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) {
        return -1;
        return nums.length;
    int i=0;
    int j=nums.length;
        int m=(i+j)/2;
    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;
        int mid = (i+j)/2;
        if(target > nums[mid]){
        }else if(target < nums[mid]){
            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:
String foo = "bar";
  • 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.