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

Problems related to Sort Array By Parity

Other problems that use the same In-place Array Modification and Two Pointers techniques:

Preparing your workspace

Progress is saved as you study.