Leetcode–Search Insert Position

The Problem:

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


  1. Be careful about bounds, and do binary search.
  2. Attention to return low or high, also see in Sqrt(x)
  3. Mistake I made:
    1. if target equals to or less than first number, both return 0; but if target equals to last number return length-1, greater than last number should return length.

Java Solution

public class Solution {
    public int searchInsert(int[] A, int target) {
        if(A==null || A.length==0) return 0;
        if(target <= A[0]) return 0;
        if(target > A[A.length-1]) return A.length;
        int low = 0;
        int high = A.length-1;
        while(low <= high){
            int mid = (high+low)/2;
                return mid;
            if(A[mid] < target){
                low = mid+1;
                high = mid-1;
        return low;

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s