Shuffle the Array (LeetCode 1470)
Interleaving two halves in one pass
The problem
You get nums of length 2n, laid out as [x1, x2, ..., xn, y1, y2, ..., yn].
Return [x1, y1, x2, y2, ..., xn, yn].
Example: nums = [2,5,1,3,4,7], n = 3 gives [2,3,5,4,1,7].
The idea
The first half and the second half line up index by index.
Element i of the first half is nums[i]; its partner is nums[i + n].
Walk i from 0 to n - 1 and append the pair each time.
Code (Python)
def shuffle(nums, n):
out = []
for i in range(n):
out.append(nums[i])
out.append(nums[i + n])
return out
Time O(n), extra space O(n) for the output.
Interview follow-up
"Can you do it in place?" Values are at most 1000, so you can pack two numbers into one slot (a + b * 1024) and unpack in a second pass. Explain the bound before you rely on it.
Practice tip
Say the index mapping out loud (i and i + n) before coding. Interviewers care that you see the structure, not just the loop.
I write these notes for Linkjob AI. If you want to rehearse explaining solutions under time pressure, an AI interview assistant can help you practice.
Shuffle the Array (LeetCode 1470): Interleaving Two Halves
By linkjob-ai
Shuffle the Array (LeetCode 1470): Interleaving Two Halves
- 5