Find the starting and ending position of a given target value.
nums = [5,7,7,8,8,10], target = 8 → [3,4]
# 2. Binary Search Variant: Find First and Last Position of Element
# Problem Statement:
# Find the starting and ending position of a given target value.
# Input: nums = [5,7,7,8,8,10], target = 8
# Output: [3,4]
# Time Complexity: O(log n)
def self.search_range(nums, target)
def find_bound(nums, target, is_first)
left, right = 0, nums.size - 1
bound = -1
while left <= right
mid = left + (right - left) / 2
puts "Debug: left=#{left}, right=#{right}, mid=#{mid}, nums[mid]=#{nums[mid]}, is_first=#{is_first}"
if nums[mid] == target
bound = mid
if is_first
right = mid - 1
else
left = mid + 1
end
elsif nums[mid] < target
left = mid + 1
else
right = mid - 1
end
end
bound
end
[ find_bound(nums, target, true), find_bound(nums, target, false) ]
O(log n)
O(1)