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
Array With Elements Not Equal to Average of Neighbors INPUT Original Array nums[] 4 i=0 1 i=1 3 i=2 2 i=3 Constraint: nums[i] != (nums[i-1]+nums[i+1])/2 Example of BAD arrangement: 1 2 3 4 (1+3)/2 = 2 = nums[1] (2+4)/2 = 3 = nums[2] INVALID! ALGORITHM STEPS Greedy Wiggle Sort 1 Sort the Array [4,1,3,2] --> [1,2,3,4] 2 Create Wiggle Pattern Swap pairs at odd indices 3 Swap i=1: nums[0],nums[1] [1,2,3,4] --> [2,1,3,4] 4 Swap i=3: nums[2],nums[3] [2,1,3,4] --> [2,1,4,3] Wiggle Pattern Visualization: 1 2 3 4 swap swap 2 1 4 3 FINAL RESULT Rearranged Array 1 i=0 4 i=1 2 i=2 3 i=3 Verification: i=1: (1+2)/2 = 1.5 1.5 != 4 OK i=2: (4+3)/2 = 3.5 3.5 != 2 OK Output: [1, 4, 2, 3] Key Insight: After sorting, swapping adjacent pairs at odd indices creates a "wiggle" pattern where each element is either a local maximum or minimum. This guarantees no element equals the average of its neighbors because neighbors are always on opposite sides (both larger or both smaller). TutorialsPoint - Array With Elements Not Equal to Average of Neighbors | Greedy Wiggle Sort
Asked in
Google 15 Facebook 12 Amazon 8
12.3K Views
Medium Frequency
~15 min Avg. Time
456 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen