Facebook Pixel

3467. Transform Array by Parity

Problem Description

You are given an integer array nums. Your task is to transform this array by following these three steps in exact order:

  1. Replace even numbers with 0: Go through the array and change every even number to 0
  2. Replace odd numbers with 1: Go through the array and change every odd number to 1
  3. Sort the array: Arrange the modified array in non-decreasing order (smallest to largest)

After performing these operations, return the transformed array.

The solution takes advantage of a key observation: after steps 1 and 2, the array will only contain 0s and 1s. When sorted in non-decreasing order, all the 0s will come first, followed by all the 1s.

The approach counts how many even numbers exist in the original array (let's call this count even). Since even numbers become 0s and odd numbers become 1s, and after sorting all 0s come before all 1s, the final array will have exactly even number of 0s at the beginning, followed by 1s for the remaining positions.

For example, if nums = [3, 2, 5, 4]:

  • After steps 1 & 2: [1, 0, 1, 0] (3 and 5 are odd β†’ 1, while 2 and 4 are even β†’ 0)
  • After sorting: [0, 0, 1, 1]

The solution directly constructs this final result by placing even number of 0s first, then filling the rest with 1s.

Quick Interview Experience
Help others by sharing your interview experience
Have you seen this problem before?

Intuition

The key insight comes from recognizing what the array looks like after each transformation step. After replacing even numbers with 0 and odd numbers with 1, we only have two distinct values in our array: 0 and 1.

When we sort an array containing only 0s and 1s, the result is predictable - all 0s will group together at the beginning, and all 1s will group together at the end. This is because 0 < 1, so sorting places all 0s before all 1s.

This observation leads to an important realization: we don't actually need to perform the replacements and sorting operations. Instead, we can directly construct the final result if we know how many 0s and 1s we'll have.

Since 0s come from even numbers and 1s come from odd numbers, we just need to count how many even numbers are in the original array. If there are even even numbers, then:

  • The final sorted array will have even zeros at the beginning
  • The remaining len(nums) - even positions will be filled with 1s

This allows us to bypass the intermediate steps entirely. Rather than:

  1. Replacing values (O(n) operation)
  2. Sorting (O(n log n) operation)

We can directly build the result in O(n) time by:

  1. Counting even numbers (one pass through the array)
  2. Filling the first even positions with 0
  3. Filling the remaining positions with 1

This optimization transforms what appears to be an O(n log n) problem due to sorting into an O(n) problem through pattern recognition.

Learn more about Sorting patterns.

Solution Approach

The implementation follows a counting-based approach that avoids the need for actual replacement and sorting operations.

Step 1: Count Even Numbers

First, we traverse the array nums and count how many even numbers exist:

even = sum(x % 2 == 0 for x in nums)

This uses a generator expression with the modulo operator. For each element x, we check if x % 2 == 0 (which is True for even numbers, False for odd). The sum() function counts the True values (treating True as 1 and False as 0).

Step 2: Fill the Array with 0s and 1s

Once we know there are even even numbers, we can directly construct the sorted result:

for i in range(even):
    nums[i] = 0

This fills the first even positions with 0 (representing the sorted even numbers).

for i in range(even, len(nums)):
    nums[i] = 1

This fills the remaining positions (from index even to the end) with 1 (representing the sorted odd numbers).

Step 3: Return the Result

return nums

The solution modifies the array in-place and returns it.

Time and Space Complexity:

  • Time Complexity: O(n) where n is the length of the array. We make one pass to count even numbers and one pass to fill the array.
  • Space Complexity: O(1) as we only use a single variable even for counting and modify the array in-place.

This approach is more efficient than the naive solution of actually performing replacements followed by sorting, which would take O(n log n) time due to the sorting step.

Ready to land your dream job?

Unlock your dream job with a 5-minute evaluator for a personalized learning plan!

Start Evaluator

Example Walkthrough

Let's walk through the solution with the array nums = [7, 2, 8, 3, 6].

Step 1: Count Even Numbers

We traverse the array and check each element:

  • 7 % 2 = 1 (odd) β†’ contributes 0 to count
  • 2 % 2 = 0 (even) β†’ contributes 1 to count
  • 8 % 2 = 0 (even) β†’ contributes 1 to count
  • 3 % 2 = 1 (odd) β†’ contributes 0 to count
  • 6 % 2 = 0 (even) β†’ contributes 1 to count

Total: even = 3 (there are 3 even numbers: 2, 8, and 6)

Step 2: Build the Result Array

Since we have 3 even numbers and the array length is 5:

  • The first 3 positions will be filled with 0s (representing the even numbers after transformation and sorting)
  • The remaining 2 positions (5 - 3 = 2) will be filled with 1s (representing the odd numbers)

Filling process:

  • Positions 0 to 2 (first even positions): Fill with 0
    • nums[0] = 0
    • nums[1] = 0
    • nums[2] = 0
  • Positions 3 to 4 (remaining positions): Fill with 1
    • nums[3] = 1
    • nums[4] = 1

Final Result: [0, 0, 0, 1, 1]

To verify this is correct, let's trace what would happen with the original three-step process:

  • Original: [7, 2, 8, 3, 6]
  • After replacing evens with 0: [7, 0, 0, 3, 0]
  • After replacing odds with 1: [1, 0, 0, 1, 0]
  • After sorting: [0, 0, 0, 1, 1] βœ“

Our optimized approach produces the same result directly without performing the intermediate transformations or sorting.

Solution Implementation

1class Solution:
2    def transformArray(self, nums: List[int]) -> List[int]:
3        # Count the number of even elements in the array
4        even_count = sum(x % 2 == 0 for x in nums)
5      
6        # Set the first 'even_count' elements to 0
7        for i in range(even_count):
8            nums[i] = 0
9      
10        # Set the remaining elements to 1
11        for i in range(even_count, len(nums)):
12            nums[i] = 1
13      
14        return nums
15
1class Solution {
2    /**
3     * Transforms an array by placing all even elements (as 0s) at the beginning
4     * and all odd elements (as 1s) at the end.
5     * 
6     * @param nums the input array of integers
7     * @return the transformed array with 0s representing even numbers and 1s representing odd numbers
8     */
9    public int[] transformArray(int[] nums) {
10        // Count the number of even elements in the array
11        int evenCount = 0;
12        for (int num : nums) {
13            // Check if number is even using bitwise operations
14            // (num & 1) gives 0 for even, 1 for odd
15            // XOR with 1 flips the bit: 0^1=1 (even), 1^1=0 (odd)
16            evenCount += ((num & 1) ^ 1);
17        }
18      
19        // Fill the first part of the array with 0s (representing even numbers)
20        for (int i = 0; i < evenCount; i++) {
21            nums[i] = 0;
22        }
23      
24        // Fill the remaining part of the array with 1s (representing odd numbers)
25        for (int i = evenCount; i < nums.length; i++) {
26            nums[i] = 1;
27        }
28      
29        return nums;
30    }
31}
32
1class Solution {
2public:
3    vector<int> transformArray(vector<int>& nums) {
4        // Count the number of even numbers in the array
5        int evenCount = 0;
6        for (int num : nums) {
7            // Check if number is even using bitwise operations
8            // (num & 1) gives 0 for even, 1 for odd
9            // XOR with 1 inverts it: 1 for even, 0 for odd
10            evenCount += ((num & 1) ^ 1);
11        }
12      
13        // Fill the first 'evenCount' positions with 0
14        for (int i = 0; i < evenCount; ++i) {
15            nums[i] = 0;
16        }
17      
18        // Fill the remaining positions with 1
19        for (int i = evenCount; i < nums.size(); ++i) {
20            nums[i] = 1;
21        }
22      
23        return nums;
24    }
25};
26
1/**
2 * Transforms an array by replacing elements with 0s and 1s based on the count of even numbers.
3 * The first 'n' elements become 0 (where n = count of even numbers), and the rest become 1.
4 * 
5 * @param nums - The input array of numbers to transform
6 * @returns The transformed array with 0s and 1s
7 */
8function transformArray(nums: number[]): number[] {
9    // Count the number of even elements in the array
10    const evenCount: number = nums.filter((num: number) => num % 2 === 0).length;
11  
12    // Set the first 'evenCount' elements to 0
13    for (let i: number = 0; i < evenCount; ++i) {
14        nums[i] = 0;
15    }
16  
17    // Set the remaining elements to 1
18    for (let i: number = evenCount; i < nums.length; ++i) {
19        nums[i] = 1;
20    }
21  
22    return nums;
23}
24

Time and Space Complexity

The time complexity is O(n), where n is the length of the array nums. This is because:

  • The first line counts even numbers by iterating through all n elements once: O(n)
  • The second loop runs even times (where even ≀ n): O(even)
  • The third loop runs n - even times: O(n - even)
  • Total: O(n) + O(even) + O(n - even) = O(n) + O(n) = O(n)

The space complexity is O(1). The algorithm only uses a constant amount of extra space for the variable even and loop counter i, regardless of the input size. The modifications are made in-place to the input array nums, so no additional space proportional to the input size is required.

Learn more about how to find time and space complexity quickly.

Common Pitfalls

1. Modifying the Original Array Without Considering Requirements

One common pitfall is assuming that modifying the input array in-place is always acceptable. Some problems or use cases might require preserving the original array.

The Issue: The current solution modifies nums directly, which means the original data is lost after transformation.

Solution: If preserving the original array is needed, create a new array for the result:

class Solution:
    def transformArray(self, nums: List[int]) -> List[int]:
        # Count the number of even elements
        even_count = sum(x % 2 == 0 for x in nums)
      
        # Create a new array for the result
        result = [0] * even_count + [1] * (len(nums) - even_count)
      
        return result

2. Edge Case: Empty Array

While the current solution handles empty arrays correctly (the loops simply don't execute), developers might overlook testing this edge case.

The Issue: Not explicitly considering what happens when nums = [].

Solution: Add an early return for clarity and efficiency:

class Solution:
    def transformArray(self, nums: List[int]) -> List[int]:
        if not nums:
            return nums
      
        even_count = sum(x % 2 == 0 for x in nums)
      
        for i in range(even_count):
            nums[i] = 0
      
        for i in range(even_count, len(nums)):
            nums[i] = 1
      
        return nums

3. Integer Overflow Concerns

In languages with fixed integer sizes, checking x % 2 on very large integers might cause issues. While Python handles arbitrary precision integers well, this could be a pitfall when translating to other languages.

The Issue: In some programming languages, very large integers might overflow or behave unexpectedly with modulo operations.

Solution: Use bitwise operations for even/odd checking, which is also slightly more efficient:

class Solution:
    def transformArray(self, nums: List[int]) -> List[int]:
        # Use bitwise AND to check for even numbers (even if x & 1 == 0)
        even_count = sum((x & 1) == 0 for x in nums)
      
        for i in range(even_count):
            nums[i] = 0
      
        for i in range(even_count, len(nums)):
            nums[i] = 1
      
        return nums

4. Misunderstanding the Problem Requirements

A critical pitfall is misinterpreting the problem and thinking you need to actually perform the three steps sequentially (replace evens, replace odds, then sort).

The Issue: Implementing the naive approach:

# Inefficient approach - DON'T DO THIS
for i in range(len(nums)):
    if nums[i] % 2 == 0:
        nums[i] = 0
    else:
        nums[i] = 1
nums.sort()  # O(n log n) - unnecessary!

Solution: Recognize the pattern that after transformation, you'll always have all 0s followed by all 1s, allowing for the O(n) counting solution shown in the original code.

Discover Your Strengths and Weaknesses: Take Our 5-Minute Quiz to Tailor Your Study Plan:

Which data structure is used to implement priority queue?


Recommended Readings

Want a Structured Path to Master System Design Too? Don’t Miss This!

Load More