Rearrange array alternately max min in Python

Rearranges a sorted list so its elements alternate between the current maximum and current minimum using two pointers in O(n) time.

Easy Python 3.9+ Aug 9, 2026 Algorithms & data structures 14 views 0 copies

Python code

23 lines
Python 3.9+
def rearrange_alternately(arr):
    """
    Rearrange sorted array so elements alternate: max, min, next max, next min...
    Returns a new list in O(n) time using O(n) space.
    """
    n = len(arr)
    result = []
    left, right = 0, n - 1
    while left <= right:
        if left == right:
            result.append(arr[left])
            break
        result.append(arr[right])   # current max
        result.append(arr[left])    # current min
        left += 1
        right -= 1
    return result

if __name__ == "__main__":
    sorted_arr = [1, 2, 3, 4, 5, 6, 7]
    output = rearrange_alternately(sorted_arr)
    print(f"Input sorted array: {sorted_arr}")
    print(f"Rearranged (max, min alternating): {output}")

Output

stdout
Input sorted array: [1, 2, 3, 4, 5, 6, 7]
Rearranged (max, min alternating): [7, 1, 6, 2, 5, 3, 4]

How it works

The algorithm uses two pointers, left and right, starting at the ends of the sorted array. In each iteration, it appends the current maximum (right pointer) and then the current minimum (left pointer), moving inward. When both pointers meet (odd-length array), the middle element is appended once. This keeps time complexity O(n) and space complexity O(n) because a new list is built. The approach leverages the sorted order to pick extremes without additional sorting or comparisons.

Common mistakes

  • Forgetting to handle the middle element when the array length is odd, causing duplicates or missing values.
  • Modifying the input array in-place while iterating, leading to index errors.
  • Using naive sorting or repeated min/max calls which raise time complexity to O(n log n) or O(n^2).

Variations

  1. Modify the array in-place by storing values at computed indices after a single pass, reducing space to O(1).
  2. Use a deque and pop from both ends alternately for a simpler but less efficient approach.

Real-world use cases

  • Ordering items in a playlist or UI feed to maximize visual variety between high and low values.
  • Preprocessing sensor readings to alternate peak and trough values for signal analysis.
  • Balancing load distribution by alternating high- and low-priority tasks in a scheduler.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Algorithms & data structures

Related tutorials and quizzes for this topic.