LeetCode 1470: Shuffle the Array Solution

Master LeetCode problem 1470 (Shuffle the Array), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1470. Shuffle the Array

Easy

Problem Explanation

Explanation

To shuffle the array in the required form, we can iterate through the array and construct the shuffled array by interleaving the elements from the first half and the second half of the input array. We can achieve this by iterating over the input array and appending the elements at the corresponding indices in the shuffled array.

  1. Initialize an empty array to store the shuffled elements.
  2. Iterate over the input array from index 0 to n (exclusive) and append nums[i] and nums[i+n] to the shuffled array.
  3. Return the shuffled array as the result.

Time Complexity: O(n) where n is the number of elements in the input array nums. Space Complexity: O(n) where n is the number of elements in the input array nums.

Solution Code

class Solution {
    public int[] shuffle(int[] nums, int n) {
        int[] shuffled = new int[2 * n];
        for (int i = 0; i < n; i++) {
            shuffled[2*i] = nums[i];
            shuffled[2*i + 1] = nums[i + n];
        }
        return shuffled;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1470 (Shuffle the Array)?

This page provides optimized solutions for LeetCode problem 1470 (Shuffle the Array) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1470 (Shuffle the Array)?

The time complexity for LeetCode 1470 (Shuffle the Array) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1470 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1470 in Java, C++, or Python.

Back to LeetCode Solutions