NeetCode #188LC-905EasyTwo Pointers
← Back to All Problems#188 · #905 · Sort Array By Parity(按奇偶排序数组)
📌 Problem Statement & Constraints
Given an integer array
nums, move all even integers to the beginning followed by all odd integers, and return any array satisfying this. Constraints: 1 <= nums.length <= 5000, 0 <= nums[i] <= 5000.💡 Core Algorithmic Approaches
- The relative order within the even and odd groups is not constrained, which allows a simple two-pointer swap.
- Keep a write pointer
kfor the next even slot and scan withi. Whennums[i]is even, swap it into positionkand advancek. - Odd values naturally drift to the back as evens are swapped forward.
- A single pass suffices, and no sorting is needed.
💻 Benchmark Python3 Implementation
class Solution:
def sortArrayByParity(self, nums: List[int]) -> List[int]:
k = 0 # next slot for an even number
for i in range(len(nums)):
if nums[i] % 2 == 0:
nums[k], nums[i] = nums[i], nums[k]
k += 1
return nums⚡ Complexity Deep Dive
⏱️ Time Complexity
O(n): one pass.
💾 Space Complexity
O(1): in place.
⚠️ Interview Pitfalls & Follow-ups
- Sorting by parity with a comparator: O(n log n) and unnecessary, since the order within groups is unconstrained.
- Building two lists and concatenating: correct but O(n) extra space.
- Swapping when
nums[i]is odd: only even values should be moved to the front. - Using
nums[i] & 1 == 0: correct but% 2 == 0is clearer for readability.
⚡
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
中文速览与面试要点
按奇偶排序数组
给你一个整数数组 nums,将 nums 中的的所有偶数元素移动到数组的前面,后跟所有奇数元素。返回满足此条件的 任一 数组作为答案。约束:1 ≤ nums.length ≤ 5000;0 ≤ nums[i] ≤ 5000。
核心要点
- 相向双指针交换(标准解) :l 从左找奇数、r 从右找偶数,找到后交换。
- 为什么这样可行 :交换后左侧的奇数被换到右侧、右侧的偶数被换到左侧,逐步收敛。
- 不要求稳定 :题目只要求「偶数在前、奇数在后」,不要求保持原相对顺序,因此交换法足够。
- 替代方案 · 两趟写入 :第一趟写所有偶数、第二趟写所有奇数。同样 O(n),且是 稳定 的(保持偶/奇数各自的相对顺序)。
常见陷阱
- 交换后不重新检查当前 l 与 r :交换后 nums[l] 变成偶数、 nums[r] 变成奇数,但代码中两个 if 会在同轮内继续判断并推进指针,因此是正确的;若改成 if/elif 结构则可能漏推进。
- 要求稳定性 :题目不要求,但若面试官追问「如何保持相对顺序」,答案是两趟写入或额外数组。
- 用 nums.sort(key=lambda x: x % 2) :正确且稳定,但会创建额外空间(Timsort 需要 O(n) 临时空间),且未体现双指针技巧。
参考实现
class Solution:
def sortArrayByParity(self, nums: list[int]) -> list[int]:
l, r = 0, len(nums) - 1
while l < r:
if nums[l] % 2 == 1 and nums[r] % 2 == 0:
nums[l], nums[r] = nums[r], nums[l] # 左奇右偶 -> 交换
if nums[l] % 2 == 0:
l += 1
if nums[r] % 2 == 1:
r -= 1
return nums
# 稳定写法(保持各自相对顺序,需 O(n) 额外空间或两趟写入):
# res = [x for x in nums if x % 2 == 0] + [x for x in nums if x % 2 == 1]
# nums[:] = res