Transform Array by Parity - 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 number with 1.

3. Sort the modified array in non-decreasing order.

Return the resulting array after performing these operations.

Input & Output

Example 1 — Basic Case
$ Input: nums = [3,1,2,4]
Output: [0,0,1,1]
💡 Note: Transform: 3→1 (odd), 1→1 (odd), 2→0 (even), 4→0 (even). After sorting: [0,0,1,1]
Example 2 — All Even
$ Input: nums = [2,4,6]
Output: [0,0,0]
💡 Note: All numbers are even, so all become 0. Sorted result: [0,0,0]
Example 3 — All Odd
$ Input: nums = [1,3,5]
Output: [1,1,1]
💡 Note: All numbers are odd, so all become 1. Sorted result: [1,1,1]

Constraints

  • 1 ≤ nums.length ≤ 1000
  • -1000 ≤ nums[i] ≤ 1000

Visualization

Tap to expand
Transform Array by Parity INPUT nums = [3, 1, 2, 4] 3 odd 1 odd 2 even 4 even i=0 i=1 i=2 i=3 Odd numbers Even numbers Array length: 4 2 odd, 2 even ALGORITHM STEPS 1 Check Each Element Determine if odd or even 2 Replace Even with 0 2 --> 0, 4 --> 0 3 Replace Odd with 1 3 --> 1, 1 --> 1 4 Sort Array Non-decreasing order Transformation: [3, 1, 2, 4] | [1, 1, 0, 0] | [0, 0, 1, 1] FINAL RESULT Output Array: 0 0 1 1 from even from even from odd from odd [0, 0, 1, 1] OK - Sorted! All 0s come before 1s Non-decreasing order Time: O(n log n) Space: O(1) or O(n) Key Insight: Optimal approach: Count evens (they become 0s) and odds (they become 1s). Result is always [0,0,...,0,1,1,...,1] with #evens zeros followed by #odds ones. This gives O(n) time complexity without actual sorting! TutorialsPoint - Transform Array by Parity | Optimal Solution
Asked in
Microsoft 25 Google 20 Amazon 15
28.1K Views
Medium Frequency
~15 min Avg. Time
850 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