16. Separate Even and Odd Numbers
Given an array of integers, create two collections containing the even and odd numbers separately.
How It Works & Algorithmic Design
Traverse the input once:
- Create an empty collection for even numbers.
- Create an empty collection for odd numbers.
- For every value, use
value % 2to determine its category. - Add the value to the corresponding collection.
- 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.