Katkat

Find the Index Range of a Target in a Sorted Array

CitadelSoftware Engineer · Technical Screen

Last updated

Implement an algorithm to find the first and last index of a target value in a sorted array in O(log n) time.

Problem Statement

Given an array of integers nums sorted in non-decreasing order, find the starting and ending index 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.

Function Signature

def find_target_range(nums: list[int], target: int) -> list[int]:
    pass

Input and Output Format

  • Input: A list of integers nums sorted in non-decreasing order, and an integer target.
  • Output: A list of two integers [first_index, last_index] representing the zero-indexed inclusive range of target, or [-1, -1] if target does not exist in nums.

Examples

Example 1

Input: nums = [5, 7, 7, 8, 8, 10], target = 8
Output: [3, 4]
Explanation: The target 8 appears first at index 3 and last at index 4.

Example 2

Input: nums = [5, 7, 7, 8, 8, 10], target = 6
Output: [-1, -1]
Explanation: The value 6 is not present in the array.

Example 3

Input: nums = [], target = 0
Output: [-1, -1]
Explanation: The array is empty, so target is not found.

Constraints

  • 0 <= len(nums) <= 10^5
  • -10^9 <= nums[i] <= 10^9
  • nums is sorted in non-decreasing order.
  • -10^9 <= target <= 10^9

Edge Cases to Consider

  • Empty array nums = [].
  • Array where all elements are identical to target (e.g., [2, 2, 2, 2], target = 2).
  • target is smaller than all elements or larger than all elements.
  • target appears exactly once.

Hints

Hint 1

A standard binary search stops immediately upon finding the target, but you can continue searching to find the extreme left and right matches.

Hint 2

Consider implementing a helper function that performs binary search with a boolean flag indicating whether you are searching for the left bound or right bound.

Hint 3

Another approach is finding the insertion position of target (lower bound) and the insertion position of target + 1.

Follow-up questions

  • How would you solve this problem if the array is an unbounded/infinite stream where the length is unknown in advance?
  • How does the implementation change if the sorted array has been rotated at an unknown pivot index?
  • Can you implement this using Python's standard library `bisect` module, and what would the exact function calls look like?