Problem Description
Given an array of integers, determine the number of "good pairs". A pair (i, j) is considered good if nums[i] equals nums[j] and i < j.
Key Insights
- Use counting to determine how many times each number appears.
- For every occurrence of a number, the number of good pairs contributed by that occurrence is the count of that number seen so far.
- A hash table is ideal for tracking frequencies quickly.
- The pair counting can be done in one pass through the array.
Space and Time Complexity
Time Complexity: O(n) where n is the length of the input array. Space Complexity: O(n) in the worst case due to the frequency hash table.
Solution
We utilize a hash table (or dictionary) to map each number to its frequency of occurrence as we iterate through the list. Each time we encounter a number, we add its current frequency (which represents the number of times it has appeared before) to the overall count of good pairs. Then, we increment its frequency in the hash table. This method counts the pairs in a single pass, making the solution efficient in both time and space.