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 check whether elements frequencies are even or not in Python
Suppose we have a list of elements called nums, we have to check whether all numbers appear even times or not. We have to solve it using constant space.
So, if the input is like nums = [8, 9, 9, 8, 5, 5], then the output will be True, because all numbers have occurred twice.
Algorithm
To solve this, we will follow these steps ?
If size of nums is odd, then return False
Sort the list nums
-
For i in range 1 to size of nums, do:
If nums[i] is same as nums[i - 1], then set nums[i] := 0 and nums[i - 1] := 0
Return true when sum of all elements present in nums is same as 0, otherwise false
Example
Let us see the following implementation to get better understanding ?
def solve(nums):
if len(nums) & 1:
return False
nums.sort()
for i in range(1, len(nums)):
if nums[i] == nums[i - 1]:
nums[i] = nums[i - 1] = 0
return sum(nums) == 0
nums = [8, 9, 9, 8, 5, 5]
print(solve(nums))
The output of the above code is ?
True
How It Works
The algorithm works by first checking if the list has an odd number of elements. If so, it's impossible for all elements to appear an even number of times. Then it sorts the list to group identical elements together. As it iterates through the sorted list, it sets pairs of identical adjacent elements to zero. Finally, if all elements appeared an even number of times, the sum will be zero.
Another Example
Let's test with a case where not all elements appear even times ?
def solve(nums):
if len(nums) & 1:
return False
nums.sort()
for i in range(1, len(nums)):
if nums[i] == nums[i - 1]:
nums[i] = nums[i - 1] = 0
return sum(nums) == 0
# Test with uneven frequencies
nums = [1, 2, 2, 3, 3, 3]
print(solve(nums))
The output of the above code is ?
False
Conclusion
This solution efficiently checks if all elements have even frequencies using constant extra space by sorting and zeroing out pairs. The algorithm returns True only when all elements can be paired up completely.
