Leetcode 2341. Maximum Number of Pairs in Array
You are given a 0-indexed integer array nums
. In one operation, you may do the following:
nums
that are equal.nums
, forming a pair.The operation is done repeatedly until no more pairs can be formed.
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 all possible pairs are formed.
nums
is empty?
A: If nums
is empty, the result should be [0, 0]
because no pairs can be formed and there are no leftover elements.HashMap
to count the frequency of each integer in the array.count // 2
).count % 2
).import java.util.HashMap;
import java.util.Map;
public class MaximumNumberOfPairs {
public int[] numberOfPairs(int[] nums) {
Map<Integer, Integer> countMap = new HashMap<>();
// Counting frequency of each number
for (int num : nums) {
countMap.put(num, countMap.getOrDefault(num, 0) + 1);
}
int pairs = 0;
int leftovers = 0;
// Calculating pairs and leftovers
for (int count : countMap.values()) {
pairs += count / 2;
leftovers += count % 2;
}
return new int[] { pairs, leftovers };
}
public static void main(String[] args) {
MaximumNumberOfPairs solver = new MaximumNumberOfPairs();
int[] nums1 = {1,2,3,4,5,6};
int[] nums2 = {1,1,2,2,3,3};
int[] nums3 = {1,1,1,1,1};
// Testing the function
System.out.println(Arrays.toString(solver.numberOfPairs(nums1))); // Output: [0, 6]
System.out.println(Arrays.toString(solver.numberOfPairs(nums2))); // Output: [3, 0]
System.out.println(Arrays.toString(solver.numberOfPairs(nums3))); // Output: [2, 1]
}
}
nums
. We are iterating through the array once to populate the frequency map and then iterating through the map which contains at most n unique keys.nums
, in the worst case, the map might have n
entries if all elements are unique.This solution ensures we count and process the elements effectively while maintaining an efficient runtime and memory usage.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?