Skip to content

Sort Array by Parity

Raymond Chen edited this page Aug 2, 2024 · 4 revisions

TIP102 Unit 1 Session 2 Advanced (Click for link to problem statements)

Problem Highlights

  • 💡 Difficulty: Easy
  • Time to complete: 10 mins
  • 🛠️ Topics: Arrays, Two-pointer technique

U-nderstand

Understand what the interviewer is asking for by using test cases and questions about the problem.

  • Established a set (2-3) of test cases to verify their own solution later.
  • Established a set (1-2) of edge cases to verify their solution handles complexities.
  • Have fully understood the problem and have no clarifying questions.
  • Have you verified any Time/Space Constraints for this problem?
  • The function sort_by_parity() should take an integer array and rearrange the elements such that all even integers come before all odd integers. The function can return any arrangement that satisfies this condition.
HAPPY CASE
Input: [3, 1, 2, 4]
Expected Output: [2, 4, 3, 1] (or any valid arrangement)

EDGE CASE
Input: [0]
Expected Output: [0]

P-lan

Plan the solution with appropriate visualizations and pseudocode.

General Idea: Use the two-pointer technique to rearrange the elements in the array, where one pointer moves from the beginning and the other from the end. Swap elements if necessary based on their parity.

1. Initialize two pointers: `left` at the start (0) and `right` at the end (len(nums) - 1) of the array.
2. While `left` is less than `right`:
   a. If the element at `left` is odd and the element at `right` is even, swap them.
   b. If the element at `left` is even, increment the `left` pointer.
   c. If the element at `right` is odd, decrement the `right` pointer.
3. Return the modified array

⚠️ Common Mistakes

  • Failing to handle cases with only even or only odd numbers.
  • Incorrectly managing pointer movements after a swap.

I-mplement

Implement the code to solve the algorithm.

def sort_by_parity(nums):
    left = 0
    right = len(nums) - 1
    
    while left < right:
        if nums[left] % 2 > nums[right] % 2:
            nums[left], nums[right] = nums[right], nums[left]
        
        if nums[left] % 2 == 0:
            left += 1
        if nums[right] % 2 == 1:
            right -= 1
    
    return nums
Clone this wiki locally