#2341
Maximum Number of Pairs in Array
EasyArrayHash TableCountingHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses a frequency count to determine how many pairs can be formed. By counting how many times each number appears, we can easily calculate the number of pairs and leftovers without needing to check each pair explicitly.
⚙️
Algorithm
5 steps- 1Step 1: Create a frequency array to count occurrences of each number in nums.
- 2Step 2: Iterate through the frequency array to calculate pairs and leftovers.
- 3Step 3: For each number, the number of pairs is frequency divided by 2, and leftovers are frequency modulo 2.
- 4Step 4: Sum the pairs and calculate the total leftovers.
- 5Step 5: Return the total pairs and leftovers.
solution.py12 lines
1# Full working Python code
2
3def maxPairs(nums):
4 freq = [0] * 101
5 for num in nums:
6 freq[num] += 1
7 pairs = 0
8 leftovers = 0
9 for count in freq:
10 pairs += count // 2
11 leftovers += count % 2
12 return [pairs, leftovers]ℹ
Complexity note: The time complexity is O(n) because we only iterate through the array a couple of times. The space complexity is O(n) due to the frequency array, which is fixed at size 101.
- 1Counting frequencies helps in determining pairs efficiently.
- 2Pairs can be formed from even counts, and leftovers from odd counts.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.