We need to decide if we can split array A into two arrays B and C such that:
Every element of A goes to exactly one of B or C.
F(B) = F(C), where F(S) = number of distinct elements in S.
Key Observations
Let’s define:
d = number of distinct values in A.
multi = number of distinct values that appear at least twice in A.
Important points:
Every distinct value in A must appear in at least one of B or C.
To have F(B) = F(C), the total number of distinct values we can distribute between them must be even, and we must be able to give each side the same count.
A value that appears at least twice can be placed in both B and C simultaneously by putting one occurrence in each.
This increases both F(B) and F(C) by 1 if the value wasn’t present there before.
A value that appears exactly once can be placed only in one of B or C, not both.
So:
Values with frequency ≥ 2: “flexible” – can contribute to both sides.
Values with frequency = 1: “rigid” – can contribute only to one side.
Core Logic
Count:
d = total distinct elements.
multi = number of elements with frequency ≥2.
If no value appears twice (multi = 0):
Every distinct value can only be on one side.
So all distinct values are strictly partitioned between B and C, and the size of the distinct sets on each side will sum to d.
For equality, we need to split them as d2 and d2.
This is only possible if d is even.
So:
If multi = 0, answer is YES iff d is even.
If at least one value appears twice (multi ≥ 1):
We can always use those multi-occurring values to balance the distinct counts between B and C.
Any difference caused by assigning single-occurrence values unevenly can be compensated by assigning a multi-occurrence value to the side with smaller distinct count (giving it a new distinct element) and also to the other side if needed.
It turns out that this always allows a valid partition when multi≥1.
So:
If multi ≥ 1, answer is always YES.
Final Rule:
For each test case:
Compute frequency of each value.
Let:
d = number of distinct values.
multi= count of values with frequency ≥2.
Then:
If multi ≥ 1: print YES.
Else (all frequencies are 1):
If d is even: print YES.
Else: print NO.
Check Against Samples:
A = [1, 2]
Frequencies: 1,1
d = 2,multi = 1, d even → YES.
A = [1, 2, 3]
Frequencies: 1,1,1
d = 3, multi = 0, d odd → NO.
A = [3, 1, 1, 2]
Frequencies: {1:2, 2:1, 3:1}
d = 3, multi = 1 (value 1) → YES.
Pseudocode:
Python code






Comments
Post a Comment