Sponsored
Sponsored
This approach uses a two-pointer technique to shuffle the array. The first pointer starts at the beginning of the array and represents the x values. The second pointer starts at the middle of the array and represents the y values. By iterating over the array and adding elements from these two pointers alternately to a new list, we can achieve the desired shuffle.
Time Complexity: O(n), where n is half the length of the array. We iterate through the array once.
Space Complexity: O(n), for storing the shuffled result.
#include <vector>
std::vector<int> shuffle(const std::vector<int>& nums, int n) {
std::vector<int> result;
for (int i = 0; i < n; ++i) {
result.push_back(nums[i]);
result.push_back(nums[i + n]);
}
return result;
}
int main() {
std::vector<int> nums = {2, 5, 1, 3, 4, 7};
int n = 3;
std::vector<int> result = shuffle(nums, n);
for (int num : result) {
std::cout << num << " ";
}
return 0;
}
Solve with full IDE support and test cases
In this C++ solution, we define a shuffle function that returns a vector with the shuffled values using the two-pointer technique. The result is then printed in the main function.
An alternate approach is to reorder the array in-place without using additional space. However, given the elements might need to be accessed multiple times, a good understanding of index manipulation and mathematics is required. The complexity to deduce the correct indices for swapping can increase the difficulty.
Time Complexity: O(n^2) in the worst case as the array is shifted multiple times.
Space Complexity: O(1), as the shuffling is done in-place.
1#include <stdio.h>
2
3void shuffleInPlace(int* nums, int n) {
4 int temp, j;
5 for (int i = n; i < 2 * n; i++) {
6 temp = nums[i];
7 for (j = i; j > 2 * (i - n); j -= 2) {
8 nums[j] = nums[j - 1];
9 }
10 nums[j] = temp;
11 }
12}
13
14int main() {
15 int nums[] = {2, 5, 1, 3, 4, 7};
16 int n = 3;
17 shuffleInPlace(nums, n);
18 for (int i = 0; i < 2 * n; i++) {
19 printf("%d ", nums[i]);
20 }
21 return 0;
22}
This C implementation performs in-place reordering by moving each y value to its correct position through a series of swaps.