DEV Community

Tanuja V
Tanuja V

Posted on • Edited on

2 1 1 2 1

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

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

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?

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more