Created
April 29, 2021 12:13
-
-
Save vrat28/5b74340b31b2a87d43751125e556e633 to your computer and use it in GitHub Desktop.
Find first and Last position of the element
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
func searchRange(_ nums: [Int], _ target: Int) -> [Int] { | |
let leftPos = find(nums, target, 0) | |
// Left position exceeds bounds or not found | |
if leftPos == nums.count || nums[leftPos] != target { | |
return [-1, -1] | |
} | |
// If left Position found, then atleast 1 occurence of the element is presence | |
// Then we can find the right position by finding for target + 1 | |
let rightPos = find(nums,target + 1,leftPos) - 1 | |
return [leftPos, rightPos] | |
} | |
func find(_ nums:[Int], _ target:Int,_ left:Int) -> Int { | |
var left = left, right = nums.count - 1 | |
while left <= right { | |
let mid = left + (right - left) / 2 | |
if nums[mid] < target { | |
left = mid + 1 | |
} | |
else{ | |
right = mid - 1 | |
} | |
} | |
return left | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment