Skip to content

Commit e79c454

Browse files
authored
Merge pull request #1982 from agarwalhimanshugaya/dsa1
add question 384
2 parents a78a399 + 4fa32f0 commit e79c454

File tree

1 file changed

+139
-0
lines changed

1 file changed

+139
-0
lines changed
Lines changed: 139 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,139 @@
1+
---
2+
id: shuffle-an-array
3+
title: Shuffle-an-Array
4+
sidebar_label: 0384-Shuffle an Array
5+
tags:
6+
- Leet code
7+
description: "Solution to leetocde 384"
8+
---
9+
10+
### Problem Description
11+
12+
Given an integer array nums, design an algorithm to randomly shuffle the array. All permutations of the array should be equally likely as a result of the shuffling.
13+
14+
Implement the Solution class:
15+
16+
- `Solution(int[] nums)` Initializes the object with the integer array nums.
17+
- `int[] reset()` Resets the array to its original configuration and returns it.
18+
- `int[] shuffle()` Returns a random shuffling of the array.
19+
20+
Example 1:
21+
22+
```
23+
Input
24+
["Solution", "shuffle", "reset", "shuffle"]
25+
[[[1, 2, 3]], [], [], []]
26+
Output
27+
[null, [3, 1, 2], [1, 2, 3], [1, 3, 2]]
28+
29+
Explanation
30+
Solution solution = new Solution([1, 2, 3]);
31+
solution.shuffle(); // Shuffle the array [1,2,3] and return its result.
32+
// Any permutation of [1,2,3] must be equally likely to be returned.
33+
// Example: return [3, 1, 2]
34+
solution.reset(); // Resets the array back to its original configuration [1,2,3]. Return [1, 2, 3]
35+
solution.shuffle(); // Returns the random shuffling of array [1,2,3]. Example: return [1, 3, 2]
36+
```
37+
38+
### Constraints:
39+
40+
- `1 <= nums.length <= 50`
41+
- `-10^6 <= nums[i] <= 10^6`
42+
43+
### Motive
44+
45+
Our motive in this question is to find a random permutation of an array on demand. Now this random permutation should be trully random with a uniform probability distribution.
46+
In other words, for any call to shuffle(), all permutations of the array should have equal probability of being returned.
47+
48+
Let's try doing it by hand. We take the elements of the array in a bag and shuffle them, then for each position in the shuffled array, we draw one element from the bag, and put that element in that position, and so on, until the bag is empty.
49+
We can simulate this exact process in our code by maintaining a copy of the original array and generating a random index of the array to put at each index.
50+
51+
But the problem arises in the exclusion of the selected elements from the bag. We could do a normal array delete `(or shift)` and that would cost us `O(n)` in the worst case, making our time complexity $O(n^2)$, but we can do better.
52+
53+
54+
### Code Implementation
55+
56+
**Python:**
57+
58+
```python
59+
class Solution(object):
60+
def __init__(self, nums):
61+
self.reset = lambda: nums
62+
self.shuffle = lambda: random.sample(nums, len(nums))
63+
```
64+
65+
**C++:**
66+
67+
```c++
68+
class Solution {
69+
vector<int> original;
70+
int n;
71+
public:
72+
73+
Solution(vector<int>& nums) {
74+
original = nums;
75+
n = original.size();
76+
}
77+
78+
vector<int> reset() {
79+
return original;
80+
}
81+
82+
vector<int> shuffle() {
83+
//make a copy of the original
84+
vector<int> shuffled = original;
85+
86+
int leftSize = n;
87+
for(int i = n-1; i>=0; i--) {
88+
//draw from the bag
89+
int j = rand()%leftSize;
90+
91+
//put this element at current position
92+
//and put the original element in the bag
93+
swap(shuffled[i], shuffled[j]);
94+
leftSize--;
95+
}
96+
return shuffled;
97+
}
98+
99+
};
100+
```
101+
102+
**Java:**
103+
104+
```java
105+
import java.util.Random;
106+
107+
public class Solution {
108+
private int[] nums;
109+
private Random random;
110+
111+
public Solution(int[] nums) {
112+
this.nums = nums;
113+
random = new Random();
114+
}
115+
116+
/** Resets the array to its original configuration and return it. */
117+
public int[] reset() {
118+
return nums;
119+
}
120+
121+
/** Returns a random shuffling of the array. */
122+
public int[] shuffle() {
123+
if(nums == null) return null;
124+
int[] a = nums.clone();
125+
for(int j = 1; j < a.length; j++) {
126+
int i = random.nextInt(j + 1);
127+
swap(a, i, j);
128+
}
129+
return a;
130+
}
131+
132+
private void swap(int[] a, int i, int j) {
133+
int t = a[i];
134+
a[i] = a[j];
135+
a[j] = t;
136+
}
137+
}
138+
```
139+

0 commit comments

Comments
 (0)