Skip to content
LakeBench
ProblemsCommunityPricing
Sign inStart practicing

First and last position in a sorted list

Python data engineering interview problem. Difficulty: intermediate. Pattern: Binary Search. About 14 minutes. Part of the Pro drill bank.

Find the first and last index of a target in a sorted list with duplicates, in logarithmic time. Treat this as a production helper: match the contracted return shape, including empty and duplicate inputs.

Implement search_range(nums: list[int], target: int) -> list[int]. nums is sorted in ascending order and may contain duplicates. Return [first, last], the lowest and highest index where target occurs. Return [-1, -1] if it does not occur. The list can hold 100,000 elements, so the work should grow with the logarithm of its length, not with its length.

Requirements

  • Return a list of two ints.

Constraints

  • Up to 100,000 elements.
  • Aim for O(log n) time; a scan over the whole list is too slow.

Examples

Input: search_range([5, 7, 7, 8, 8, 10], 8) Output: [3, 4] 8 first appears at index 3 and last at index 4.

Topics: lakebench, python, sorted, boundaries, log n.

More Python interview questions · All interview problems · Learn data engineering

intermediate

First and last position in a sorted list

Interview-style drill: Find the first and last index of a target in a sorted list with duplicates, in logarithmic time.

Implement `search_range(nums: list[int], target: int) -> list[int]`. `nums` is sorted in ascending order and may contain duplicates. Return `[first, last]`, the lowest and highest index where `target` occurs. Return `[-1, -1]` if it does not occur. The list can hold 100,000 elements, so the work should grow with the logarithm of its length, not with its length.