1718. Stack-Sortable Completion

Hard7.5 points estimatedStackGreedyArray

Wagons numbered 1 to n arrive one at a time on a single track and each must pass through a one-track siding that works like a stack: a wagon may wait in the siding, but only the most recently parked wagon can leave. The leaving order has to be 1, 2, ..., n. A permutation of the arrival order is called stack-sortable when this can be done. The first wagons to arrive are already fixed and given as prefix (distinct values from 1 to n). Return the lexicographically largest full arrival order of all n wagons that starts with prefix and is stack-sortable, or the array [-1] if no such order exists. Here 1 <= n <= 1000 and 1 <= prefix.length <= n. Aim for O(n) time: simulate the prefix, then repeatedly emit the unused numbers below the current top in decreasing order.

Example 1

Input:
n = 4, prefix = [3]
Output:
[3,2,1,4]
Explanation:

Wagon 3 waits in the siding, so 2 and 1 must come next in that order and 4 last, giving [3, 2, 1, 4].

Example 2

Input:
n = 3, prefix = [1,3]
Output:
[1,3,2]
Explanation:

Wagon 1 leaves at once, wagon 3 waits, and the only wagon left is 2, so the result is [1, 3, 2].

Example 3

Input:
n = 3, prefix = [2,3]
Output:
[-1]
Explanation:

Wagon 3 would sit on top of the smaller wagon 2, which could then never leave first, so no order exists.

Constraints

1 ≤ n ≤ 1000

1 ≤ prefix.length ≤ n

prefix holds distinct values from 1 to n

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O(n)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…