Baozi Training Leetcode 1512 solution Number of Good Pairs
Problem Statement
Given an array of integers nums
.
A pair (i,j)
is called good if nums[i]
== nums[j]
and i
< j
.
Return the number of good pairs.
Example 1:
Input: nums = [1,2,3,1,1,3] Output: 4 Explanation: There are 4 good pairs (0,3), (0,4), (3,4), (2,5) 0-indexed.
Example 2:
Input: nums = [1,1,1,1] Output: 6 Explanation: Each pair in the array are good.
Example 3:
Input: nums = [1,2,3] Output: 0
Constraints:
1 <= nums.length <= 100
1 <= nums[i] <= 100
Problem link
Video Tutorial
You can find the detailed video tutorial here
Thought Process
Array is the most basic data structures and common solutions inclue
- Nested for loops O(N^2)
- Sort O(NlgN)
- Use extra space O(N)
This
applies to this problem perfectly. The O(N^2) brute force solution is
naive. We can also use a Map data structure (key is the number, value is
the occurrence count) thus O(N). We can also sort the array and use
this simple formula (also leetcode's hint) to calculate the good number
pair.
Good pairs = N * (N-1) / 2 where N is how many duplicate numbers, this is from combination C(n^2), from n elements pick two
Solutions
Use Map
1 public int numIdenticalPairs(int[] nums) { 2 if (nums == null || nums.length == 0) { 3 return 0; 4 } 5 6 // key: int value; value: number of occurrence 7 Map<Integer, Integer> lookup = new HashMap<>(); 8 int goodPairsCount = 0; 9 for (int i : nums) { 10 if (lookup.containsKey(i)) { 11 goodPairsCount += lookup.get(i); 12 lookup.put(i, lookup.get(i) + 1); 13 } else { 14 lookup.put(i, 1); 15 } 16 } 17 18 return goodPairsCount; 19 }
Time Complexity: O(N), N is the array size
Space Complexity: O(N) since we use extra Map
Sort
1 public int numIdenticalPairsWithSort(int[] nums) { 2 if (nums == null || nums.length == 0) { 3 return 0; 4 } 5 6 Arrays.sort(nums); 7 8 int goodPairsCount = 0; 9 int start = 0; 10 int end = 0; 11 12 while (end < nums.length) { 13 if (nums[end] == nums[start]) { 14 end++; 15 continue; 16 } 17 // if you have n occurrences of a number, the good pair is n*(n-1)/2, Cn^2 18 int delta = end - start; 19 if (delta > 1) { 20 goodPairsCount += delta * (delta - 1) / 2; 21 } 22 start = end; 23 } 24 // handle the case 1, 2, 3, 3, 3 25 if (start != nums.length - 1) { 26 goodPairsCount += (end - start) * (end - start - 1) / 2; 27 } 28 return goodPairsCount; 29 }
Time Complexity: O(NlgN), N is the array size since we sort
Space Complexity: O(1) no extra space is used
References
- None