#1470
Shuffle the Array
EasyApproaches
💡
Intuition
Time O(n²)Space O(1)
The brute-force approach involves creating a new array and manually inserting elements from the two halves of the original array. This is simple but inefficient as it requires multiple iterations.
⚙️
Algorithm
3 steps- 1Step 1: Initialize an empty array result of size 2n.
- 2Step 2: Iterate through the first half of nums and the second half, inserting elements alternately into result.
- 3Step 3: Return the result array.
solution.py6 lines
1def shuffle(nums, n):
2 result = []
3 for i in range(n):
4 result.append(nums[i])
5 result.append(nums[i + n])
6 return resultℹ
Complexity note: The time complexity is O(n²) because of the repeated appending in a loop, which can lead to multiple iterations over the array.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.