Given an array of size 3n of the form
[x1, x2, x3... xn, y1, y2, y3... yn, z1, z2, z3... zn]
Convert it to [x1, y1, z1, x2, y2, z2, ... xn, yn, zn]
Here xn, yn, zn can be any integers. See example input and output below.
Two constraints
- Do in O(n)
- O(1) memory (inplace)
An example input and output are as follows.
Input :
[5, 8, 11, 3, 2, 17, 21, 1, 9]
3n = 9. So n = 3.
Here
x1=5 x2=8 x3=11 y1=3 y2=2 y3=17 z1=21 z2=1 z3=9
Output :
[5, 3, 21, 8, 2, 1, 11, 17, 9]
One possible O(n log n) soln:
Considering just x's and y's. Now I can swap all y's to its position which will leave me x2, x4, x6 swapped out of position. Then I will swap in x2, x4's which will leave x3, x7's out of position. And next iteration would be x8, x16's. This would take me to O(n log n) but not O(n).
See Question&Answers more detail:
os