Taro Logo

Sort Array By Parity

#5 Most AskedEasy
0 views
Topics:
ArraysTwo Pointers

Given an integer array nums, move all the even integers at the beginning of the array followed by all the odd integers.

Return any array that satisfies this condition.

Example 1:

Input: nums = [3,1,2,4]
Output: [2,4,3,1]
Explanation: The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted.

Example 2:

Input: nums = [0]
Output: [0]

Constraints:

  • 1 <= nums.length <= 5000
  • 0 <= nums[i] <= 5000

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. Can the array contain negative numbers or zeros, and how should they be classified regarding parity?
  2. Should the sorting be done in-place, or is it acceptable to allocate a new array for the result?
  3. If multiple valid arrangements satisfy the condition, does it matter which one I return, or is any order among the evens and odds acceptable?
  4. What is the expected behavior if the input array is empty or contains only a single element?
  5. Are there any constraints on the maximum size of the input array or the range of the integers it contains?

Brute Force Solution

Approach

Imagine you have a mixed pile of items where some are of one type and the others are of a different type, and you want to group all of one specific type together at the beginning. The brute force strategy involves meticulously searching through your collection to find what you are looking for and organizing the items by completely re-examining the collection multiple times.

Here's how the algorithm would work step-by-step:

  1. Start by looking through the entire collection from the very beginning to the very end to find the first item of the special type you want to group first.
  2. Whenever you find one of these special items, pull it out and place it neatly at the front of a brand new workspace.
  3. Once you have scanned through and collected all the items of that special type by placing them at the beginning, go back through the remaining items in the original collection.
  4. Pick up every remaining item one by one and place them directly after the first group of items in your workspace.
  5. Review your new workspace to confirm that all items of the first type are grouped together at the front followed by everything else.

Code Implementation

def sort_array_by_parity(input_numbers):
    workspace_array = []

    # We scan first to isolate all even numbers at the front of our new workspace
    for current_number in input_numbers:
        if current_number % 2 == 0:
            workspace_array.append(current_number)

    # We scan a second time to append remaining odd numbers after the evens
    for current_number in input_numbers:
        if current_number % 2 != 0:
            workspace_array.append(current_number)

    # We return the fully reorganized workspace containing both grouped types
    return workspace_array

Big(O) Analysis

Time Complexity
O(n) – The strategy involves scanning through the entire array of size n twice to separate the even and odd numbers. First, we iterate through all n elements to find and collect all the even numbers, which takes n operations. Then, we iterate through the array a second time to collect all the remaining odd numbers, taking another n operations. Combining these passes results in approximately n plus n operations, which simplifies to a linear time complexity of O(n).
Space Complexity
O(N) – The brute force strategy described requires allocating a brand new workspace array to hold all the rearranged items. Because this new array must store every single element from the original collection, the extra memory scales directly with the input size N. Specifically, this intermediate storage demands an auxiliary array of size N to house the grouped elements before they are reviewed. As the input size N grows, the auxiliary memory required increases proportionally, leading to a linear space complexity of O(N).

Optimal Solution

Approach

The optimal approach uses two searchers starting from opposite ends of the line to organize the items efficiently. By moving inward and swapping items when they are in the wrong places, the collection is sorted in a single pass.

Here's how the algorithm would work step-by-step:

  1. Station one searcher at the very beginning of the line and another searcher at the very end.
  2. Instruct the searcher at the beginning to look for an odd item, and the searcher at the end to look for an even item.
  3. Once both searchers find what they are looking for, have them swap their items so the even item moves toward the front and the odd item moves toward the back.
  4. After the swap, have both searchers take one step closer to each other.
  5. If a searcher is already looking at the correct type of item, have that searcher stay put while the other searcher catches up.
  6. Continue this process of searching, swapping, and moving until the two searchers meet in the middle.
  7. Once they meet, all the even items will be grouped at the front and all the odd items will be at the back.

Code Implementation

def sort_array_by_parity(input_array):
    left_searcher = 0
    right_searcher = len(input_array) - 1

    # Traverse inward until pointers meet to partition evens and odds efficiently.
    while left_searcher < right_searcher:
        while left_searcher < right_searcher and input_array[left_searcher] % 2 == 0:
            left_searcher += 1

        while left_searcher < right_searcher and input_array[right_searcher] % 2 == 1:
            right_searcher -= 1

        # Swap mispositioned elements so evens move left and odds move right.
        if left_searcher < right_searcher:
            input_array[left_searcher], input_array[right_searcher] = input_array[right_searcher], input_array[left_searcher]
            left_searcher += 1
            right_searcher -= 1

    return input_array

Big(O) Analysis

Time Complexity
O(n) – The two-pointer approach involves a left searcher and a right searcher that traverse the array from opposite ends toward the center. Each element in the array of size n is visited at most once by either the left or the right pointer as they move inward. The total number of operations scales linearly with the input size because the pointers never backtrack. This results in approximately n operations in the worst case, which simplifies to O(n).
Space Complexity
O(1) – The two-pointer approach reorganizes the elements directly within the original input array by swapping them in place. The algorithm only allocates a few primitive variables to track the positions of the searchers at the beginning and the end. Because no auxiliary data structures, temporary lists, or recursion stack frames are utilized, the extra memory remains constant regardless of the input size N.

Edge Cases

Empty array or null input
How to Handle:
Return the array as-is since no rearrangement is necessary.
Array with a single element
How to Handle:
Return the array unchanged because a single element is already sorted by parity.
Array with all even numbers
How to Handle:
Pointers traverse the array without swapping, leaving all elements in their original positions.
Array with all odd numbers
How to Handle:
The left pointer immediately finds an odd number and stays put while the right pointer scans to the beginning, resulting in no changes.
Array with alternating even and odd numbers
How to Handle:
The two-pointer swap approach efficiently moves evens to the front and odds to the back in a single pass.
Array containing negative numbers and zero
How to Handle:
Parity is determined by modulo two, so negative even numbers and zero correctly route to the beginning of the array.
Maximum constraint array size up to the problem limit
How to Handle:
An in-place two-pointer approach scales linearly with time complexity O(N) and space complexity O(1).
Multiple valid solutions possible
How to Handle:
The problem accepts any ordering of evens followed by odds, so the relative order of elements does not need to be preserved.
0/6 completed