Neural Mastery
← Practice
Find First and Last Position of Element in Sorted Arraymedium

Find First and Last Position of Element in Sorted Array

medium Coding Interview Patterns 15–20 min

NumPy allowed · plain Python earns 10 bonus points

Interactive
Graph & Tree Traversal, Step by Step
Structure
Algorithm
ABCDE
visiting A -> visited order so far: [A]
queue now: [B, C]
Step 1 / 5
Both modes run the real algorithm from the linked practice problem, one step at a time -- edit the graph or pick different tree nodes and every step recomputes live.

Implement Find First and Last Position -- two binary searches for two different boundaries (the leftmost and rightmost occurrence of a repeated value), the classic real use case for duplicate-tolerant binary search.

Related Skills

Task

Implement search_range(nums, target): run one binary search biased to keep shrinking left after finding a match (to find the FIRST occurrence), and a second biased to keep shrinking right (to find the LAST occurrence).

Function Signature

search_range(nums: list[int], target: int) -> list[int]

Examples

Example 1: Multiple Occurrences
Input: nums = [5, 7, 7, 8, 8, 10] target = 8
Output: [3, 4]
Example 2: Target Absent
Input: nums = [5, 7, 7, 8, 8, 10] target = 6
Output: [-1, -1]

Constraints

  • Libraries (e.g. bisect) are allowed and accepted normally; A plain-Python solution earns 10 bonus points.
  • Must run in O(log n) time -- a linear scan through duplicates does not satisfy the intended solution.
  • Return [-1, -1] if target does not appear anywhere in nums.
Python3Saved ✓
def search_range(nums: list[int], target: int) -> list[int]:
"""nums: sorted ascending, may contain duplicates. Return [first,
last] -- the indices of target's first and last occurrence -- or
[-1, -1] if target is not present. Must run in O(log n) time."""
# Your implementation here
pass

Case 1: Multiple Occurrences
Input: nums = [5, 7, 7, 8, 8, 10] target = 8
Expected: [3, 4]
Case 2: Target Absent
Input: nums = [5, 7, 7, 8, 8, 10] target = 6
Expected: [-1, -1]