Problem Description
You are given a 0-indexed integer array nums
. In one operation, you may choose two integers in nums
that are equal and remove both integers from nums
, forming a pair. The operation is done on nums
as many times as possible. Return a 0-indexed integer array answer
of size 2 where answer[0]
is the number of pairs that are formed and answer[1]
is the number of leftover integers in nums
after doing the operation as many times as possible.
Key Insights
- Pairs can only be formed using equal integers.
- Counting the occurrences of each integer allows us to determine how many pairs can be formed.
- Any leftover integers will be the total count of integers minus twice the number of pairs formed.
Space and Time Complexity
Time Complexity: O(n), where n is the length of the array nums
, because we need to iterate through the array to count occurrences.
Space Complexity: O(1), since the maximum number of unique integers is limited (0 to 100), we can use a fixed-size array for counting.
Solution
To solve the problem, we can use a counting approach. We'll maintain an array (or a hash table) to count the occurrences of each integer in nums
. After counting, we can compute the number of pairs that can be formed by dividing the count of each integer by 2 and summing these values. The leftover integers will be calculated as the total number of integers minus twice the number of pairs formed.