LeetCode 384: Shuffle an Array Solution
Master LeetCode problem 384 (Shuffle an Array), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
384. Shuffle an Array
Problem Explanation
Explanation
To shuffle an array such that all permutations are equally likely, we can use the Fisher-Yates algorithm. The idea is to iterate over the array from the end to the beginning, and at each iteration, swap the current element with a randomly selected element from the remaining elements.
- For the
shufflemethod, we create a copy of the original array and apply the Fisher-Yates shuffle algorithm to shuffle the elements. - For the
resetmethod, we return a copy of the original array to reset it back to its initial configuration.
Time Complexity:
shuffle: O(n)reset: O(n)
Space Complexity: O(n), where n is the number of elements in the input array.
Solution Code
import java.util.Arrays;
import java.util.Random;
class Solution {
private int[] original;
private int[] shuffled;
private Random rand;
public Solution(int[] nums) {
original = nums.clone();
shuffled = nums.clone();
rand = new Random();
}
public int[] reset() {
return original;
}
public int[] shuffle() {
for (int i = shuffled.length - 1; i > 0; i--) {
int j = rand.nextInt(i + 1);
swap(shuffled, i, j);
}
return shuffled;
}
private void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 384 (Shuffle an Array)?
This page provides optimized solutions for LeetCode problem 384 (Shuffle an Array) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 384 (Shuffle an Array)?
The time complexity for LeetCode 384 (Shuffle an Array) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 384 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 384 in Java, C++, or Python.