Transform Array by Parity Problem
#3467
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3467.
You are given an integer array nums. Transform nums by performing the following operations in the exact order specified:
- Replace each even number with 0.
- Replace each odd numbers with 1.
- 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 <= 1001 <= nums[i] <= 1000
Solution
Approach: Counting
Replacing even numbers by 0 and odd numbers by 1 and then sorting just puts all the zeros first. So count the even numbers even, set the first even positions to 0 and the rest to 1.
Complexity: O(n) time, O(1) extra space.
class Solution:
def transformArray(self, nums: List[int]) -> List[int]:
even = sum(x % 2 == 0 for x in nums)
for i in range(even):
nums[i] = 0
for i in range(even, len(nums)):
nums[i] = 1
return nums