Problem

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

1
2
3
4
5
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

1
2
3
4
5
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

Examples

Solution

Method 1 – Counting/Sorting

Intuition

Replace even numbers with 0, odd numbers with 1, then sort. This is equivalent to counting the number of even and odd numbers and constructing the result.

Approach

Iterate through the array, replace each number as described, then sort the result.

Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
    vector<int> transformArray(vector<int>& nums) {
        for (int& x : nums) x = (x % 2 == 0 ? 0 : 1);
        sort(nums.begin(), nums.end());
        return nums;
    }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
import java.util.*;
class Solution {
    public int[] transformArray(int[] nums) {
        for (int i = 0; i < nums.length; ++i) {
            nums[i] = (nums[i] % 2 == 0) ? 0 : 1;
        }
        Arrays.sort(nums);
        return nums;
    }
}
1
2
3
4
from typing import List
class Solution:
    def transformArray(self, nums: List[int]) -> List[int]:
        return sorted(0 if x % 2 == 0 else 1 for x in nums)
1
2
3
4
5
6
7
8
9
impl Solution {
    pub fn transform_array(mut nums: Vec<i32>) -> Vec<i32> {
        for x in nums.iter_mut() {
            *x = if *x % 2 == 0 { 0 } else { 1 };
        }
        nums.sort();
        nums
    }
}
1
2
3
function transformArray(nums: number[]): number[] {
    return nums.map(x => x % 2 === 0 ? 0 : 1).sort((a, b) => a - b);
}

Complexity

  • ⏰ Time complexity: O(n log n)
  • 🧺 Space complexity: O(n)