Category : Easy

**Problem**

Given the array `nums`

consisting of `2n`

elements in the form `[x`

._{1},x_{2},...,x_{n},y_{1},y_{2},...,y_{n}]

Return the array in the form `[x`

._{1},y_{1},x_{2},y_{2},...,x_{n},y_{n}]

https://leetcode.com/problems/shuffle-the-array/

**Examples**

**Example 1:**

1 2 3 4 | Input: nums = [2,5,1,3,4,7], n = 3 Output: [2,3,5,4,1,7] Explanation: Since x1=2, x2=5, x3=1, y1=3, y2=4, y3=7 then the answer is [2,3,5,4,1,7]. |

**Example 2:**

1 2 | Input: nums = [1,2,3,4,4,3,2,1], n = 4 Output: [1,4,2,3,3,2,4,1] |

**Example 3:**

1 2 | Input: nums = [1,1,2,2], n = 2 Output: [1,2,1,2] |

**Constraints:**

`1 <= n <= 500`

`nums.length == 2n`

`1 <= nums[i] <= 10^3`

**Solution Approach**

The solution is pretty straight forward you just need to find the rule which will satisfy the condition given in the problem. We will create an empty array of 2*n size.

Now coming to finding the rule or the pattern in the question we need to look at the example. If we consider the indexes of suppose n=3 then the array order should change from [0,1,2,3,4,5] to [0,3,1,4,2,5] according to the question. We can clearly see that the positions if it is divisible by 2 then at the new array’s index, will have an element which was previously at that index divided by 2 in the old array. From the above example, we can apply this technique as the zeroth index of new array will contain 0/2= 0, the second index will contain 2/2=1 and finally, the fourth index will contain 4/2=2 in the new array. So our array now looks like this [0, _, 1, _, 2, _ ]

For the next part its clear that every odd index in the final array will have the element at index n+(i/2) from the old array i.e. at index 1 we will have element at 3+(1/2) = 3rd index, at index 3 we will have element at 3+(3/2) = 4th index and finally at index 5 we will have 3+(5/2) = 5th indexed element from the old array.

Hence our new array will be [0,3,1,4,2,5] which can be returned as the answer.

**Solution code**

1 2 3 4 5 6 7 8 9 10 11 12 | class Solution { public int[] shuffle(int[] nums, int n) { int[] answerArray = new int[2*n]; for (int i =0; i<2*n; i++){ if(i%2==0) answerArray[i] = nums[i/2]; else answerArray[i] = nums[n+i/2]; } return answerArray; } } |

For more Leetcode explained solutions visit Leetcode Solutions. If you like capture the flag challenges visit here.

Check out my socials below in the footer. Feel free to ask any doubts in the comment section or contact me via Contact page I will surely respond. Happy Leetcoding 🙂