← Questions

Fewest passes to collect a permutation in order

0
AmazonCodingLast asked Jul 2025

A coding interview question asked in Amazon's online assessment, last asked Jul 2025. It tests arrays and counting.

A shelf holds the numbers 1..n in some order, each exactly once. You collect them in order: start with target 1 and walk the shelf left to right. Whenever the number in front of you is the current target, you take it, the target becomes the next number, and you keep walking. When you reach the end of the shelf and numbers are still missing, you start a new pass from the left. Return how many passes it takes to collect all n numbers.

Interface

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

  • count_passes(shelf: list[int]) -> int — shelf is a permutation of 1..n; returns the number of passes started.

Example

[3, 1, 2, 5, 4]  ->  3    # pass 1 takes 1, 2; pass 2 takes 3, 4; pass 3 takes 5
[1, 2, 3]        ->  1
[3, 2, 1]        ->  3

Constraints

  • 1 <= n <= 200,000
  • shelf is a permutation of 1..n.
  • Aim for O(n) time and O(n) extra space.

Clarifying questions

  • Is the shelf always a full permutation, with no missing or repeated numbers?
  • Does the first walk count as a pass?
  • Can I take several numbers in one pass when they appear in order?

What a strong answer covers

  • Simulation first, and why it is O(n^2) in the worst case ([n, n-1, ..., 1]).
  • The key fact: record the position of each value. Number v + 1 needs a new pass exactly when it sits to the left of v.
  • Answer = 1 + the number of v with pos[v + 1] < pos[v]; O(n) time.
  • Tests: sorted, reversed, n = 1.

Follow-ups

  • Queries swap two positions; report the pass count after each swap in O(1).
  • The shelf may hold duplicates and you need one copy of each value, in order. What changes?
  • The shelf is a circle and you keep walking without returning to the start. How many full laps?

Where it's asked

  • Amazon · Online assessment · Last asked Jul 2025Coding problems plus a repository bug-fix section with a built-in assistant or a design scenario, then a work-style survey · AI only inside the bug-fix section's built-in assistant

What it tests

arrays · 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