Transform Array by Parity - Problem
Transform Array by Parity

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 0
2. Replace each odd number with 1
3. 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
Transform Array by Parity - Complete SolutionInput Array3124Step 1: Counting PhaseCount Even Numbers:2, 4โ†’Even: 2Count Odd Numbers:3, 1โ†’Odd: 2Step 2: Direct ConstructionCreate result: 2 zeros (for evens) + 2 ones (for odds)0011โœ“ Final Result: [0, 0, 1, 1]๐Ÿš€ Algorithm EfficiencyTime Complexity: O(n) - Single pass for countingSpace Complexity: O(1) - Only counter variables needed
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!
Asked in
Amazon 45 Google 38 Microsoft 32 Meta 28
28.7K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen