Python 1470.py
class Solution:
def shuffle(self, nums: List[int], n: int) -> List[int]:
for i in range(n):
yield nums[i]
yield nums[i + n]
Difficulty
and has an acceptance rate of about 89% (1+ million submissions).
Typical patterns to solve this problem:
- Array
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 Solution class with a single method shuffle. The method receives a list nums and an integer n, and it produces a sequence that interleaves the first n elements with the second n elements of the list. The interleaving is performed using a for loop that iterates over the index range of the first half and yields elements from both halves in alternating order. Because the method uses yield, the result is a generator that produces values on demand rather than constructing a full list up front.
Key Steps
Input Validation Implicit Assumption
The method assumes that nums contains exactly 2 * n elements. No explicit checks are present, so the logic proceeds under the premise that the input satisfies this contract.
Iteration Over the First Half
for i in range(n):
The loop variable i runs from 0 to n-1. This range covers every index belonging to the first half of the input list.
Yielding the Element from the First Half
yield nums[i]
During each iteration, the element at position i-which belongs to the first segment of the array-is emitted first.
Yielding the Corresponding Element from the Second Half
yield nums[i + n]
Immediately after the first element, the element located n positions ahead (i.e., the matching element from the second segment) is emitted. This creates the required alternating pattern.
Generator Output
Because the method uses yield statements, the caller receives a generator object. Consuming the generator (e.g., via list(solution.shuffle(nums, n))) will produce the interleaved sequence without ever storing the entire result in memory.
Edge Cases Handled
When n is zero, the range(n) expression yields an empty sequence, so the loop body never executes. Consequently, the generator produces no output, which correctly represents the interleaved result of two empty halves.
If nums is an empty list and n is also zero, the same behavior occurs: the generator yields nothing, matching the expectation for an empty input.
The implementation also gracefully handles the minimal non-empty case where n equals one and nums contains exactly two elements. The loop runs a single iteration, yielding the first element followed by the second, delivering the correct interleaved order.
Performance Optimizations
The use of a generator (yield) is a deliberate optimization. By emitting each element as it is computed, the method avoids allocating an auxiliary list to hold the entire shuffled result. This approach reduces peak memory consumption, especially beneficial when nums is large.
The loop body performs a constant amount of work per iteration: two index lookups and two yield operations. There is no additional data copying or temporary storage, which keeps the runtime overhead minimal.
Because the algorithm accesses each element exactly once and in sequential order, it benefits from CPU cache locality, further enhancing execution speed.
Overall, the design leverages lazy evaluation to achieve an efficient, low-memory solution for the interleaving task.
ELI5 - Simplified Explanation
Imagine you have a deck of cards split into two equal piles. One pile is on the left and the other pile is on the right. Both piles have the same number of cards, which is what n represents. The computer takes the very top card from the left pile and puts it down on the table. Then, it takes the very top card from the right pile and places it right next to it. It keeps doing this, grabbing from the left and then the right, until every single card has been moved into one long, mixed line. It is just like alternating turns playing a game by taking one piece and then letting your friend take one piece.
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++ | Python | Java | TS | ||||||
| WalkCCC | C++ | Python | Java | ||||||||
| leetcode.ca | C++ | Python | Java | Go | C | Rust | TS | ||||
| Progiez | C++ | Python | Java | ||||||||
| github | BigEggStudy | C# | |||||||||
| black-shadows | C++ | ||||||||||
| chandansgowda | Python | ||||||||||
| charles-wangkai | Java | ||||||||||
| Dijkstra-Edu | Java | ||||||||||
| DimitrisJim | C | ||||||||||
| everthis | JS | ||||||||||
| fartem | Ruby | ||||||||||
| FelixFan1122 | C# | ||||||||||
| fpdjsns | C++ | ||||||||||
| fsq | C++ | ||||||||||
| halfrost | Go | ||||||||||
| haoel | C++ | ||||||||||
| JoshCrozier | JS | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| Krazune | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| lzl124631x | C++ | ||||||||||
| muhammadfarhankt | Go | ||||||||||
| suxrobGM | C# | ||||||||||
| trung-hn | Python | ||||||||||
| varunu28 | Java | ||||||||||
| vthwang | Java | ||||||||||
| YuriSpiridonov | Python | ||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||
| WalkCCC | C++, Python, Java | ||||||||||
| leetcode.ca | C, C++, Go, Java, Python, Rust, TypeScript | ||||||||||
| Progiez | C++, Java, Python | ||||||||||
| BigEggStudy | C# | ||||||||||
| black-shadows | C++, C++ | ||||||||||
| chandansgowda | Python | ||||||||||
| charles-wangkai | Java | ||||||||||
| Dijkstra-Edu | Java | ||||||||||
| DimitrisJim | C | ||||||||||
| everthis | JavaScript | ||||||||||
| fartem | Ruby | ||||||||||
| FelixFan1122 | C# | ||||||||||
| fpdjsns | C++ | ||||||||||
| fsq | C++ | ||||||||||
| halfrost | Go | ||||||||||
| haoel | C++ | ||||||||||
| JoshCrozier | JavaScript | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| Krazune | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| lzl124631x | C++ | ||||||||||
| muhammadfarhankt | Go | ||||||||||
| suxrobGM | C# | ||||||||||
| trung-hn | Python | ||||||||||
| varunu28 | Java | ||||||||||
| vthwang | Java | ||||||||||
| YuriSpiridonov | Python |
Videos
Solved On The Same Day
- problem 598: Range Addition II
- problem 653: Two Sum IV - Input is a BST
- problem 1512: Number of Good Pairs
- problem 1920: Build Array from Permutation
- problem 1929: Concatenation of Array
- problem 396: Rotate Function
- problem 877: Stone Game
- problem 1033: Moving Stones Until Consecutive
- problem 2396: Strictly Palindromic Number
- problem 1402: Reducing Dishes
- problem 1406: Stone Game III
- problem 1463: Cherry Pickup II
- problem 1510: Stone Game IV
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