Find First and Last Position

Find the starting and ending position of a given target value.

Medium

Examples

Example 1: nums = [5,7,7,8,8,10], target = 8 → [3,4]

Implementation

Ruby

  # 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) ]

Complexity Analysis

Time Complexity: O(log n)
Space Complexity: O(1)

Patterns & Techniques

Problem Details

Category: Binary Search And Sorting
Difficulty: Medium
Module: BinarySearchAndSorting
Method: self.search_range
← Back to Binary Search And Sorting