Python 0905.py
class Solution:
def sortArrayByParity(self, nums: List[int]) -> List[int]:
odd = []
even = []
for i in nums:
if i % 2 == 0:
even.append(i)
else:
odd.append(i)
return even + odd
Difficulty
and has an acceptance rate of about 77% (1+ million 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 class Solution with a method sortArrayByParity that receives a list of integers and returns a new list where all even numbers appear before any odd numbers. The algorithm follows a straightforward two-bucket approach: it separates the input into an even bucket and an odd bucket, then concatenates the buckets to produce the final ordering.
Key Steps
Bucket Initialization
The method begins by creating two empty containers, one for even values and one for odd values.
odd = []
even = []
These lists serve as the temporary storage for elements classified by parity.
Single-Pass Classification Loop
A for loop iterates over each element of the input list nums. For each element i, the code evaluates the remainder of division by two.
for i in nums:
if i % 2 == 0:
even.append(i)
else:
odd.append(i)
If the remainder is zero, the element is appended to the even list; otherwise, it is appended to the odd list. This loop processes the entire input in one linear pass, ensuring that each element is examined exactly once.
Result Construction
After classification, the method returns the concatenation of the two buckets, placing the even bucket first.
return even + odd
The + operator creates a new list that contains all elements of even followed by all elements of odd. This final list satisfies the required ordering constraint.
Edge Cases Handled
The algorithm gracefully handles an empty input list. In that scenario, both even and odd remain empty, and the concatenation yields an empty list, which is a correct result.
When the input consists solely of even numbers, the odd bucket stays empty, and the concatenated result is simply a copy of the original list, preserving the original order of even elements.
Conversely, if the input contains only odd numbers, the even bucket remains empty, and the returned list is a copy of the original list, now positioned after an empty even segment.
Negative integers are also correctly classified because the modulo operation with 2 yields a remainder of 0 for even negatives and 1 for odd negatives. Thus, the method works uniformly for the full range of integer values supported by Python.
Performance Optimizations
The implementation leverages Python’s built-in list append method, which operates in amortized constant time, allowing rapid insertion of elements into the buckets without the overhead of resizing on each operation.
By performing a single traversal of the input list, the algorithm avoids repeated passes or nested loops, minimizing the total number of element accesses.
The final concatenation uses the list + operator, which efficiently allocates a new list of the exact required size and copies the contents of the two buckets in a single operation. This approach eliminates the need for incremental extensions or additional temporary structures during the merge phase.
Overall, the design achieves a streamlined flow: initialization, one pass for classification, and a single copy step for result assembly, each step optimized for the typical performance characteristics of Python list operations.
ELI5 - Simplified Explanation
Imagine there is a big basket filled with mixed up numbers. Some of these numbers are even, like the ones that have a buddy pair, and others are odd, like the ones that are all by themselves. To fix this, two empty buckets are set out. One bucket is for the even friends and one bucket is for the odd friends. Every number in the basket is picked up one by one. If a number is even, it gets placed into the even bucket. If a number is odd, it gets placed into the odd bucket. After every single number has been sorted, the even bucket is placed next to the odd bucket to make one long line of sorted numbers.
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 | Rust | Go | TS | ||||
| LeetcodeHelp | C++ | Java | Python | ||||||||
| Progiez | C++ | Java | Python | ||||||||
| github | BigEggStudy | C# | |||||||||
| black-shadows | C++ | ||||||||||
| charles-wangkai | Java | ||||||||||
| Dijkstra-Edu | Java | ||||||||||
| DimitrisJim | C | ||||||||||
| everthis | JS | ||||||||||
| fartem | Ruby | ||||||||||
| fpdjsns | C++ | ||||||||||
| fsq | C++ | ||||||||||
| haoel | C++ | ||||||||||
| JoshCrozier | JS | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| Krazune | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| qiyuangong | Java | ||||||||||
| ruoru | Rust | ||||||||||
| suxrobGM | C# | ||||||||||
| trung-hn | Python | ||||||||||
| varunu28 | Java | ||||||||||
| XiaotaoGuo | C++ | ||||||||||
| 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 | ||||||||||
| Dijkstra-Edu | Java | ||||||||||
| DimitrisJim | C | ||||||||||
| everthis | JavaScript | ||||||||||
| fartem | Ruby | ||||||||||
| fpdjsns | C++ | ||||||||||
| fsq | C++ | ||||||||||
| haoel | C++ | ||||||||||
| JoshCrozier | JavaScript | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| Krazune | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| qiyuangong | Java | ||||||||||
| ruoru | Rust | ||||||||||
| suxrobGM | C# | ||||||||||
| trung-hn | Python | ||||||||||
| varunu28 | Java | ||||||||||
| XiaotaoGuo | C++ | ||||||||||
| YuriSpiridonov | Python |
Videos
Similar Problems
- problem 922: Sort Array By Parity II
Solved On The Same Day
- problem 205: Isomorphic Strings
- problem 922: Sort Array By Parity II
- 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