Even-Odd Separator - Problem

Given an array of integers, separate the even and odd numbers into two different arrays while maintaining their original order.

You need to return a 2D array where:

  • The first sub-array contains all even numbers in their original order
  • The second sub-array contains all odd numbers in their original order

Example: For input [1, 2, 3, 4, 5, 6], return [[2, 4, 6], [1, 3, 5]]

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,2,3,4,5,6]
Output: [[2,4,6],[1,3,5]]
💡 Note: Even numbers [2,4,6] maintain original order, odd numbers [1,3,5] maintain original order
Example 2 — All Even Numbers
$ Input: nums = [2,4,6,8]
Output: [[2,4,6,8],[]]
💡 Note: All numbers are even, so first array contains all elements, second array is empty
Example 3 — Mixed with Negatives
$ Input: nums = [-3,-2,-1,0,1,2]
Output: [[-2,0,2],[-3,-1,1]]
💡 Note: Even numbers include negatives and zero: [-2,0,2], odds: [-3,-1,1]

Constraints

  • 1 ≤ nums.length ≤ 103
  • -106 ≤ nums[i] ≤ 106

Visualization

Tap to expand
INPUTALGORITHMRESULT123456Array: [1,2,3,4,5,6]1Check: num % 22If even: add to evens[]3If odd: add to odds[]4Single pass through arrayEvens Array246Odds Array135[[2,4,6], [1,3,5]]Key Insight:Single pass with modulo check efficiently separates numbers while preserving orderTutorialsPoint - Even-Odd Separator | Single Pass Approach
Asked in
Amazon 25 Microsoft 18 Google 15 Apple 12
24.1K Views
Medium Frequency
~12 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen