BackeasyArraysPaytm

Partition Even Odd Solution

Problem Statement

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.

Example 1
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]

Example 2
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
Live Compiler1 Free Run Available
Loading Editor...
Test Cases & Output
Click "Run" to test your 1 free compile trial!

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free

Partition Even Odd — Problem Statement & Solution Guide

ArraysEasyTwo Pointers
TimeO(n)
|
SpaceO(n)

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

Example 1

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]

Example 2

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

JavaScript Solution
Time: O(n)
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); 
   }

Asked in Top Tech Interviews

Paytm

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.