1470. Shuffle the Array
Today, we’ll be looking at the following problem:
1470. Shuffle the Array
Shuffle the Array - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared…
You’re given an array called nums that is composed of 2n elements in the following format:
Your job is to return the array in the following format:
If this is still unclear, you can refer to the examples that the problem provides you with. For instance, the problem provides you 1 example with an input array nums and an integer called n:
Input: nums = [2,5,1,3,4,7], n = 3
The resulting output should appear as follows with the example above:
This is because the 2 matches with the 4 since 2 is x1 and 4 is y1. Likewise, the 3 matches with the 1 because 3 is x2 and 1 is y2, and finally, the 5 matches with the 7 because 5 is x3 and 7 is y3.
The significance behind n is simply that 2n represents the total number of elements in the nums array due to n being the length of either the x or y range of numbers, or in other words, you can interpret it as n representing half of the number of elements in the nums array.
The approach for this problem can be fairly straightforward. You could first instantiate an empty array that we will eventually return as the final output array (in my case, I named it res).
res = 
Then, I can use a for-loop that will iterate n times and in each iteration, I can first append a number from the x range followed by appending a number from the y range. For instance, in the example above, in the first iteration, I would initially append 2 because 2 is the first number of the x range or x1 and then I would append 3 because 3 is the first number of the y range or y1. We should repeat this process n times. By the end of the for-loop, we should have our res array populated with all 2n elements from both the x & y range or the input nums array reordered.
for i in range(n):
res.append(nums[i + n])
Thank you for reading!
In case if you haven’t yet joined my Discord server where I host daily sessions on data structures & algorithms for free, please join via the link shared below.
If you have any questions or comments, please don’t be afraid to connect with me on any of the platforms below or feel free to send me an email at email@example.com