Python 0922.py
class Solution:
def sortArrayByParityII(self, nums: List[int]) -> List[int]:
odd = []
even = []
for i in nums:
if i % 2 == 0:
even.append(i)
else:
odd.append(i)
result = []
for i in range(len(even)):
# zero-based
result.append(even[i])
result.append(odd[i])
return result
Difficulty
and has an acceptance rate of about 71% (500k+ submissions).
Typical patterns to solve this problem:
- Array
- Sorting
- Two Pointers
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation defines a method that receives a list of integers and returns a new list where the elements are arranged such that every even-indexed position holds an even number and every odd-indexed position holds an odd number. The algorithm first partitions the input into two collections-one for even values and one for odd values-then interleaves these collections to produce the final ordering.
Partitioning the Input
The first logical block iterates over the original array and distributes each element based on its parity.
odd = []
even = []
for i in nums:
if i % 2 == 0:
even.append(i)
else:
odd.append(i)
During this pass each element is examined exactly once, and the modulo operation determines its category. The use of two separate lists isolates even and odd numbers, simplifying later processing.
Interleaving the Two Collections
After the partitioning step, the method builds the result by alternating elements from the even list and the odd list.
result = []
for i in range(len(even)):
# zero-based
result.append(even[i])
result.append(odd[i])
The loop runs for the length of the even list, which, by problem constraints, matches the length of the odd list. By appending an even element followed by the corresponding odd element, the method guarantees the required parity placement at each index.
Edge Cases Handled
The algorithm gracefully handles an empty input list; the initial partitioning loops produce two empty collections, and the interleaving loop executes zero times, resulting in an empty output list. When the input contains a single pair of numbers-one even and one odd-the partitioning creates one-element even and odd lists, and the interleaving loop runs once, yielding a correctly ordered two-element result. The code also correctly processes inputs that contain zero values, as zero satisfies the even-parity check (0 % 2 == 0). Because the interleaving loop relies on the length of the even list, any input that respects the required balance of even and odd numbers will be handled without index errors.
Performance Optimizations
The implementation achieves efficiency by separating concerns into two linear passes: one for classification and one for construction. The first pass avoids any unnecessary data movement beyond appending to the appropriate list, and the second pass directly accesses elements by index, eliminating the need for additional searches or condition checks. By pre-allocating the odd and even containers and using append, the method leverages the underlying dynamic array growth strategy, which amortizes allocation costs. The interleaving loop accesses each list by index, which is an O(1) operation, ensuring that the overall runtime scales linearly with the size of the input. The clear separation of even and odd elements also reduces branching inside the final loop, as the parity decision has already been resolved.
ELI5 - Simplified Explanation
Imagine you have a big pile of mixed-up socks that belong to two different toy robots. One robot only wears even numbers and the other robot only wears odd numbers.
To help them get dressed, first look at every sock in the pile one by one. If the number on the sock is an even number, put it into a special even basket. If the number is an odd number, put it into a special odd basket. Now there are two neat baskets waiting on the floor.
Next, pick up one even sock from the first basket and place it on the floor. Then, pick up one odd sock from the other basket and place it right next to the even one. Keep doing this pattern, taking one from the even basket and then one from the odd basket, until all the socks are lined up in a long, perfect row.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||||
| www | AlgoMonster | C++ | Java | Python | TS | ||||||
| WalkCCC | C++ | Java | Python | ||||||||
| leetcode.ca | C++ | Java | Python | JS | Go | Rust | TS | ||||
| LeetcodeHelp | C++ | Java | Python | ||||||||
| Progiez | C++ | Java | Python | ||||||||
| github | BigEggStudy | C# | |||||||||
| black-shadows | C++ | ||||||||||
| charles-wangkai | Java | ||||||||||
| DimitrisJim | C | ||||||||||
| everthis | JS | ||||||||||
| fartem | Ruby | ||||||||||
| fsq | C++ | ||||||||||
| gouthampradhan | Java | ||||||||||
| halfrost | Go | ||||||||||
| JoshCrozier | JS | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| Krazune | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| qiyuangong | Java | ||||||||||
| suxrobGM | C# | ||||||||||
| varunu28 | Java | ||||||||||
| YuriSpiridonov | Python | ||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||
| WalkCCC | C++, Python, Java | ||||||||||
| leetcode.ca | C++, Go, Java, JavaScript, Python, Rust, TypeScript | ||||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||||
| Progiez | C++, Java, Python | ||||||||||
| BigEggStudy | C# | ||||||||||
| black-shadows | C++, C++ | ||||||||||
| charles-wangkai | Java | ||||||||||
| DimitrisJim | C | ||||||||||
| everthis | JavaScript | ||||||||||
| fartem | Ruby | ||||||||||
| fsq | C++ | ||||||||||
| gouthampradhan | Java | ||||||||||
| halfrost | Go | ||||||||||
| JoshCrozier | JavaScript | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| Krazune | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| qiyuangong | Java | ||||||||||
| suxrobGM | C# | ||||||||||
| varunu28 | Java | ||||||||||
| YuriSpiridonov | Python |
Videos
Similar Problems
- problem 905: Sort Array By Parity
- problem 2149: Rearrange Array Elements by Sign
- problem 2164: Sort Even and Odd Indices Independently
- problem 2231: Largest Number After Digit Swaps by Parity
Solved On The Same Day
- problem 205: Isomorphic Strings
- problem 905: Sort Array By Parity
- problem 2423: Remove Letter To Equalize Frequency
- problem 18: 4Sum
- problem 80: Remove Duplicates from Sorted Array II
- problem 92: Reverse Linked List II
- problem 93: Restore IP Addresses
- problem 384: Shuffle an Array
- problem 1143: Longest Common Subsequence
- problem 1615: Maximal Network Rank
- problem 32: Longest Valid Parentheses
- problem 149: Max Points on a Line
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality