NeetCode #210LC-2149MediumTwo Pointers
← Back to All Problems#210 · #2149 · Rearrange Array Elements by Sign(按符号重排数组)
📌 Problem Statement & Constraints
Given an integer array
nums with an equal number of positive and negative integers, rearrange it so that positives occupy the even indices and negatives the odd indices, preserving their relative order. Constraints: 2 <= nums.length <= 2 * 10^5, nums.length is even, nums[i] != 0.💡 Core Algorithmic Approaches
- Two write pointers: one at index 0 for positives (advancing by 2) and one at index 1 for negatives.
- Scan the array in order, writing each value into its group's next slot.
- Because the scan is in order and the write pointers advance monotonically within each group, the relative order is preserved automatically.
- The result array is a fresh allocation, so the input is not modified.
💻 Benchmark Python3 Implementation
class Solution:
def rearrangeArray(self, nums: List[int]) -> List[int]:
res = [0] * len(nums)
pos, neg = 0, 1 # even slots for positives, odd for negatives
for x in nums:
if x > 0:
res[pos] = x
pos += 2
else:
res[neg] = x
neg += 2
return res⚡ Complexity Deep Dive
⏱️ Time Complexity
O(n): one pass.
💾 Space Complexity
O(n) for the result. In-place rearrangement with order preservation is not possible in a single pass, which is why the extra array is needed.
⚠️ Interview Pitfalls & Follow-ups
- Using a single write pointer with swaps: the relative order would be lost.
- Advancing by 1 instead of 2: the groups would collide.
- Assuming the counts differ: the constraints guarantee an equal number of positives and negatives, so no slot is left unfilled.
- Treating 0 as positive: the constraints exclude 0, but if it occurred it would need an explicit decision.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🧩 Related Two Pointers Problems
中文速览与面试要点
按符号重排数组
给你一个下标从 0 开始的整数数组 nums,数组长度为 偶数 n,由数目相等的正整数和负整数组成。你需要 重排 nums 中的元素,使修改后的数组满足下述条件:① 任意 连续 的两个整数 符号不同 ;② 对于符号相同的所有整数,保留它们在 nums 中的 相对顺序 。重排后数组以正整数开头。约束:2 ≤ nums.length ≤ 2 × 10^5;1 ≤ |nums[i]| ≤ 10^5;nums[i] != 0;nums.length 为偶数;nums 中正数与负数数目相等。
核心要点
- 分组后交错拼接(标准解) :分别收集正数与负数(保持原相对顺序),然后按「正、负、正、负…」交替拼接。
- 为什么这样满足条件 :交错排列使任意相邻两数符号必不同;分组收集保持了同号元素的相对顺序。
- 复杂度 :O(n) 时间、O(n) 空间。
- O(1) 空间的双指针写法 :用一个结果数组与两个「读取指针」——正数指针从下标 0 开始每隔一个写入、负数指针从下标 1 开始每隔一个写入。由于正负数量相等,下标不会冲突。
常见陷阱
- 以负数开头 :题目明确要求「重排后数组以正整数开头」。
- 交错时未保持相对顺序 :用集合或字典分组会丢失顺序,必须用列表按原序收集。
- 用排序(如 key=abs ) :会打乱同号元素的相对顺序,违反条件②。
- 担心正负数量不等 :题目保证相等,因此交错时不会有一方提前用尽。
参考实现
class Solution:
def rearrangeArray(self, nums: list[int]) -> list[int]:
pos = [x for x in nums if x > 0]
neg = [x for x in nums if x < 0]
res = []
for p, q in zip(pos, neg):
res.append(p) # 正数在前
res.append(q) # 负数在后
return res
# 单数组双指针写法(省去两个中间列表):
# res = [0] * len(nums)
# pi = ni = 0 # 分别指向 pos / neg 列表的读取位置(此处用两个指针遍历原数组)
# i = 0
# for x in nums:
# if x > 0:
# res[i] = x; i += 2
# for x in nums:
# if x < 0:
# res[i] = x; i += 2
# 注意:上面需要两次遍历,第二次从下标 1 开始