384. Shuffle an Array

brute force

https://www.geeksforgeeks.org/shuffle-a-given-array-using-fisher-yates-shuffle-algorithm/

A simple solution is to create an auxiliary array temp[] which is initially a copy of arr[].

Randomly select an element from temp[], copy the randomly selected element to arr[0] and remove the selected element from temp[].

Repeat the same process n times and keep copying elements to arr[1], arr[2], … . The time complexity of this solution will be O(n^2).

T: O(n^2)

public int[] shuffle() {
    List<Integer> aux = getArrayCopy();

    for (int i = 0; i < array.length; i++) { // O(n)
        int removeIdx = rand.nextInt(aux.size());
        array[i] = aux.get(removeIdx);
        aux.remove(removeIdx); // this is also O(n)
    }

    return array;
}

use fisher yates shuffle algorithm

refer:

T:O(n)

S:O(n)

latest explain

ex:

so you can see the index and rand index maybe the same, means don't move

Last updated

Was this helpful?