-
Notifications
You must be signed in to change notification settings - Fork 258
Good Pairs
Sar Champagne Bielert edited this page Apr 10, 2024
·
4 revisions
Unit 2 Session 2 (Click for link to problem statements)
Understand what the interviewer is asking for by using test cases and questions about the problem.
- Q
- A
Plan the solution with appropriate visualizations and pseudocode.
General Idea: First, find out how many of each element are in the list. Then calculate how many possible pairs can exist for each value, and add these up.
1) First, create a frequency map for the list (
def numIdenticalPairs(nums):
# Frequency map to count occurrences of each number
frequency_map = {}
for num in nums:
if num in frequency_map:
frequency_map[num] += 1
else:
frequency_map[num] = 1
# Count the number of good pairs
good_pairs = 0
for count in frequency_map.values():
good_pairs += count * (count - 1) // 2 # Combination of 2 from n
return good_pairs