LeetCode 1968, Medium. Topics: Array, Greedy, Sorting. View on LeetCode.
Generate this problem as a practice environment: tested reference solution, 16 parametrized pytest cases, and a playground notebook:
Problem
You are given a 0-indexed array nums of distinct integers. You want to rearrange the elements in the array such that every element in the rearranged array is not equal to the average of its neighbors.
More formally, the rearranged array should have the property such that for every i in the range 1 <= i < nums.length - 1, (nums[i-1] + nums[i+1]) / 2 is not equal to nums[i].
Return any rearrangement of nums that meets the requirements.
Examples
Constraints
3 <= nums.length <= 10^5
0 <= nums[i] <= 10^5
- All elements of
nums are distinct.
Solution
Reference implementation from solution.py on GitHub, full suite in test_solution.py:
Complexity
NeetCode All. Last modified on September 7, 2026