VOOZH about

URL: https://www.geeksforgeeks.org/dsa/rearrange-array-maximum-minimum-form/

⇱ Rearrange an Array in Maximum Minimum - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Rearrange an Array in Maximum Minimum

Last Updated : 24 May, 2026

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]

Using Two Pointer Technique with Auxiliary Array - O(n log n) Time O(n) Space

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:


Output
6 1 5 2 4 3 

Time Complexity: O(n log n)
Auxiliary Space: O(n)

Using Modular Arithmetic - O(n log n) Time O(1) Space

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,

  • If i is even, then we need to place maximum remaining element, so update arr[i] = arr[i] + (arr[max_idx] % m) * m and decrement max_idx by 1. Now, arr[i] has arr[i] as well as arr[max_idx] as its value.
  • If i is odd, then we need to place minimum remaining element, so update arr[i] = arr[i] + (arr[min_idx] % m) * m and increment min_idx by 1. Now, arr[i] has arr[i] as well as arr[min_idx] as its value.
  • Finally, traverse the array again and divide every element by m to get the required rearranged elements.

Working of Approach:


Output
6 1 5 2 4 3 

Time Complexity: O(n log n)
Auxiliary Space: O(1)

Comment
Article Tags: