Problem 1470

Abstract / Summary

Given a sorted array and an integer indicating a split point, interleave the elements from the two halves while maintaining their original order.

Note

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

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]
5 lines | 165 bytes | submitted October 3, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

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

Typical patterns to solve this problem:
  • Array
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 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.

written by openai gpt

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.

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.38 | σ = 2.27

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++ 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
41 links | 28 authors | 10 languages

Videos

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

Solved On The Same Day

5 easy 4 medium 4 hard
14 solutions   October 3, 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