#3467
Transform Array by Parity
EasyArraySortingCountingCountingArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
Count the even and odd numbers, then construct the result directly based on counts, which avoids sorting.
⚙️
Algorithm
3 steps- 1Step 1: Initialize counters for even and odd numbers.
- 2Step 2: Iterate through the array to count evens and odds.
- 3Step 3: Construct the result array with '0's followed by '1's based on the counts.
solution.py3 lines
1def transform_array(nums):
2 evens = sum(1 for x in nums if x % 2 == 0)
3 return [0] * evens + [1] * (len(nums) - evens)ℹ
Complexity note: Counting evens and odds takes O(n), and constructing the result also takes O(n), leading to O(n) overall.
- 1Transforming numbers can be done with counting instead of sorting.
- 2Directly constructing the output array saves time.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.