⚡Flashcard Drill➔
NeetCode #205LC-1968MediumTwo Pointers
← Back to All Problems

#205 · #1968 · Array With Elements Not Equal to Average of Neighbors(构造元素不等于两相邻元素平均值的数组)

📌 Problem Statement & Constraints

Given an array nums, rearrange it so that no element equals the average of its neighbours. Return any valid arrangement. Constraints: 3 <= nums.length <= 10^5, 0 <= nums[i] <= 10^5.

💡 Core Algorithmic Approaches

  1. Sort the array and interleave the smaller half with the larger half: place the small values at the even indices and the large values at the odd indices.
  2. Then for every middle position, the value is a large one bounded below by the adjacent small values, and the strict inequality holds.
  3. Specifically, with res[2k] <= res[2k+1] >= res[2k+2], the equality case (an element being the exact average of its neighbours) cannot occur because the sorted halves are separated.
  4. This is a constructive proof, which is why the problem accepts any valid arrangement.

💻 Benchmark Python3 Implementation

class Solution:
    def rearrangeArray(self, nums: List[int]) -> List[int]:
        nums.sort()
        n = len(nums)
        res = [0] * n
        mid = (n + 1) // 2             # size of the smaller half
        j = 0
        for i in range(0, n, 2):       # small values at even indices
            res[i] = nums[j]
            j += 1
        for i in range(1, n, 2):       # large values at odd indices
            res[i] = nums[j]
            j += 1
        return res

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(n log n): the sort dominates.
💾 Space Complexity
O(n) for the result.

⚠️ Interview Pitfalls & Follow-ups

  • Splitting the array evenly when n is odd: the smaller half has (n + 1) // 2 elements, and the interleaving depends on this split.
  • Placing large values at even indices: then the peak condition would be violated; small values must go at the even positions.
  • Trying to check all triples after a random shuffle: no guarantee of success, and the constructive approach is deterministic.
  • Forgetting that the arrangement only needs to be valid, not optimal: any valid permutation is accepted.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related Two Pointers Problems

中文速览与面试要点

构造元素不等于两相邻元素平均值的数组

给你一个下标从 0 开始的数组 nums,数组由若干 互不相同 的整数组成。请你重新排列 nums 中的元素,使其满足:对于每个下标 i(1 ≤ i ≤ nums.length − 2), nums[i − 1] + nums[i + 1] != 2 × nums[i] (即 nums[i] 不等于其相邻元素的平均值)。返回重新排列后的数组 nums。约束:3 ≤ nums.length ≤ 10^5;0 ≤ nums[i] ≤ 10^5;nums 中所有元素互不相同。

核心要点

  • 排序后大小交错(标准解) :把数组升序排序,然后按「小、大、次小、次大…」的顺序交错取元素。
  • 为什么交错取一定满足条件 :设交错后的序列为 a₀ &lt; b₀ &lt; a₁ &lt; b₁ &lt; … (a 来自前半、b 来自后半)。对任意 i, nums[i−1] 与 nums[i+1] 分别位于 nums[i] 的两侧(一大一小),因此它们的平均值要么大于 nums[i] 要么小于 nums[i] ,不可能恰好等于。
  • 更简单的等价写法 :把排序后的数组分成前半段与后半段,然后交替拼接: small[0], large[0], small[1], large[1], … 。
  • 复杂度 :排序 O(n log n),拼接 O(n)。

常见陷阱

  • 随机打乱 :无法保证条件成立(相邻三元组可能恰好构成等差数列)。必须用有序交错的方式。
  • 前半段长度取 n // 2 :n 为奇数时应取 (n+1)//2 ,保证 small 比 large 多一个,交错时不会提前用尽。
  • 用「每次取最小与最大」的贪心但不排序 :必须先排序才能保证「小 &lt; 大」的严格交错关系。
  • 误以为需要检查每个三元组并调整 :交错构造是 结构性保证 ,无需任何检查。

参考实现

class Solution:
    def rearrangeArray(self, nums: list[int]) -> list[int]:
        nums.sort()
        n = len(nums)
        half = (n + 1) // 2                 # 前半段长度(n 为奇数时多一个)
        small = nums[:half]
        large = nums[half:]
        res = []
        for i in range(half):
            res.append(small[i])
            if i < len(large):
                res.append(large[i])
        return res

# 双指针交错写法(等价):
# nums.sort()
# res = []
# l, r = 0, len(nums) - 1
# while l <= r:
#     res.append(nums[l]); l += 1
#     if l <= r:
#         res.append(nums[r]); r -= 1
# return res