Friday, January 9, 2015

Search Insert Position and Search for a Range

Both problems require binary search. There are two ways to write the loop:

 while (start + 1 < end) {
            int mid = (start + end) / 2;
            if (A[mid] == target)
                return mid;
            else if (A[mid] < target) 
                start = mid;
            else
                end = mid;
        }

Or:

 while (start < end) {
            int mid = (start + end) / 2;
            if (A[mid] == target)
                return mid;
            else if (A[mid] < target) 
                start = mid + 1;
            else
                end = mid - 1;
        }

The first one exits the loop when there are two elements left and the second one exits when there is only one element. I always prefer the second one because it requires less comparison after exiting the loop.

However, for these problem, it is better to use the first one, because both problems require us to search for a range.

Search Insert Position
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

If there are two elements left when we exit the loop, either the target is at the start, the end, or we need to insert it in between. If we exit the loop with only one element, and if the target doesn't equal to the element at that position, then it's hard for us to determine where to add the target.

public int searchInsert(int[] A, int target) {
        if (A == null)
            throw new NullPointerException("Null array!");
        if (A.length == 0)
            return 0;
        if (target <= A[0])
            return 0;
        if(target > A[A.length - 1])
            return A.length;
        int start = 0;
        int end = A.length - 1;
        while (start + 1 < end) {
            int mid = (start + end) / 2;
            if (A[mid] == target)
                return mid;
            else if (A[mid] < target) 
                start = mid;
            else
                end = mid;
        }
        if (A[start] == target)
            return start;
        else if (A[end] == target)
            return end;
        return start + 1;
    }

Search for a Range
Given a sorted array of integers, find the starting and ending position of a given target value.
Your algorithm's runtime complexity must be in the order of O(log n).
If the target is not found in the array, return [-1, -1].
For example,
Given [5, 7, 7, 8, 8, 10] and target value 8,
return [3, 4].

For this problem, my approach is to do binary search twice, first time to search for the start position of the range, the second to search for the end position. Since we are looking for a range, when A[mid] == target, we can not simply return the mid, to search for the start point, we search the first half of the array, and to search for the end point, we search the second half of the array.


public int[] searchRange(int[] A, int target) {
        if (A == null)
            throw new NullPointerException("Null array!");
        int[] bound = new int[2];
        bound[0] = -1;
        bound[1] = -1;
        if (A.length == 0 || target < A[0] || target > A[A.length - 1])
            return bound;
        int start = 0;
        int end = A.length - 1;
        while (start + 1< end) {
            int mid = (start + end) / 2;
            if (A[mid] == target) {
                end = mid;
            }
            else if (A[mid] < target)
                start = mid;
            else
                end = mid;
        }
        if (A[start] == target)
            bound[0] = start;
        else if (A[end] == target)
            bound[0] = end;
        else
            return bound;
        start = 0;
        end = A.length - 1;
        while (start + 1 < end) {
            int mid = (start + end) / 2;
            if (A[mid] == target)
                start = mid;
            else if (A[mid] < target)
                start = mid;
            else
                end = mid;
        }
        if (A[end] == target)
            bound[1] = end;
        else if (A[start] == target)
            bound[1] = start;
        else 
            bound[0] = -1;
        return bound;
        
    }

1 comment:

  1. The development of artificial intelligence (AI) has propelled more programming architects, information scientists, and different experts to investigate the plausibility of a vocation in machine learning. Notwithstanding, a few newcomers will in general spotlight a lot on hypothesis and insufficient on commonsense application. IEEE final year projects on machine learning In case you will succeed, you have to begin building machine learning projects in the near future.

    Projects assist you with improving your applied ML skills rapidly while allowing you to investigate an intriguing point. Furthermore, you can include projects into your portfolio, making it simpler to get a vocation, discover cool profession openings, and Final Year Project Centers in Chennai even arrange a more significant compensation.


    Data analytics is the study of dissecting crude data so as to make decisions about that data. Data analytics advances and procedures are generally utilized in business ventures to empower associations to settle on progressively Python Training in Chennai educated business choices. In the present worldwide commercial center, it isn't sufficient to assemble data and do the math; you should realize how to apply that data to genuine situations such that will affect conduct. In the program you will initially gain proficiency with the specialized skills, including R and Python dialects most usually utilized in data analytics programming and usage; Python Training in Chennai at that point center around the commonsense application, in view of genuine business issues in a scope of industry segments, for example, wellbeing, promoting and account.

    ReplyDelete