#905
Sort Array By Parity
EasyArrayTwo PointersSortingTwo PointersArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal solution uses a two-pointer technique to rearrange the numbers in a single pass, which is more efficient. One pointer will track the position to place even numbers, while the other will iterate through the array.
⚙️
Algorithm
5 steps- 1Step 1: Initialize a pointer 'evenIndex' at the start of the array.
- 2Step 2: Iterate through the array with a second pointer 'i'.
- 3Step 3: If the current number is even, swap it with the number at 'evenIndex' and increment 'evenIndex'.
- 4Step 4: Continue until the end of the array.
- 5Step 5: Return the modified array.
solution.py10 lines
1# Full working Python code
2
3def sortArrayByParity(nums):
4 evenIndex = 0
5 for i in range(len(nums)):
6 if nums[i] % 2 == 0:
7 nums[i], nums[evenIndex] = nums[evenIndex], nums[i]
8 evenIndex += 1
9 return nums
10ℹ
Complexity note: The time complexity is O(n) because we only traverse the array once. The space complexity is O(1) since we are rearranging the elements in place without using additional space.
- 1Using a two-pointer technique can significantly reduce the time complexity.
- 2In-place modifications help save space and improve efficiency.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.