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.
Python code
23 linesdef 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
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
- Modify the array in-place by storing values at computed indices after a single pass, reducing space to O(1).
- 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
More from Algorithms & data structures
- Binary Search for Ship Capacity in Python medium
- Binary Search on Answer in Python: Koko Eating Bananas medium
- Bucket Numbers into Histogram Bin Counts in Python easy
- Container With Most Water: Two-Pointer Solution in Python medium
- Count Smaller Elements to the Right in Python easy
- Depth First Search Traversal Order in Python easy
Keep learning
Related tutorials and quizzes for this topic.