#905

Sort Array By Parity

Easy
ArrayTwo PointersSortingTwo PointersArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal 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
  1. 1Step 1: Initialize a pointer 'evenIndex' at the start of the array.
  2. 2Step 2: Iterate through the array with a second pointer 'i'.
  3. 3Step 3: If the current number is even, swap it with the number at 'evenIndex' and increment 'evenIndex'.
  4. 4Step 4: Continue until the end of the array.
  5. 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.