Sort Array By Parity
Sort Array By Parity is a Easy Data Structures and Algorithms interview problem you can solve, run and submit on Thita.ai. It belongs to the Two Pointers pattern, in the In-place Array Modification subpattern.
Problem statement
Given an integer array nums, move all the even integers at the beginning of the array followed by all the odd integers.
Return any array that satisfies this condition.
Example 1:
Input: nums = [3,1,2,4] Output: [2,4,3,1] Explanation: The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted.
Example 2:
Input: nums = [0] Output: [0]
Constraints:
- 1 <= nums.length <= 5000
- 0 <= nums[i] <= 5000
Topics and companies
Topics: Array, Two Pointers, Sorting.
Reported in interviews at Capital One, VMware.
How to practise Sort Array By Parity on Thita.ai
Starter code is provided in C, C#, C++, Go, Java, JavaScript and Python. Your solution runs against 5 test cases for this problem, with the AI coach available for a hint when you are stuck rather than a finished answer. The reference solution runs in O(n) time and O(1) space.
Open Sort Array By Parity in the code editor, or read the Sort Array By Parity editorial for a worked solution with its approach and complexity analysis.
Where Sort Array By Parity sits in the DSA pattern sheet
- Two Pointers pattern guide
- In-place Array Modification subpattern
- The full DSA patterns sheet
- All coding practice problems
Problems related to Sort Array By Parity
Other problems that use the same In-place Array Modification and Two Pointers techniques:
- Intersection of Two Arrays — Easy, same subpattern
- Move Pieces to Obtain a String — Medium, same subpattern
- Move Zeroes — Easy, same subpattern
- Remove Duplicates from Sorted Array — Easy, same subpattern
- Remove Duplicates from Sorted Array II — Medium, same subpattern
- Remove Element — Easy, same subpattern
Preparing your workspace
Progress is saved as you study.