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 number have occurred twice.
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
nums[i] := 0,
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))
Input
[8, 9, 9, 8, 5, 5]
Output
True