Problem
Given an array of integersnums, return the number of good pairs.
A pair (i, j) is called good if nums[i] == nums[j] and i < j.
Examples
Constraints
- 1 <= nums.length <= 100
- 1 <= nums[i] <= 100
Documentation Index
Fetch the complete documentation index at: /llms.txt
Use this file to discover all available pages before exploring further.
Tested Python solution for LeetCode 1512 with 16 pytest cases. Generate a practice environment with lcpy.
lcpy gen -n 1512 # by problem number
lcpy gen -s number_of_good_pairs # by problem name
nums, return the number of good pairs.
A pair (i, j) is called good if nums[i] == nums[j] and i < j.
Input: nums = [1,2,3,1,1,3]
Output: 4
Input: nums = [1,1,1,1]
Output: 6
Input: nums = [1,2,3]
Output: 0
class Solution:
# Time: O(n)
# Space: O(n)
def num_identical_pairs(self, nums: list[int]) -> int:
counts: dict[int, int] = {}
result = 0
for num in nums:
seen = counts.get(num, 0)
result += seen
counts[num] = seen + 1
return result
| Time | Space |
|---|---|
| O(n) | O(n) |