← Questions

Find first and last position of an element in a sorted array

0
Applied IntuitionMetaCodingLast asked Feb 2026

A coding interview question asked in Applied Intuition's technical phone screen and at Meta, last asked Feb 2026. It tests binary-search and arrays.

Given an integer array sorted in non-decreasing order and a target, return the index of the target's first and last occurrence, or [-1, -1] if it is not present. Run in O(log n).

Interface

Unless you agree on a different interface with the interviewer, assume:

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

Example

search_range([5, 7, 7, 8, 8, 10], 8)  ->  [3, 4]
search_range([5, 7, 7, 8, 8, 10], 6)  ->  [-1, -1]
search_range([], 0)                   ->  [-1, -1]
search_range([2, 2, 2], 2)            ->  [0, 2]

Constraints

  • 0 <= len(nums) <= 10^5; values fit in 32-bit integers.
  • O(log n) time, O(1) extra space.

Clarifying questions

  • Can the array be empty?
  • Are there many duplicates, so that scanning out from one hit could be O(n)?
  • Should the answer be two indices or a count?

What a strong answer covers

  • Two binary searches: the first index with nums[i] >= target and the first with nums[i] > target, minus one; or one lower-bound helper called twice.
  • A consistent loop invariant (half-open [lo, hi)), so there are no off-by-one bugs or infinite loops.
  • Why expanding from a single hit is O(n) in the worst case.
  • Tests: empty array, target absent, target at both ends, every element equal.

Follow-ups

  • Return how many times the target occurs.
  • The array is rotated sorted. Find the target's range.
  • The data is too large to index and sits behind an expensive get(i) call. Minimize calls.

Where it's asked

  • Applied Intuition · Technical phone screen · Last asked Feb 202645 min · Live coding in CoderPad; the language can be fixed by the role (Python, C++, or C for embedded)
  • Meta · AI-enabled coding · Last asked Oct 202560 min · Several progressive tasks on a starter codebase in CoderPad with an AI assistant panel; usually two rounds · The first task usually without AI, later tasks with it

What it tests

binary-search · arrays

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding