DEV Community

Tanuja V
Tanuja V

Posted on • Updated on

Find First and Last Position of Element in Sorted Array | LeetCode | Java

In this problem, we would be applying the two binary search to check whether the target element is present or not. If present, we would be moving the pointers forward & backward to find the occurrence of the element (first & last).

class Solution {
    public int[] searchRange(int[] nums, int target) {

        int res[] = {-1, -1};

        int n = nums.length;

        int low = 0, high = n-1;

        while(low<=high){

            int mid = low + (high-low)/2;

            if(nums[mid]==target){
                res[0] = mid;
                high = mid-1;
            }

           else if(nums[mid]<target)
                low = mid+1;

            else
                high = mid-1;
        }

        low = 0;
        high = n-1;

        while(low<=high){

            int mid = low + (high-low)/2;

            if(nums[mid]==target){
                res[1] = mid;
                low = mid+1;
            }

           else if(nums[mid]<target)
                low = mid+1;

            else
                high = mid-1;
        }

        return res;
    }
}
Enter fullscreen mode Exit fullscreen mode

Thanks for reading :)
Feel free to comment and like the post if you found it helpful
Follow for more 🤝 && Happy Coding 🚀

If you enjoy my content, support me by following me on my other socials:
https://linktr.ee/tanujav7

Top comments (1)

Collapse
 
ivis1 profile image
Ivan Isaac

Really clear explanation on using binary search twice! For the initial low and high, what prompted you to choose those values specifically?