2206. Divide Array Into Equal Pairs
EasyView on LeetCode
Time: O(n)
Space: O(n)
Advertisement
Intuition
Count pairs with equal elements. For each value, count occurrences - pairs = count*(count-1)/2.
Algorithm
- 1Frequency map. For each value v with count c: pairs += c*(c-1)/2.
Common Pitfalls
- •C(n,2) = n*(n-1)/2 gives number of pairs from n elements.
2206.cs
C#
// Approach: Count occurrences; all counts must be even to form pairs.
// Time: O(n) Space: O(n)
public class Solution
{
public bool DivideArray(int[] nums)
{
int[] count = new int[501];
foreach (var num in nums)
++count[num];
return count.All(c => c % 2 == 0);
}
}Advertisement
Was this solution helpful?