Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to count number of valid pairs from a list of numbers, where pair sum is odd in Python
Suppose we have a list of positive numbers, we have to find the number of valid pairs of indices (i, j), where i < j, and nums[i] + nums[j] is an odd number.
An important mathematical property: the sum of two numbers is odd only when one number is even and the other is odd. This means we need to count pairs where one element is even and another is odd.
So, if the input is like [5, 4, 6], then the output will be 2, as two pairs are [5,4] and [5,6], whose sums are odd.
Algorithm
To solve this, we will follow these steps ?
- Count the number of even numbers in the list
- Count the number of odd numbers in the list
- Return the product of even count and odd count
Using List Comprehension
We can separate even and odd numbers using list comprehension ?
class Solution:
def solve(self, nums):
even_numbers = [i for i in nums if i % 2 == 0]
odd_numbers = [i for i in nums if i % 2 == 1]
return len(even_numbers) * len(odd_numbers)
nums = [5, 4, 6]
ob = Solution()
print(ob.solve(nums))
2
Optimized Approach
Instead of creating separate lists, we can just count even numbers and calculate odd count ?
def count_odd_sum_pairs(nums):
even_count = sum(1 for num in nums if num % 2 == 0)
odd_count = len(nums) - even_count
return even_count * odd_count
# Test with different examples
test_cases = [
[5, 4, 6],
[1, 3, 5], # All odd numbers
[2, 4, 6], # All even numbers
[1, 2, 3, 4, 5]
]
for nums in test_cases:
result = count_odd_sum_pairs(nums)
print(f"Input: {nums}, Pairs with odd sum: {result}")
Input: [5, 4, 6], Pairs with odd sum: 2 Input: [1, 3, 5], Pairs with odd sum: 0 Input: [2, 4, 6], Pairs with odd sum: 0 Input: [1, 2, 3, 4, 5], Pairs with odd sum: 6
How It Works
The algorithm works because:
- Even + Even = Even (not counted)
- Odd + Odd = Even (not counted)
- Even + Odd = Odd (counted)
Each even number can pair with every odd number to form a valid pair. So if we have m even numbers and n odd numbers, the total valid pairs will be m × n.
Time and Space Complexity
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| List Comprehension | O(n) | O(n) |
| Optimized Counting | O(n) | O(1) |
Conclusion
Count even and odd numbers separately, then multiply their counts to get valid pairs with odd sums. The optimized approach uses O(1) space by avoiding intermediate lists.
