We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Transform Array by Parity

Number: 3778

Difficulty: Easy

Paid? No

Companies: N/A


Problem Description

Given an integer array, transform the array by replacing each even number with 0 and each odd number with 1, then sort the resulting array in non-decreasing order. Return the final transformed array.


Key Insights

  • The transformation step is straightforward: use the modulo operator to determine parity.
  • After transforming, sorting the binary array is efficient since it only contains 0s and 1s.
  • Care must be taken to perform the operations in the specified order.

Space and Time Complexity

Time Complexity: O(n log n) due to the sorting step (n is the length of the array).
Space Complexity: O(n) for storing the transformed array (or O(1) extra space if sorting in-place).


Solution

We first iterate over the array and replace each element: if the number is even, we set it to 0; otherwise, we set it to 1. Once the transformation is complete, we sort the array in non-decreasing order. This approach leverages a simple loop for transformation and the built-in sort method for ordering, which efficiently handles the nearly sorted nature of a binary array.


Code Solutions

# Python solution
def transformArrayByParity(nums):
    # Transform each element: even becomes 0, odd becomes 1
    transformed = [0 if num % 2 == 0 else 1 for num in nums]
    # Sort the transformed list in non-decreasing order and return it
    transformed.sort()
    return transformed

# Example usage:
nums = [4, 3, 2, 1]
print(transformArrayByParity(nums))  # Output: [0, 0, 1, 1]
← Back to All Questions