1676. Discard and Tuck

Easy1.5 points estimatedQueueSimulation

A stack of cards numbered 1 to n lies face up with card 1 on top and card n at the bottom. Repeat the following until no cards are left: discard the top card, then take the top card and put it at the bottom of the deck, doing this t times in a row. If fewer than t cards remain the moves just keep cycling the deck, and on an empty deck they do nothing.

Return an array holding all n card numbers in the order in which they were discarded. Model the deck as a queue where each tuck moves the front to the back. Rotating by t modulo the current size gives the same deck, so the simulation needs O(n * min(n, t)) time and O(n) space. Constraints: 1 <= n <= 1000 and 0 <= t <= 1000.

Example 1

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

Each discard is followed by one tuck: 1, 3 and 5 go first, then the deck holds 4 above 2.

Example 2

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

With no tucks the cards are discarded in their original order.

Example 3

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

After discarding 1 the deck 2,3 is tucked five times and ends as 3,2, so 3 goes next.

Constraints

1 ≤ n ≤ 1000; 0 ≤ t ≤ 1000

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 * min(n, t))
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…