16. Separate Even and Odd Numbers

Difficulty:EasyPattern:Filtering / Array TraversalTime:O(n)Space:O(n)

Given an array of integers, create two collections containing the even and odd numbers separately.

How It Works & Algorithmic Design

Traverse the input once:

  1. Create an empty collection for even numbers.
  2. Create an empty collection for odd numbers.
  3. For every value, use value % 2 to determine its category.
  4. Add the value to the corresponding collection.
  5. Return both collections.

Why This Approach Works Best

Every element is inspected once. Because the output itself can contain up to $n$ elements, the auxiliary/output space is $O(n)$.

Example Walkthrough
Input: [1, 4, 7, 8, 10, 13]
Mixed even and odd values.
Separated Values: Even=[4,8,10] | Odd=[1,7,13]
Each number is placed into exactly one output collection.

Answer: Separate even and odd values

function separateEvenOdd(arr) {
  const even = [];
  const odd = [];

  for (const value of arr) {
    if (value % 2 === 0) even.push(value);
    else odd.push(value);
  }

  return { even, odd };
}
💡 Create two output arrays and classify each number using modulo.
Key Takeaways
  • Modulo provides a simple way to classify even and odd numbers.
  • Every input value is visited exactly once.
  • The output arrays require O(n) space in the worst case.