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[0] := mid and res[1] := mid
- otherwise when A[mid] < target, then low := mid + 1, else high := mid
- if res[0] = -1, then return res
- low := res[0] + 1, high := length of nums
- while low < high
- mid := low + (high – low)/2
- if A[mid] is target, then
- low := mid + 1, res[1] := 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 −
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[0]=mid res[1]=mid elif nums[mid]<target: low = mid+1 else: high = mid if res[0] == -1: return res low = res[0]+1 high = len(nums) while low<high: mid = int(low + (high-low)//2) if nums[mid] == target: low = mid+1 res[1] = 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]