Sort Array By Parity

EasyTwo Pointerstwo pointers

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

Given an integer array nums, rearrange it so that every even number comes before every odd number. Many arrangements satisfy that, so the output is pinned: return a new array containing all the even numbers **in their original relative order**, followed by all the odd numbers **in their original relative order** (a stable partition). An O(n) time solution is expected.

Examples

Input: nums = [3,1,2,4]
Output: [2,4,3,1]
Evens 2, 4 keep their order, then odds 3, 1 keep theirs.
Input: nums = [0]
Output: [0]
0 is even; a single element is already partitioned.

Constraints

  • 1 <= nums.length <= 5000
  • 0 <= nums[i] <= 5000
  • Relative order within the even group and within the odd group must be preserved.

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More two pointers problems