Sponsored
Sponsored
This approach utilizes two pointers to iteratively place even and odd numbers at the correct indexes.
One pointer is used to find even numbered indexes and the other one for odd numbered indexes. Traverse through the array, and whenever you find an element not in its correct place, swap it with the correct one using the two pointers.
Time Complexity: O(n) since we may visit each element a couple of times.
Space Complexity: O(1) as the swap is done in-place.
1#include <stdbool.h>
2void sortArrayByParityII(int* nums, int numsSize) {
3 int even = 0, odd = 1;
4 while (even < numsSize && odd < numsSize) {
5 while (even < numsSize && nums[even] % 2 == 0) even += 2;
6 while (odd < numsSize && nums[odd] % 2 == 1) odd += 2;
7 if (even < numsSize && odd < numsSize) {
8 int temp = nums[even];
9 nums[even] = nums[odd];
10 nums[odd] = temp;
11 }
12 }
13}
This C implementation uses two pointers; one for indexing even positions and another for odd positions.
Both pointers step through the array stepping by two positions each time, and they swap the odd-even positioned elements whenever they're misplaced.
This approach involves segregating even and odd numbers into separate lists and then efficiently assembling them at respected places in the resultant array.
Despite potentially not being in-place, this technique simplifies understanding the array content and meets the problem requirements.
Time Complexity: O(n)
Space Complexity: O(n) due to the auxiliary lists for even and odd numbers.
1var sortArrayByParityII = function(nums) {
2
With JavaScript, use filter
to isolate evens and odds. Assembly of the result array is sequential through a basic loop.
This approach constructs a correctly sequenced result array.