DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Cover image for Algorithms Problem Solving: Shuffle the array
TK
TK

Posted on • Originally published at leandrotk.github.io

Algorithms Problem Solving: Shuffle the array

This post is part of the Algorithms Problem Solving series.

Problem description

This is the Shuffle the array problem. The description looks like this:

Given the arrayΒ numsΒ consisting ofΒ 2nΒ elements in the formΒ [x1,x2,...,xn,y1,y2,...,yn].

Return the array in the formΒ [x1,y1,x2,y2,...,xn,yn].

Examples

Input: nums = [2,5,1,3,4,7], n = 3
Output: [2,3,5,4,1,7]

Input: nums = [1,2,3,4,4,3,2,1], n = 4
Output: [1,4,2,3,3,2,4,1]

Input: nums = [1,1,2,2], n = 2
Output: [1,2,1,2]
Enter fullscreen mode Exit fullscreen mode

Solution

The idea of my solution was to get the first and the last half of the nums list. Then iterate through the lists and append one by one.

def shuffle(nums, n):
    first_half = nums[:n]
    last_half = nums[n:]
    final_list = []

    for index in range(len(first_half)):
        final_list.append(first_half[index])
        final_list.append(last_half[index])

    return final_list
Enter fullscreen mode Exit fullscreen mode

We could also iterate through the lists simultaneously by using the zip function. And append the items in one call, instead of two lines:

def shuffle(nums, n):
    first_half = nums[:n]
    last_half = nums[n:]
    final_list = []

    for first, last in zip(first_half, last_half):
        final_list.extend((first, last))

    return final_list
Enter fullscreen mode Exit fullscreen mode

Resources

Top comments (1)

Collapse
jpantunes profile image
JP Antunes

Not sure if this is idiomatic Python but we can do it in O(n) space and O(log(n)) time ... I think ... :-)

def shuffle(nums, n):
    final_list = []
    for idx in range(n):
        final_list.append(nums[idx])
        final_list.append(nums[n + idx])
    return final_list

🌚 Browsing with dark mode makes you a better developer.

It's a scientific fact.