Taro Logo

Transform Array by Parity

#62 Most AskedEasy
0 views
Topics:
Arrays

You are given an integer array nums. Transform nums by performing the following operations in the exact order specified:

  1. Replace each even number with 0.
  2. Replace each odd numbers with 1.
  3. Sort the modified array in non-decreasing order.

Return the resulting array after performing these operations.

Example 1:

Input: nums = [4,3,2,1]

Output: [0,0,1,1]

Explanation:

  • Replace the even numbers (4 and 2) with 0 and the odd numbers (3 and 1) with 1. Now, nums = [0, 1, 0, 1].
  • After sorting nums in non-descending order, nums = [0, 0, 1, 1].

Example 2:

Input: nums = [1,5,1,4,2]

Output: [0,0,1,1,1]

Explanation:

  • Replace the even numbers (4 and 2) with 0 and the odd numbers (1, 5 and 1) with 1. Now, nums = [1, 1, 1, 0, 0].
  • After sorting nums in non-descending order, nums = [0, 0, 1, 1, 1].

Constraints:

  • 1 <= nums.length <= 100
  • 1 <= nums[i] <= 1000

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. How large can the input array `nums` be, and what is the range of values for the integers inside it?
  2. Should the transformation and rearrangement be done in-place, or is it expected/acceptable to return a new array?
  3. If the input array is empty or contains only a single element, how should it be handled?
  4. When rearranging the zeros and ones, does the relative order among the original even numbers (now zeros) or odd numbers (now ones) need to be preserved (i.e., is stability required)?
  5. Can the input array contain negative numbers, and how should negative numbers be classified in terms of parity?

Brute Force Solution

Approach

Imagine you have a collection of items, and you want to rearrange them so that all the items that look a certain way come before the others. The brute force strategy involves gathering all the items and thoroughly inspecting every possible way to line them up until you find an arrangement where the required items are successfully moved to the front.

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

  1. Gather all the items together into a temporary workspace.
  2. Look at every single item in the workspace one by one to identify which ones belong at the very beginning of the line.
  3. Create a brand new line and place those specific identified items into it first.
  4. Return to the original workspace and collect all the remaining items that do not belong at the front.
  5. Place these remaining items directly behind the ones you already organized.
  6. Review the final combined line to ensure all the front-category items appear before the others.
  7. Present this newly arranged line as the final result.

Code Implementation

def transform_array_by_parity(input_numbers):
    # Gather all items into a workspace to safely inspect without losing original references
    workspace_numbers = list(input_numbers)

    front_category_items = []
    remaining_category_items = []

    # Separate items into categories to ensure all required elements move to the front
    for current_number in workspace_numbers:
        if current_number % 2 == 0:
            front_category_items.append(0)
        else:
            remaining_category_items.append(1)

    # Combine the categorized items so the front-category items precede the others
    final_arranged_line = front_category_items + remaining_category_items

    return final_arranged_line

Big(O) Analysis

Time Complexity
O(n) – To analyze the time complexity, let n be the number of items in the input array. Step 1 and 2 involve iterating through all n items to inspect their parity and identify them. Steps 3, 4, and 5 require iterating through the items again to build the new rearranged array by placing the front-category items first followed by the remaining ones. Since we perform a constant number of full passes over the n elements, the total operations scale linearly as n plus n, which simplifies to O(n).
Space Complexity
O(N) – The auxiliary space complexity is driven by the temporary workspace and the brand new line created to hold the rearranged items, where N represents the total number of elements in the collection. Specifically, the algorithm allocates a temporary list or array to gather and store all N elements during the multi-step sorting process. As the input size N grows, the memory required to hold these intermediate and final output structures scales in direct proportion. Therefore, the total extra memory consumed simplifies to Big O notation of O(N).

Optimal Solution

Approach

Instead of moving items around multiple times or creating a brand new collection, the optimal approach relies on counting how many items belong in each group first. Once you know how many special items you have, you can directly rewrite the collection by filling the beginning with zeroes for the first group and ones for the remaining spots.

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

  1. Look through the entire collection and count how many items belong to the first group.
  2. Take a fresh sheet and write down a zero for every single item that belongs to the first group.
  3. Look at how many spots are left over in the collection.
  4. Fill in all the remaining spots with ones.
  5. Replace the original collection with this newly organized sequence so everything is sorted by type.

Code Implementation

def transform_array_by_parity(input_numbers):
    # Count evens first to determine the exact boundary for zero placement.
    even_number_count = sum(1 for number in input_numbers if number % 2 == 0)

    # Construct the final array directly using the calculated group counts.
    transformed_numbers = [0] * even_number_count + [1] * (len(input_numbers) - even_number_count)

    # Mutate the original array in place to meet the return contract efficiently.
    input_numbers[:] = transformed_numbers

    return input_numbers

Big(O) Analysis

Time Complexity
O(n) – First, we iterate through the entire collection of n elements to count the items belonging to the first group. Next, we run through a sequence of operations bounded by n to fill the array with the appropriate zeros and ones. Since these two passes occur sequentially rather than being nested, the total operations scale linearly as roughly 2n, which simplifies to O(n).
Space Complexity
O(N) – The auxiliary space is driven by the newly organized sequence and the counter variables used to rewrite the collection. Specifically, step 2 and step 4 construct a fresh output list to hold all the transformed elements. Since this newly allocated sequence stores N elements where N is the total number of items in the input collection, the extra memory grows linearly with the input size. Thus, the overall auxiliary space complexity simplifies to Big O of N.

Edge Cases

Empty array or single element array
How to Handle:
Return the array as is since it is already trivially partitioned by parity.
Array with all even numbers
How to Handle:
Replace all elements with zeros and leave them in place since no ones exist to reorder past.
Array with all odd numbers
How to Handle:
Replace all elements with ones and leave them in place since no zeros exist to precede them.
Array with negative numbers
How to Handle:
Correctly classify negative even numbers as zeros and negative odd numbers as ones based on modulo parity rules.
Array with a mix of alternating even and odd numbers
How to Handle:
Count the number of zeros and ones to overwrite the array efficiently without extra sorting overhead.
Maximum constraint array sizes up to the limit
How to Handle:
Process the array in linear time using a single pass for counting and a second pass for rewriting to scale efficiently.
0/257 completed