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
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!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code