![]() |
VOOZH | about |
Given an arr[] of distinct integers. Rearrange the array in such a way that the first element is the largest and the second element is the smallest, the third element is the second largest and the fourth element is the second smallest, and so on.
Examples :
Input: arr[] = [7, 1, 2, 3, 4, 5, 6]
Output: [7, 1, 6, 2, 5, 3, 4]
Explanation: The first element is first maximum and second element is first minimum and so on.
Input: arr[] = [1, 6, 9, 4, 3, 7, 8, 2]
Output: [9, 1, 8, 2, 7, 3, 6, 4]
Explanation: The first element is first maximum and second element is first minimum and so on.
Table of Content
The idea is to find the maximum element, then the minimum, then the next maximum, and so on, by repeatedly scanning the array to find the next unvisited max or min using visited Array.
7 1 6 2 5 3 4
Time Complexity: O(n^2)
Space Complexity: O(n)
The idea is to first sort the array. After sorting, we initialize two pointers - one at the beginning and one at the end. In each step, we add the largest and smallest remaining elements alternately to the result by moving the right pointer leftward and the left pointer rightward.
Let us understand with an example:
Input: arr[] = [7, 1, 2, 3, 4, 5, 6]
After sorting -> [1, 2, 3, 4, 5, 6, 7]
Start: res = []
So, i = j = 3 -> pick 4 -> res = [7, 1, 6, 2, 5, 3, 4]
Then Stop, Output : 7 1 6 2 5 3 4
7 1 6 2 5 3 4
Time Complexity: O(n log n)
Space Complexity: O(n)