"Sort Array By Parity" is a fundamental array manipulation problem that is often used as an introductory challenge in technical interviews. You are given an array of non-negative integers, and your task is to rearrange the elements such that all the even integers appear at the beginning of the array, followed by all the odd integers.
The relative order of the even numbers among themselves doesn't matter, and the same applies to the odd numbers. The goal is simply to partition the array based on parity (divisibility by 2) in the most efficient way possible, ideally in-place to save space.
Companies like Apple, Microsoft, and Meta ask this interview question to assess a candidate's basic understanding of array traversal and in-place modification. It’s a classic test of whether you can implement a simple partitioning logic without using extra space ( space complexity). It also serves as a precursor to more complex partitioning algorithms like the one used in Quick Sort.
The primary algorithmic pattern is the Two Pointers technique. You maintain two pointers: one starting at the beginning of the array (left) and one at the end (right).
left is even, move left forward.right is odd, move right backward.left is pointing to an odd number and right is pointing to an even number, swap them and then move both pointers.
This continues until the pointers meet, ensuring all evens are on the left and odds are on the right in time.Input: [3, 1, 2, 4]
left = 0 (val 3), right = 3 (val 4).left = 1 (val 1), right = 2 (val 2).left and right now point to the same area or cross.
Result: [4, 2, 1, 3].One common mistake is using an auxiliary array, which increases the space complexity to . While this works, it’s not the optimal solution interviewers are looking for. Another mistake is incorrect boundary conditions in the two-pointer loop, leading to infinite loops or out-of-bounds errors. Some candidates also overcomplicate the logic by trying to maintain the original relative order (stable sort), which is not required by this specific sort array by parity coding problem.
When you see a problem that asks to "group" or "partition" elements based on a property, your first thought should be Two Pointers. Practice this pattern on similar problems like "Move Zeroes" or "Remove Element." Being able to explain the trade-offs between an in-place space solution and a simpler space solution demonstrates strong engineering judgment.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Sort Array By Parity II | Easy | Solve | |
| Squares of a Sorted Array | Easy | Solve | |
| Minimum Average of Smallest and Largest Elements | Easy | Solve | |
| Merge Sorted Array | Easy | Solve | |
| 3Sum Closest | Medium | Solve |