Shuffle array using random integer API
Company: Google
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: hard
Interview Round: Technical Screen
Quick Answer: This question evaluates understanding of randomized algorithms, uniform probability distributions over permutations, in-place array manipulation, and time/space complexity analysis within the Coding & Algorithms domain.
Constraints
- 0 <= len(nums) <= 100000
- All values in nums are distinct integers
- len(random_indices) == max(0, len(nums) - 1)
- For each k, 0 <= random_indices[k] <= len(nums) - 1 - k
- The algorithm must run in O(n) time and use O(1) extra space, not counting the input arrays
Examples
Input: ([1, 2, 3, 4], [1, 1, 0])
Expected Output: [3, 1, 4, 2]
Explanation: Use indices 1, 1, and 0 for ranges [0,3], [0,2], and [0,1]. The swaps produce [1,4,3,2], then [1,3,4,2], then [3,1,4,2].
Input: ([], [])
Expected Output: []
Explanation: An empty deck has only one permutation, so no swaps are performed.
Hints
- Think about filling the array from the end: which card should go into the last unshuffled position?
- After choosing a random index from the remaining prefix, a swap can place that chosen card without needing extra memory.