Skip to main content

Find Odd an Even Number in Array

Classify an array into even and odd numbers efficiently using the linear scan pattern.

––– views

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.

  1. Loop through each element in the array.
  2. For each element: If num % 2 == 0, append to evens. Else, append to odds.
  3. Return both lists.
ApproachTime ComplexitySpace Complexity
Iterative Linear ScanO(n)O(n)
List ComprehensionO(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]