Problem 922

Abstract / Summary

Arrange the array so every even index has an even number and every odd index has an odd number.

Note

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

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
18 lines | 438 bytes | submitted August 18, 2023 | GitHub   7% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 71% (500k+ 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 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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 7 | μ = 6.54 | σ = 1.37

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 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
37 links | 22 authors | 10 languages

Videos

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

Similar Problems

4 similar problems

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