34. Find First and Last Position of Element in Sorted Array

Given an array of integers nums sorted in ascending order, 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].

Example 1:

Input: nums = [5,7,7,8,8,10], target = 8
Output: [3,4]

Example 2:

Input: nums = [5,7,7,8,8,10], target = 6
Output: [-1,-1]

Solution

class Solution {
    public int[] searchRange(int[] nums, int target) {
        int len = nums.length;
        int lo = 0;
        int hi = len - 1;
        boolean isFound = false;
        if(len == 0){
            return new int[]{-1,-1};
        }
        while(lo <= hi){
            if(nums[lo] == target && nums[hi] == target){
                isFound = true;
                break;
            }
            
            //invariant: nums[lo] < target && nums[hi] > target
            int mid = lo + (hi-lo)/2;
            if(nums[mid] > target){
                hi = mid - 1;
            }else if (nums[mid] < target){
                lo = mid + 1;
            }else if (nums[mid] == target){
                if(nums[lo] != target){
                    lo++;
                }else if (nums[hi] != target){
                    hi--;
                }
            }
        }
        return isFound ? new int[]{lo,hi} : new int[]{-1,-1};
        
    }
}

Last updated

Was this helpful?