You are given an array nums of length n in which every value is a valid index into the array, and an integer k.
One iteration replaces every element at the same time with the value found at the index it points to: the new array has new[i] = nums[nums[i]] for every i, and all reads use the array as it was before the iteration. The new array then becomes nums for the next iteration.
Return the array after exactly k iterations. Because k can be as large as 109, a solution that performs every iteration one at a time is too slow.
Function Signature
def simulate_array(nums: list[int], k: int) -> list[int]:
Rules
-
All positions update simultaneously. Within one iteration, every read uses the array from before that iteration.
-
k = 0
means no iterations: return the values of
nums
unchanged.
-
Return a list of length
n
whose element
i
is the final value at index
i
.
Constraints
-
1 <= n <= 1000
-
0 <= nums[i] < n
-
0 <= k <= 10^9
Examples
Input: nums = [1,0,3,2], k = 1000000000
Output: [0,1,2,3]
After one iteration the array is [0,1,2,3] (for example, new[0] = nums[nums[0]] = nums[1] = 0). Every element of [0,1,2,3] points to itself, so later iterations change nothing.
Input: nums = [2,0,1], k = 5
Output: [1,2,0]
Iteration 1 gives [1,2,0] and iteration 2 gives [2,0,1] again, so the array alternates between the two states. After any odd number of iterations it is [1,2,0].
Input: nums = [1,2,3,4,2], k = 1000000000
Output: [4,2,3,4,2]
Iterations 1, 2 and 3 give [2,3,4,2,3], [4,2,3,4,2] and [2,3,4,2,3], so from iteration 1 on the array alternates and every even iteration gives [4,2,3,4,2]. The starting array never comes back, so the repetition starts at iteration 1, not at iteration 0.