Skip to main content

Count Odd Even

Problem​

Given an array A[] of N elements. The task is to return the count of the number of odd and even elements in the array.

Examples:​

Example 1:

Input:
N = 5
A[] = 1 2 3 4 5
Output:
3 2
Explanation:
There are 3 odd elements (1, 3, 5) and 2 even elements (2 and 4).

Your task:​

Your task is to complete the function countOddEven() which should return the count of odd and even elements of the array.

  • Expected Time Complexity: O(N)O(N)
  • Expected Auxiliary Space: O(1)O(1)

Constraints:​

  • 1<=N<=1061<=N<=10^6
  • 1<=Aj<=1061<=A_j<=10^6

Solution​

Python​

def countOddEven(self, arr, n):
odd, even = 0,0
for i in range(0, n):
if arr[i]%2==0:
even+=1
else:
odd+=1
return odd, even

Java​

public int[] countOddEven(int[] arr, int n) {
int odd = 0, even = 0;
for (int i = 0; i < n; i++) {
if (arr[i] % 2 == 0) {
even++;
} else {
odd++;
}
}
int[] result = { odd, even };
return result;
}

C++​

vector<int> countOddEven(int arr[], int sizeof_array) {
int odd = 0, even = 0;
for (int i = 0; i < sizeof_array; i++) {
if (arr[i] % 2 == 0) {
even++;
} else {
odd++;
}
}
vector<int> result = { odd, even };
return result;
}

C​

void countOddEven(int arr[], int sizeof_array, int *odd, int *even) {
*odd = 0;
*even = 0;
for (int i = 0; i < sizeof_array; i++) {
if (arr[i] % 2 == 0) {
(*even)++;
} else {
(*odd)++;
}
}
}
  • Time Complexity: O(N)O(N)
  • Auxiliary Space: O(1)O(1)