1158. Shuffle Applied K Times

Medium3.5 points estimatedSimulationArrayMaths

A deck has n cards, and nums[i] is the value of the card at position i. A shuffle machine acts on all cards at once: the card at position i is moved to position perm[i], where perm is a permutation of 0..n-1.

Run the machine exactly k times and return the deck as an array of values, indexed by position. The count k can be as large as 10^15, so the runs cannot be replayed one by one. Constraints: 1 <= n <= 2*10^5, 0 <= k <= 10^15 and -10^9 <= nums[i] <= 10^9. Aim for O(n) time and O(n) space.

Example 1

Input:
nums = [10,20,30], perm = [1,2,0], k = 1
Output:
[30,10,20]
Explanation:

One shuffle sends position 0 to 1, 1 to 2 and 2 to 0, so the values become [30, 10, 20].

Example 2

Input:
nums = [5,6,7,8], perm = [1,0,3,2], k = 3
Output:
[6,5,8,7]
Explanation:

The machine swaps neighbouring pairs, so an odd number of runs gives [6, 5, 8, 7].

Example 3

Input:
nums = [1,2,3], perm = [0,1,2], k = 1000000000000000
Output:
[1,2,3]
Explanation:

The permutation is the identity, so any number of shuffles leaves the deck unchanged.

Constraints

1 ≤ n ≤ 2*105
perm is a permutation of 0..n-1
0 ≤ k ≤ 1015
-109 ≤ nums[i] ≤ 109

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 2,000 msC++ 500 msJava 1,000 msJavaScript 1,000 msTypeScript 1,000 ms

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…