[Question] 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.
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]
// TC: O(2log(N))
// SC: O(1)
func findFirstAndLastOccurance(_ arr: [Int], _ targetElement: Int) -> [Int] {
func findFirstOccurance() ->Int {
let arrayCount = arr.count
var low = 0
var high = arrayCount - 1
var idx = -1
while low <= high {
let mid = (low + high) / 2
if arr[mid] >= targetElement {
high = mid - 1;
} else{
low = mid + 1;
}
if arr[mid] == targetElement {
idx = mid
}
}
return idx
}
func findLastOccurance() ->Int {
let arrayCount = arr.count
var low = 0
var high = arrayCount - 1
var idx = -1
while low <= high {
let mid = (low + high) / 2
if arr[mid] <= targetElement {
low = mid + 1;
} else{
high = mid - 1;
}
if arr[mid] == targetElement {
idx = mid
}
}
return idx
}
return [findFirstOccurance(), findLastOccurance()]
}
var inputBinArray = [5,7,7,8,8,10]
let targetElem = 8
let opFirstAndLast = findFirstAndLastOccurance(inputBinArray, targetElem)
print("opFirstAndLast --- ", opFirstAndLast)// 3, 4
We can also solve a Question like Count Occurrences of a number in Sorted Array
// Question 7 : Count occurrence in Sorted array.
let ipCountArray = [2, 4, 6, 8, 8, 8, 11, 13]
let opCountOccurance = findFirstAndLastOccurance(ipCountArray, 8)
print("opCountOccurance---",(opCountOccurance.last! - opCountOccurance.first!) + 1 ) // 3