Partition Even Odd — Problem Statement & Solution Guide
Problem Description
You are given an array of integers nums. Reorder the array such that all elements at even indices come before all elements at odd indices, maintaining their original order within their respective groups.
Examples
Input
[1, 2, 3, 4, 5]
Output
[1, 3, 5, 2, 4]
Explanation: Step-by-step: with input [1, 2, 3, 4, 5], we first separate the elements at even indices (1, 3, 5) and odd indices (2, 4), then combine them, giving output [1, 3, 5, 2, 4]
Input
[5, 4, 3, 2, 1]
Output
[5, 3, 1, 4, 2]
Explanation: Step-by-step: with input [5, 4, 3, 2, 1], we first separate the elements at even indices (5, 3, 1) and odd indices (4, 2), then combine them, giving output [5, 3, 1, 4, 2]
Constraints
- 1 <= n <= 5000
- 0 <= arr[i] <= 5000
Optimal Approach & Strategy
Two pointers. Left pointer finds odds, right pointer finds evens. Swap them when found. Time O(N), Space O(1).
Brute Force Approach
Create a new array. Iterate twice: first for evens, then for odds. Space O(N).
Verified Code Solutions
function solution(nums) {
let even = [], odd = [];
for (let i = 0; i < nums.length; i++) {
if (i % 2 === 0) {
even.push(nums[i]);
} else {
odd.push(nums[i]);
}
}
return even.concat(odd);
}class Solution {
public:
vector<int> solution(vector<int>& nums) {
vector<int> even, odd;
for (int i = 0; i < nums.size(); i++) {
if (i % 2 == 0) {
even.push_back(nums[i]);
} else {
odd.push_back(nums[i]);
}
}
even.insert(even.end(), odd.begin(), odd.end());
return even;
}
};class Solution {
public int[] solution(int[] nums) {
int[] even = new int[(nums.length + 1) / 2];
int[] odd = new int[nums.length / 2];
int evenIndex = 0, oddIndex = 0;
for (int i = 0; i < nums.length; i++) {
if (i % 2 == 0) {
even[evenIndex++] = nums[i];
} else {
odd[oddIndex++] = nums[i];
}
}
int[] result = new int[nums.length];
System.arraycopy(even, 0, result, 0, even.length);
System.arraycopy(odd, 0, result, even.length, odd.length);
return result;
}
}def solution(nums):
even = [nums[i] for i in range(len(nums)) if i % 2 == 0]
odd = [nums[i] for i in range(len(nums)) if i % 2 != 0]
return even + oddfunction solution(nums) {
let even = [], odd = [];
for (let i = 0; i < nums.length; i++) {
if (i % 2 === 0) {
even.push(nums[i]);
} else {
odd.push(nums[i]);
}
}
return even.concat(odd);
}Asked in Top Tech Interviews
Solve in Interative Editor
Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.