Transform Array by Parity - Problem
Transform Array by Parity
You are given an integer array
Operations to perform (in exact order):
1. Replace each even number with
2. Replace each odd number with
3. Sort the modified array in non-decreasing order
Return the resulting array after performing these operations.
Example: If
You are given an integer array
nums. Your task is to transform this array through a specific sequence of operations that will convert it into a binary representation based on parity.Operations to perform (in exact order):
1. Replace each even number with
02. Replace each odd number with
13. Sort the modified array in non-decreasing order
Return the resulting array after performing these operations.
Example: If
nums = [3, 1, 2, 4], after replacing by parity we get [1, 1, 0, 0], and after sorting we get [0, 0, 1, 1]. Input & Output
example_1.py โ Basic Case
$
Input:
[3, 1, 2, 4]
โบ
Output:
[0, 0, 1, 1]
๐ก Note:
3 (odd) โ 1, 1 (odd) โ 1, 2 (even) โ 0, 4 (even) โ 0. After transformation: [1, 1, 0, 0]. After sorting: [0, 0, 1, 1].
example_2.py โ All Even Numbers
$
Input:
[2, 4, 6, 8]
โบ
Output:
[0, 0, 0, 0]
๐ก Note:
All numbers are even, so they all become 0. The array remains [0, 0, 0, 0] after sorting.
example_3.py โ Single Element
$
Input:
[5]
โบ
Output:
[1]
๐ก Note:
5 is odd, so it becomes 1. The result is [1].
Constraints
- 1 โค nums.length โค 104
- 1 โค nums[i] โค 103
- All elements in nums are positive integers
Visualization
Tap to expand
Understanding the Visualization
1
Identify Pattern
Recognize that after transformation, we only have 0s and 1s
2
Count Categories
Count how many even (โ0) and odd (โ1) numbers we have
3
Direct Construction
Build the sorted result directly: all 0s first, then all 1s
Key Takeaway
๐ฏ Key Insight: Since the result only contains 0s and 1s, we can skip the transformation and sorting steps entirely by counting the frequencies and constructing the sorted result directly!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code