Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Search for a range of a target in a sorted array

Find the starting and ending positions of a target value in a sorted array using binary search.

Python practice15 minSearching & SortingIntermediateLast updated March 25, 2026

Problem statement

Given a sorted list of integers nums and an integer target, return a list [first_index, last_index] representing the first and last positions of target in nums. If target is not found, return [-1, -1]. Achieve O(log n) time using binary search (no full linear scan).

Task

Implement an efficient O(log n) search to find the first and last occurrence indices of a target in a sorted list.

Examples

Target occurs multiple times

Input

nums = [2, 4, 4, 4, 6], target = 4

Output

[1, 3]

The target 4 first appears at index 1 and last at index 3.

Input format

Function call: search_range(nums, target) where nums is a sorted list of integers and target is an integer.

Output format

Return a list [first_index, last_index] (both integers). If not found return [-1, -1].

Constraints

- 0 <= len(nums) <= 10^5 - nums is non-decreasing (sorted) - Use binary search for O(log n) time

Samples

Sample 1

Input

search_range([1,2,3,3,3,4], 3)

Output

[2, 4]

3 appears from index 2 through 4.