|
| 1 | +# https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/ |
| 2 | +# Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value. |
| 3 | +# If target is not found in the array, return [-1, -1]. |
| 4 | +# You must write an algorithm with O(log n) runtime complexity. |
| 5 | +# Example 1: |
| 6 | +# Input: nums = [5,7,7,8,8,10], target = 8 |
| 7 | +# Output: [3,4] |
| 8 | +# |
| 9 | + |
| 10 | +# recursive solution |
| 11 | +def search_range(nums, target) |
| 12 | + output_range = [-1, -1] |
| 13 | + # try to go left |
| 14 | + binary_search_helper(nums, target, 0, nums.length - 1, output_range, true) |
| 15 | + |
| 16 | + # go right |
| 17 | + binary_search_helper(nums, target, 0, nums.length - 1, output_range, false) |
| 18 | + output_range |
| 19 | +end |
| 20 | + |
| 21 | +# recursive solution |
| 22 | +def binary_search_helper(nums, target, left, right, output_range, go_left) |
| 23 | + return if left > right |
| 24 | + |
| 25 | + mid = (left + right) / 2 |
| 26 | + if target > nums[mid] |
| 27 | + binary_search_helper(nums, target, mid + 1, right, output_range, go_left) |
| 28 | + elsif target < nums[mid] |
| 29 | + binary_search_helper(nums, target, left, mid - 1, output_range, go_left) |
| 30 | + elsif go_left |
| 31 | + # if value found at mid, we will try to go left or right |
| 32 | + if mid.zero? || nums[mid - 1] != target |
| 33 | + output_range[0] = mid |
| 34 | + else |
| 35 | + binary_search_helper(nums, target, left, mid - 1, output_range, go_left) |
| 36 | + end |
| 37 | + # if we are at 1st value or previous value is not same as target |
| 38 | + # means we have found the start of the range value |
| 39 | + elsif mid == nums.length - 1 || target != nums[mid + 1] |
| 40 | + # we have reached at end of array or the next value is not equal to target |
| 41 | + # we have found end of the range |
| 42 | + output_range[1] = mid |
| 43 | + else |
| 44 | + binary_search_helper(nums, target, mid + 1, right, output_range, go_left) |
| 45 | + end |
| 46 | +end |
| 47 | + |
| 48 | +puts search_range([5, 7, 7, 8, 8, 10], 6).to_s |
| 49 | + |
| 50 | +puts search_range([0, 1, 21, 33, 45, 45, 45, 45, 45, 45, 61, 71, 73], 45).to_s |
0 commit comments