Array With Elements Not Equal to Average of Neighbors - Problem

You're given an array of distinct integers and need to rearrange them strategically! ๐ŸŽฏ

The challenge: Create a new arrangement where no element equals the average of its neighbors. For any element at position i (where 1 โ‰ค i < array.length - 1), it should satisfy:

nums[i] โ‰  (nums[i-1] + nums[i+1]) / 2

In other words, avoid creating arithmetic sequences of length 3! For example, if you have [2, 4, 6], the middle element 4 equals (2 + 6) / 2 = 4, which violates our rule.

Your task: Return any valid rearrangement that satisfies this constraint. Multiple correct answers exist!

Input & Output

example_1.py โ€” Basic Case
$ Input: [1,2,3,4,5]
โ€บ Output: [1,5,2,4,3]
๐Ÿ’ก Note: After sorting and using two pointers: alternately pick from ends. Check: 5โ‰ (1+2)/2=1.5, 2โ‰ (5+4)/2=4.5, 4โ‰ (2+3)/2=2.5 โœ“
example_2.py โ€” Small Array
$ Input: [6,2,0,9,7]
โ€บ Output: [0,9,2,7,6]
๐Ÿ’ก Note: Sorted: [0,2,6,7,9]. Alternating picks create [0,9,2,7,6]. Verify: 9โ‰ (0+2)/2=1, 2โ‰ (9+7)/2=8, 7โ‰ (2+6)/2=4 โœ“
example_3.py โ€” Edge Case
$ Input: [1,2,3]
โ€บ Output: [1,3,2]
๐Ÿ’ก Note: Original [1,2,3] has 2=(1+3)/2. After rearranging to [1,3,2]: check 3โ‰ (1+2)/2=1.5 โœ“. Problem solved!

Constraints

  • 3 โ‰ค nums.length โ‰ค 105
  • -105 โ‰ค nums[i] โ‰ค 105
  • All integers in nums are distinct
  • It is guaranteed that a valid arrangement exists

Visualization

Tap to expand
Wiggle Pattern: Creating Peaks and ValleysStep 1: Sort ArraySorted: [1, 3, 4, 6, 9]Step 2: Two Pointers Setup1LEFT3469RIGHTStep 3: Alternate Selection11st92nd33rd64th45thResult: Wiggle Pattern[1, 9, 3, 6, 4]Verification9 โ‰  (1 + 3) รท 2 = 2 โœ“3 โ‰  (9 + 6) รท 2 = 7.5 โœ“6 โ‰  (3 + 4) รท 2 = 3.5 โœ“๐ŸŽฏ All ConstraintsSatisfied!
Understanding the Visualization
1
Sort by Height
Arrange people from shortest to tallest: [1,3,4,6,9]
2
Create Peaks and Valleys
Alternate between shortest and tallest: pick 1, then 9, then 3, then 6, then 4
3
Final Arrangement
Result: [1,9,3,6,4] - no one is average height of neighbors!
Key Takeaway
๐ŸŽฏ Key Insight: By alternating between extreme values (smallest and largest), we maximize the differences between adjacent elements, making it impossible for any middle element to equal the average of its neighbors!
Asked in
Google 42 Meta 35 Amazon 28 Microsoft 22
52.3K Views
Medium Frequency
~15 min Avg. Time
1.8K 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