Array With Elements Not Equal to Average of Neighbors - 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.
Input & Output
Example 1 — Basic Case
$
Input:
nums = [4,1,3,2]
›
Output:
[1,4,2,3]
💡 Note:
Rearranged so that (1+2)/2 = 1.5 ≠ 4, and (4+3)/2 = 3.5 ≠ 2. No element equals the average of its neighbors.
Example 2 — Three Elements
$
Input:
nums = [1,2,3]
›
Output:
[1,3,2]
💡 Note:
Original [1,2,3] fails because (1+3)/2 = 2. Rearranged [1,3,2] works because (1+2)/2 = 1.5 ≠ 3.
Example 3 — Larger Array
$
Input:
nums = [1,2,3,4,5]
›
Output:
[1,3,2,5,4]
💡 Note:
Creates zigzag pattern where no middle element equals average of neighbors: 1<3>2<5>4
Constraints
- 3 ≤ nums.length ≤ 105
- -105 ≤ nums[i] ≤ 105
- All the elements of nums are unique
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array with elements that may equal neighbor averages
2
Process
Rearrange into zigzag pattern (peaks and valleys)
3
Output
No element equals average of its neighbors
Key Takeaway
🎯 Key Insight: A zigzag pattern naturally prevents average conflicts between neighbors
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code