DEV Community

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

Posted on • Originally published at leandrotk.github.io

1

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

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

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

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay