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.
1var sortArrayByParityII = function(nums) {
2 let even = 0, odd = 1, n = nums.length;
3 while (even < n && odd < n) {
4 while (even < n && nums[even] % 2 === 0) even += 2;
5 while (odd < n && nums[odd] % 2 === 1) odd += 2;
6 if (even < n && odd < n) {
7 [nums[even], nums[odd]] = [nums[odd], nums[even]];
8 }
9 }
10 return nums;
11};
JavaScript uses destructuring assignment within two pointers to swap the misplaced elements.
Even and odd tracking give efficiency to the swapping procedure.
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.
1class Solution:
2 def sortArrayByParityII(self
This Python method separates evens and odds into different sublists. Then it assembles those lists alternatively filling into the result array.
This approach straightforwardly constructs a properly sequenced result list.