↓Skip to main content
  1. LeetCode/

LeetCode 922: Sort Array By Parity II

·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: Runtime Error ×10 → Output Limit Exceeded → Accepted ×3 → Runtime Error → Accepted ×2

Approach
#

i visits only even slots and j only odd slots, both stepping by two (Two Pointers Template 2). When nums[i] is odd it is misplaced; advance j to an odd slot holding an even number (also misplaced) and swap. Half the numbers are even, so one always exists.

My Attempts
#

This took 17 submissions, the first ten all REs: the pointers’ bounds were off and ran past the end, e.g. j overran on [9, 8] (IndexError); one version left a debug print and hit Output Limit Exceeded.

Solution
#

class Solution:
    def sortArrayByParityII(self, nums: List[int]) -> List[int]:
        j = 1
        for i in range(0, len(nums), 2):
            if nums[i] % 2:                              # 偶數位置放了奇數
                while nums[j] % 2:
                    j += 2
                nums[i], nums[j] = nums[j], nums[i]
        return nums

Complexity
#

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

Mistakes to Avoid
#

  • Both pointers step by two.
  • j never resets; earlier odd slots are already correct.

Interview Explanation
#

i walks even slots and j odd slots; when i finds an odd number, j advances to a misplaced even and they swap. Each pointer only moves forward, O(n).

Related

LeetCode 905: Sort Array By Parity
·1 min
LeetCode Easy Array Two-Pointers Sorting
LeetCode 905 note: a write pointer swaps even numbers to the front, just like move zeroes
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