VOOZH about

URL: https://www.geeksforgeeks.org/dsa/shuffle-2n-integers-a1-b1-a2-b2-a3-b3-bn-without-using-extra-space/

⇱ Shuffle 2n integers as a1-b1-a2-b2-a3-b3-..bn without using extra space - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Shuffle 2n integers as a1-b1-a2-b2-a3-b3-..bn without using extra space

Last Updated : 16 Mar, 2023

We have an array of the form {a0, a1, a2....., an, b0, b1, b2, .....bn} and our task is to rearrange the same in theform given below by using O(1) space- 
{a0, b0, a1, b1, a2, b2...........an, bn} 

Examples: 

Input : arr[] = {1, 3, 5, 7, 2, 4, 6, 8}
Output : {1, 2, 3, 4, 5, 6, 7, 8}

Input : arr[] = {11, 13, 15, 12, 14, 16}
Output : {11, 12, 13, 14, 15, 16}

We have already discussed two approaches-  

As we can see we have to transform the array so there must be an even size array.To rearrange the array we will start from the middle of the array and each time we will shift 1 element of the second half to left at it's desired position. This algorithm will take O(n^2).

Algorithm-  

1- Take the input array
2- If size is null or odd return
3- find the middle index of the array
4- While (midindex>0)
 set count = midindex and 
 swapindex = midindex
 while (count-->0){
 swap(swapindex+1, swapindedx)
 swapindex++
 }
 midindex--
5- End


Working- 

array- 1 3 5 7 2 4 6 8
1st Loop- 1 2 3 5 7 4 6 8
2nd Loop- 1 2 3 4 5 7 6 8
3rd loop- 1 2 3 4 5 6 7 8

Output: 

1 2 3 4 5 6


Time Complexity: O(N2)
Auxiliary Space: O(1)

Efficient Approach:

Note: The assumption is that the largest value  in the array is INT_MAX/2 and consists of only positive integers

The algorithm utilizes bit manipulation techniques to rearrange an array [x1,x2,...,xn,y1,y2,...,yn]. 

It is based on the constraint that 1 <= nums[i] <= INT_MAX/2. 

  1. The largest number in the array is 1000 which requires 10 bits in binary representation. 
  2. Thus, two numbers can fit into a 32-bit binary representation without overwriting each other. 
  3. The algorithm has two loops: the first loop groups the numbers into pairs [x1, y1], [x2, y2]... [xn,yn] and stores both numbers in one binary representation.
  4.  The second loop places these pairs in their final positions. To get the two numbers out of the binary representation, the algorithm uses Bitwise AND and Right Shift.

Implementation:

The algorithm has two parts, loop 1 and loop 2. 

  1. Loop 1 groups the numbers in the array into pairs [x1, y1], [x2, y2]... [xn,yn] by storing both xn and yn in one binary representation. 
  2. Loop 2 then places these pairs in their final position in the array. 

To store two numbers in one binary representation, two pointers i and j are used.

 i starts from n and moves backwards to 0, while j starts from the end of the array and moves backwards to n.

Code:


Output
 1 2 3 4 5 6

Complexity Analysis

  • Time Complexity: O(N)
  • Auxiliary Space: O(1)
Comment
Article Tags:
Article Tags: