Similar Problems

Similar Problems not available

Shuffle The Array

Companies:

LeetCode:  Shuffle The Array Leetcode Solution

Difficulty: Unknown

Topics: not-available  

Problem Statement:

Given an array nums consisting of 2n elements, return an array consisting of n elements of the original array shuffled in a way where nums[i] and nums[i + n] are shuffled together.

Example:

Input: nums = [2,5,1,3,4,7], n = 3
Output: [2,3,5,4,1,7] 
Explanation: Since n = 3, we have [2,5,1] and [3,4,7]. After shuffling, the array becomes [2,3,5,4,1,7].

Solution: We can solve this problem by iterating through the array and creating a new array where the elements are shuffled together. Below is the step-by-step solution to this problem:

  1. Define an empty array to store the shuffled elements of the given array.
shuffled_arr = []
  1. Initialize two pointers i and j to point to the first and the n+1th element of the given array respectively.
i = 0
j = n
  1. Iterate through the array until i is less than n.
while i < n:
  1. Append the ith and jth element of the given array to the shuffled_arr.
shuffled_arr.append(nums[i])
shuffled_arr.append(nums[j])
  1. Increment both i and j by 1.
i += 1
j += 1
  1. Return the shuffled_arr.
return shuffled_arr

The complete function will look like this:

def shuffle(nums, n):
    shuffled_arr = []
    i = 0
    j = n
    while i < n:
        shuffled_arr.append(nums[i])
        shuffled_arr.append(nums[j])
        i += 1
        j += 1
    return shuffled_arr

Time Complexity: O(n), where n is the length of the given array.

Space Complexity: O(n), where n is the length of the given array.

Solution Implementation

1