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

Suppose we have an array of integers A. This is sorted in ascending order, we have to find the starting and ending position of a given target value. When the target is not found in the array, return [-1, -1]. So if the array is like [2,2,2,3,4,4,4,4,5,5,6], and target is 4, then the output will be [4,7]

To solve this, we will follow these steps −

• Initially res := [-1,-1], set low := 0, high := length of array A
• while low < high
• mid := low + (high – low)/2
• if A[mid] is target, then
• high := mid, res := mid and res := mid
• otherwise when A[mid] < target, then low := mid + 1, else high := mid
• if res = -1, then return res
• low := res + 1, high := length of nums
• while low < high
• mid := low + (high – low)/2
• if A[mid] is target, then
• low := mid + 1, res := mid
• otherwise when A[mid] < target, then low := mid + 1, else high := mid
• return res

## Example(Python)

Let us see the following implementation to get better understanding −

Live Demo

class Solution(object):
def searchRange(self, nums, target):
res = [-1,-1]
low = 0
high = len(nums)
while low<high:
mid = int(low + (high-low)//2)
if nums[mid] == target:
high = mid
res=mid
res=mid
elif nums[mid]<target:
low = mid+1
else:
high = mid
if res == -1:
return res
low = res+1
high = len(nums)
while low<high:
mid = int(low + (high-low)//2)
if nums[mid] == target:
low = mid+1
res = mid
elif nums[mid] < target:
low = mid + 1
else:
high = mid
return res
ob1 = Solution()
print(ob1.searchRange([2,2,2,3,3,4,4,4,4,5,5,6], 4))

## Input

[2,2,2,3,4,4,4,4,5,5,6]
4

## Output

[5, 8]