DEV Community

SaiPavan Seelamsetty
SaiPavan Seelamsetty

Posted on

2 2

Find First and Last Position of Element in Sorted Array - Python

Given an array of integers nums sorted in non-decreasing order, find the starting and ending position of a given target value.

If target is not found in the array, return [-1, -1].

You must write an algorithm with O(log n) runtime complexity.

https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/

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]
Example 3:

Input: nums = [], target = 0
Output: [-1,-1]

Constraints:

0 <= nums.length <= 105
-109 <= nums[i] <= 109
nums is a non-decreasing array.
-109 <= target <= 109

    def searchRange(self, numbers: List[int], target: int) -> List[int]:
        result=[-1,-1]
        l=0
        h=len(numbers)-1
        while l<=h:
            mid=(l+h)//2
            if target>numbers[mid]:
                l=mid+1
            elif target<numbers[mid]:
                h=mid-1
            else:
                result[0]=mid
                h=mid-1
        l=0
        h=len(numbers)-1
        while l<=h:
            mid=(l+h)//2
            if target>numbers[mid]:
                l=mid+1
            elif target<numbers[mid]:
                h=mid-1
            else:
                result[1]=mid
                l=mid+1
        return result   


Enter fullscreen mode Exit fullscreen mode

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay