array and hashmap October 26, 2022

Maximum number of pairs in array

Time O(n) Space O(n) Open original problem

We will count the frequency of each number in the array. Then we iterate the frequency map and count the number of pairs.

class Solution:
    def numberOfPairs(self, nums: List[int]) -> List[int]:
        count = collections.Counter(nums)
        res = [0, 0]
        for val in count.values():
            res[0] += val // 2
            res[1] += val % 2
        return res

Time Complexity: O(n)
Space Complexity: O(n)