Problem:
Given an array of integers, separate the numbers into two lists:
- One containing all even numbers.
- One containing all odd numbers.
Example
Input: arr = [9, 4, 5, 1, 21, 28]
Output:
Even numbers: [4, 28]
Odd numbers: [9, 5, 1, 21]Algorithm: Iterative Linear Scan (Best for Clarity & Interviews)
Initialize two empty lists: evens and odds.
- Loop through each element in the array.
- For each element: If num % 2 == 0, append to evens. Else, append to odds.
- Return both lists.
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| Iterative Linear Scan | O(n) | O(n) |
| List Comprehension | O(n) | O(n) |
Method 1: Iterative Approach
def odd_even(arr):
evens = []
odds = []
for num in arr:
if num % 2 == 0:
evens.append(num)
else:
odds.append(num)
return evens, odds
# Example usage
arr = [9, 4, 5, 1, 21, 28]
evens, odds = odd_even(arr)
print("Even numbers:", evens) # Output: [4, 28]
print("Odd numbers:", odds) # Output: [9, 5, 1, 21]List Comprehension
arr = [9, 4, 5, 1, 21, 28]
evens = [num for num in arr if num % 2 == 0]
odds = [num for num in arr if num % 2 != 0]
print("Even numbers:", evens) # Output: [4, 28]
print("Odd numbers:", odds) # Output: [9, 5, 1, 21]