1679. Front or Back Dealer

Easy1.5 points estimatedQueueGreedyArray

A dealer receives the numbers of a permutation of 1..n one at a time, in the order given by perm. Each number is placed either at the front or at the back of a row that starts empty. After every number has been placed, the row read from front to back is the deal.

Return the lexicographically smallest deal that can be produced, comparing rows element by element from the front. The greedy rule is: place a number at the front exactly when it is smaller than the number currently at the front of the row, otherwise place it at the back (the first number simply starts the row). Use a double-ended queue so each placement is O(1); the whole task takes O(n) time and O(n) space. Constraints: 1 <= n = perm.length <= 1000 and perm is a permutation of 1..n.

Example 1

Input:
perm = [2,1,3]
Output:
[1,2,3]
Explanation:

2 starts the row, 1 is smaller than 2 so it goes in front, and 3 goes to the back.

Example 2

Input:
perm = [3,1,2]
Output:
[1,3,2]
Explanation:

3 starts, 1 goes to the front, and 2 is not smaller than the front 1 so it goes to the back, giving 1,3,2.

Example 3

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

Every number is smaller than the current front, so each one goes in front.

Constraints

1 ≤ perm.length ≤ 1000; perm is a permutation of 1..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…