For an array to be divisible into pairs of equal elements, every distinct value must appear an even number of times. By sorting the array, identical elements become adjacent. We can then scan through and count consecutive runs of equal values. If any run has an odd length, we cannot form valid pairs.
Algorithm
Sort the array.
Iterate through the sorted array, tracking runs of consecutive equal elements.
classSolution:defdivideArray(self, nums: List[int])->bool:
N =len(nums)
nums.sort()
i =0while i < N:
j = i
while j < N and nums[i]== nums[j]:
j +=1if(j - i)%2!=0:returnFalse
i = j
returnTrue
Time & Space Complexity
Time complexity: O(nlogn)
Space complexity: O(1) or O(n) depending on the sorting algorithm.
2. Hash Map
Intuition
We can count the frequency of each element using a hash map. After counting, we check if every element appears an even number of times. If any element has an odd count, it cannot be fully paired, so we return false.
Algorithm
Create a hash map to store the count of each element.
Iterate through the array and increment the count for each element.
classSolution:defdivideArray(self, nums: List[int])->bool:
count ={}for num in nums:if num notin count:
count[num]=0
count[num]+=1for cnt in count.values():if cnt %2==1:returnFalsereturnTrue
Time & Space Complexity
Time complexity: O(n)
Space complexity: O(n)
3. Hash Set
Intuition
Instead of counting all frequencies, we can use a set to track elements with odd occurrences. When we see an element, if it is already in the set (meaning we have seen it an odd number of times), we remove it. If it is not in the set, we add it. At the end, if the set is empty, all elements appeared an even number of times.
Algorithm
Create an empty hash set.
Iterate through each element in the array.
If the element is in the set, remove it (completing a pair).
Otherwise, add it to the set (unpaired element).
After processing all elements, return true if the set is empty, false otherwise.
classSolution:defdivideArray(self, nums: List[int])->bool:
odd_set =set()for num in nums:if num notin odd_set:
odd_set.add(num)else:
odd_set.remove(num)returnnotlen(odd_set)