← Questions

Target indices after sorting an array

0
MetaCodingLast asked Jul 2025

A coding interview question asked in Meta's AI-enabled coding round, last asked Jul 2025. It tests binary-search and counting.

Given an integer array nums and a target, return the indices at which target would sit once nums is sorted in non-decreasing order. Then solve it when nums is already sorted, in logarithmic time.

Interface

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

  • target_indices(nums: list[int], target: int) -> list[int] — 0-based indices into the sorted array, in increasing order; [] when target is absent.

Example

target_indices([1, 2, 5, 2, 3], 2)  ->  [1, 2]   # sorted: [1, 2, 2, 3, 5]
target_indices([1, 2, 5, 2, 3], 3)  ->  [3]
target_indices([1, 2, 5, 2, 3], 4)  ->  []

Constraints

  • 1 <= len(nums) <= 100,000; values and target in [-10^9, 10^9].

Clarifying questions

  • Is the input already sorted, or must I account for sorting?
  • Are the indices 0-based into the sorted array?
  • Should I return the full list of indices or only the first and last position?

What a strong answer covers

  • The obvious O(n log n) way: sort and scan.
  • The O(n) way without sorting: count values less than target (lt) and equal to it (eq); the answer is lt, lt + 1, ..., lt + eq - 1.
  • When nums is already sorted: two binary searches for the first and last occurrence (lower and upper bound), O(log n) to find the range.
  • Off-by-one care in the binary searches, and the empty-range case.
  • Tests: target absent, target smaller or larger than every value, every value equal to the target.

Follow-ups

  • Return only [first, last] positions in a sorted array, or [-1, -1] when absent.
  • Count the occurrences of target in a sorted array in O(log n).
  • The sorted array is rotated at an unknown pivot.

Where it's asked

  • Meta · AI-enabled coding · Last asked Jul 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 · counting

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