↓Skip to main content
  1. LeetCode/

LeetCode 905: Sort Array By Parity

·1 min· ·
LeetCode Easy Array Two-Pointers Sorting
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-09-25

  • Submissions: Wrong Answer → Accepted ×2 → Runtime Error → Accepted ×3

Approach
#

The same as LC 283 (Two Pointers Template 5): left is where the next even number goes, swapping each even number forward.

My Attempts
#

Attempt 1 did not return the array; attempt 2 used an undefined variable.

Solution
#

class Solution:
    def sortArrayByParity(self, nums: List[int]) -> List[int]:
        left = 0
        for right in range(len(nums)):
            if nums[right] % 2 == 0:
                nums[left], nums[right] = nums[right], nums[left]
                left += 1
        return nums

Complexity
#

Time O(n), space O(1).

Mistakes to Avoid
#

  • This problem returns the array.

Interview Explanation
#

A write pointer swaps evens to the front in order, leaving odds behind. Time O(n), space O(1).

Related

LeetCode 922: Sort Array By Parity II
·1 min
LeetCode Easy Array Two-Pointers Sorting
LeetCode 922 note: pointers i over even slots and j over odd slots, each stepping by two; when slot i holds an odd number, move j to a misplaced even and swap
LeetCode 455: Assign Cookies
·2 mins
LeetCode Easy Array Two-Pointers Greedy Sorting
LeetCode 455 note: sort children and cookies, satisfying the least greedy child with the smallest cookie that suffices; each pointer walks once
LeetCode 888: Fair Candy Swap
·2 mins
LeetCode Easy Array Hash-Table Binary-Search Sorting
LeetCode 888 note: equal sums after swapping x and y means y = x + (sumB - sumA) / 2; put B in a set and check each x from A
LeetCode 821: Shortest Distance to a Character
·2 mins
LeetCode Easy Array Two-Pointers String
LeetCode 821 note: one left-to-right pass for the distance to the nearest c on the left, then a right-to-left pass taking the minimum
LeetCode 832: Flipping an Image
·2 mins
LeetCode Easy Array Two-Pointers Bit-Manipulation Matrix
LeetCode 832 note: reverse each row and invert its bits, which two pointers can do at once
LeetCode 747: Largest Number At Least Twice of Others
·2 mins
LeetCode Easy Array Sorting
LeetCode 747 note: find the largest and second largest in one pass and return the largest’s index if it is at least twice the second; multiply to avoid dividing by zero