Leetcode Shuffle the Array | O(1) space

preview_player
Показать описание
Leetcode 1470. Shuffle the Array. O(1) space & O(n) time complexity solution.
Google interview question. Level: Medium - Hard

_______________________________________________________________________________________

Рекомендации по теме
Комментарии
Автор

unique approach, i can see on your screen that you practice codechef and codeforces...that's why you are able to think of such a unique solution...thankyou bhaiya....

anshulgupta
Автор

At first I didn't understand but when I take pen and paper and solve it, I feel like easyy peasyy.
Thank you for this solution.

PremSingh-otvk
Автор

great approach with great explanation 👏

arpitkhanulia
Автор

store new number in second half and then retrieve all the number from there itself.
Logic : myNumber = (1024 *x) + y
x = myNumber/1024;
y = nyNumber%1024;

int len = nums.length;
// to store the pair of numbers in right half of the original array
for(int i = n; i < len; i++) {
nums[i] = (nums[i] * 1024) + nums[i - n];
}

int index = 0;
// to retrive values from the pair of numbers and placing those retrieved value at their desired position
for(int i = n; i < len; i++, index += 2) {
nums[index] = nums[i] % 1024;
nums[index + 1] = nums[i] / 1024;
}

return nums;

MohdDanish-kvry
Автор

class Solution { public: vector<int> shuffle(vector<int>& nums, int n) { vector<int>ans1; for(int i=0;i<n;i++){ ans1.push_back(nums[i]); ans1.push_back(nums[i+n]); } return ans1; } };

Misaki
Автор

can anyone tell me how the function shuffle is working when i =0

lostsky
Автор

How it is O(N) time complexity? I could see while inside for loop

dineshkinibailoor
Автор

how is this O(1) space? you're still using the same O(N) space only right? or am i missing something?

soubhikmullick
Автор

My approach | Java Code
```
class Solution {
public int[] shuffle(int[] nums, int n) {
int[] newArr = new int[nums.length];
int j = 0;
for(int i = 0; i<n; i++){
newArr[j] = nums[i];
newArr[j+1] = nums[i+n];
j = j+2;
}
return newArr;
}
}
```

me-ooh-no
Автор

worst aproach I have wasted my whole day doing with it .. failing a lot of test cases .. wont work for 8 length arrays

pcdrive-xdgs