![]() |
VOOZH | about |
Given an array arr[] of positive integers. The task is to rearrange the array elements alternatively i.e. first element should be the max value, the second should be the min value, the third should be the second max, the fourth should be the second min, and so on.
Examples:
Input: arr[] = [1, 2, 3, 4, 5, 6]
Output: [6, 1, 5, 2, 4, 3]
Explanation: Max element = 6, min = 1, second max = 5, second min = 2, and so on...
The modified array is: [6, 1, 5, 2, 4, 3]
Input: arr[]= [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110]
Output: [110, 10, 100, 20, 90, 30, 80, 40, 70, 50, 60]
Explanation: Max element = 110, min = 10, second max = 100, second min = 20, and so on...
The Modified array is : [110, 10, 100, 20, 90, 30, 80, 40, 70, 50, 60]
Table of Content
The idea is to use an auxiliary array. We maintain two pointers one to the leftmost or smallest element and the other to the rightmost or largest element. We move both pointers toward each other and alternatively copy elements at these pointers to an auxiliary array. Finally, we copy the auxiliary array back to the original array.
Working of Approach:
6 1 5 2 4 3
Time Complexity: O(n log n)
Auxiliary Space: O(n)
The idea is to use multiplication and modular arithmetic to store two elements at each index. Assume m = maximum element in the array + 1. Now, if we want to store two numbers say x and y at any index, then we can store x + (y * m) at that index. This will work because using x + (y * m), we can get the first value by using modulo: (x + (y * m)) mod m = x and the second value by using (x + (y * m)) / m = y.
To arrange the elements alternately, we can maintain two pointers min_idx = 0 to keep track of the next minimum element and max_idx = n - 1 to keep track of the next maximum element. Now, iterate from i = 0 to n - 1,
Working of Approach:
6 1 5 2 4 3
Time Complexity: O(n log n)
Auxiliary Space: O(1)