FastPrepShuffle a Deck From Random Choices

Shuffle a Deck From Random Choices

Google logoGoogle● EasyNEW GRADPHONE SCREEN
Learn

Problem statement

Implement the Fisher-Yates shuffle for an integer array deck. To make the randomized process deterministic for testing, the input also contains picks.

Process i from deck.length - 1 down to 1. At that step, use the next value j from picks, where 0 <= j <= i, and swap deck[i] with deck[j]. Return the shuffled deck.

In a real randomized implementation, each pick is produced independently by random.randint(0, i) or an equivalent inclusive random-integer API.

Function

shuffleDeck(deck: int[], picks: int[]) → int[]

Examples

Example 1

deck = [1,2,3,4]picks = [1,0,1]return = [3,4,1,2]

Swap positions (3,1), then (2,0), then (1,1).

Example 2

deck = [1,2,3]picks = [2,1]return = [1,2,3]

Both choices select the current index, so no values move.

Example 3

deck = [1,2,3]picks = [0,0]return = [2,3,1]

The last item moves to the front, then the remaining prefix is shuffled.

Constraints

  • 1 <= deck.length <= 200000.
  • picks.length = deck.length - 1.
  • For pick index t, 0 <= picks[t] <= deck.length - 1 - t.

More Google problems

See Google hiring insights
public int[] shuffleDeck(int[] deck, int[] picks) {
    // Write your code here.
}
deck[1,2,3,4]
picks[1,0,1]
expected[3,4,1,2]
Checking account…