Sort Array By Parity — LeetCode 905 Python Solution
- Problem
- #905
- Pattern
- Two Pointers
- Reading time
- 2 min
- Source
- leetcode.com
The problem
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
- 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.
Python solution
class Solution:
def sortArrayByParity(self, nums: List[int]) -> List[int]:
i, j = 0, len(nums) - 1
while i < j:
if nums[i] % 2 == 0:
i += 1
elif nums[j] % 2 == 1:
j -= 1
else:
nums[i], nums[j] = nums[j], nums[i]
i, j = i + 1, j - 1
return numsComplexity
| Measure | Complexity |
|---|---|
| Time | O(n), where n is the length of the array nums |
| Space | O(1) auxiliary |
Pattern: Two Pointers
Use the order already in the input to discard half the search space at every step. LeetCode 905. Sort Array By Parity is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Two Pointers.
The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 905. Sort Array By Parity?
- LeetCode 905. Sort Array By Parity is rated Easy on LeetCode.
- What is the time complexity of LeetCode 905. Sort Array By Parity?
- The Python solution on this page runs in O(n), where n is the length of the array nums.
- What is the space complexity of LeetCode 905. Sort Array By Parity?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 905. Sort Array By Parity cover?
- LeetCode 905. Sort Array By Parity is tagged Array, Two Pointers and Sorting on LeetCode.