easy +10 pts

Sort array by parity

Reorder an array so all even integers come before odd integers, preserving relative order.

Write a function `sort_by_parity(nums)` that takes a list of integers `nums` and returns a new list where all even numbers appear before all odd numbers, while maintaining the relative order of even numbers among themselves and odd numbers among themselves. The input list should not be modified.

Constraints

0 <= len(nums) <= 10^4; -10^6 <= nums[i] <= 10^6. Your solution should run in O(n) time and O(n) space. The function must return a new list.

Example

>>> sort_by_parity([3,1,2,4])
[2,4,3,1]
>>> sort_by_parity([0,1,2])
[0,2,1]
>>> sort_by_parity([])
[]
10 points ~15 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Think about creating two separate lists: one for even numbers and one for odd numbers.
Iterate through the input list once and append each element to the appropriate list.
Concatenate the two lists at the end.
Remember not to modify the input list.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.