Problem 905

Abstract / Summary

Rearrange an array so that all even numbers come before all odd numbers.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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
12 lines | 284 bytes | submitted August 18, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 77% (1+ million submissions).

Typical patterns to solve this problem:
  • Array
  • Sorting
  • Two Pointers
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 8 | μ = 7.52 | σ = 0.96

Complexity Analysis

Time: linear
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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
41 links | 26 authors | 10 languages

Videos

4 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

3 easy 7 medium 2 hard
13 solutions   August 18, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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