← Questions

Order queries to minimize total completion time

0
Scale AICodingLast asked Apr 2026

A coding interview question asked in Scale AI's coding round, last asked Apr 2026. It tests greedy, sorting and scheduling.

You get a list of queries, each written as an interval [start, end]. Running a query takes end - start time units; the endpoints say nothing about when it may run. One worker runs whole queries one after another, starting at time 0, with no gaps and no preemption. A query's completion time is the moment it finishes. Return the query indices in the order that makes the sum of completion times as small as possible, and argue why that order is optimal.

Interface

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

  • processing_order(intervals: list[list[int]]) -> list[int] — returns every zero-based index exactly once. Empty input returns [].

Example

processing_order([[0,3],[10,11],[2,4]])        ->  [1, 2, 0]      # durations 3, 1, 2; finishes at 1, 3, 6; total 10
processing_order([[5,7],[0,2],[9,11]])         ->  [0, 1, 2]      # all durations 2; ties go to the smaller index
processing_order([[1,6],[0,2],[3,4],[2,4]])    ->  [2, 1, 3, 0]   # durations 5, 2, 1, 2; total 19
processing_order([])                           ->  []

Constraints

  • 0 <= len(intervals) <= 100,000.
  • 0 <= start < end <= 10^9.
  • Intervals may overlap, nest or repeat; each row is its own query.
  • Queries with equal durations go in ascending index order.

Clarifying questions

  • Do the interval endpoints restrict when a query may start, or only give its length?
  • Can the worker pause one query to run another?
  • How should ties between equal durations be ordered?
  • Do all queries arrive at time 0, or do some arrive later?

What a strong answer covers

  • Shortest processing time first: sort by (duration, index), O(n log n) time.
  • The exchange argument: if a longer query runs right before a shorter one, swapping them lowers the total by the difference in their lengths, so no optimal order has such a pair.
  • Why the total equals the sum of duration × (number of queries from it to the end).
  • Large sums: with 10^5 queries of length up to 10^9 the total reaches about 5 × 10^18, so it needs 64-bit integers.
  • Tests for empty input, all-equal durations and identical rows.

Follow-ups

  • Queries arrive at different times: what changes, and when does preemption (shortest remaining time first) help?
  • Each query has a weight: minimize the weighted sum of completion times (sort by duration / weight).
  • Several identical workers run in parallel.

Where it's asked

  • Scale AI · Coding · Last asked Apr 2026Live coding, one or two rounds, Python

What it tests

greedy · sorting · scheduling

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