You are given an integer array of even length representing different types of candies. Each number represents a different type of candy. You need to distribute these candies evenly between your sibling and yourself, meaning each person gets exactly n/2 candies. Return the maximum number of different types of candy your sibling can receive.
The answer is the minimum of two values: the number of distinct candy types (determined using a hash set) and n/2. If there are more distinct types than half the candies, the sibling can only get n/2 at most. If there are fewer distinct types, the sibling can get at most all the distinct types.
For example, candies = [1,1,2,2,3,3] has 3 distinct types. n/2 = 3. Answer is min(3, 3) = 3. Each sibling gets 3 candies, one of each type.
This problem tests understanding of hash sets and the ability to compute the minimum of two values. It is commonly asked in entry-level interviews as a straightforward hash set application.
The key insight is that the sibling cannot receive more than n/2 candies total, nor can they receive more than the number of distinct types available. The hash set efficiently counts distinct types in O(n) time. This problem is often asked as a warm-up before more complex hash set problems.
Example Input & Output
3 distinct types, n/2=3.
3 distinct, n/2=2 → min(3,2)=2.
1 distinct, n/2=2 → min(1,2)=1.
Algorithm Flow

Solution Approach
Count distinct types with a hash set. Return min(distinct, n/2).
Time O(n), Space O(n).
Best Answers
import java.util.*;
class Solution {
public int solution(int[] candies) {
Set<Integer> set = new HashSet<>();
for (int c : candies) set.add(c);
return Math.min(set.size(), candies.length / 2);
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
