Code Logo

Distribute Candies

Published at23 Jul 2026
Easy 0 views
Like0

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

Example 1
Input
[1,1,2,2,3,3]
Output
3
Explanation

3 distinct types, n/2=3.

Example 2
Input
[1,1,2,3]
Output
2
Explanation

3 distinct, n/2=2 → min(3,2)=2.

Example 3
Input
[1,1,1,1]
Output
1
Explanation

1 distinct, n/2=2 → min(1,2)=1.

Algorithm Flow

Recommendation Algorithm Flow for Distribute Candies
Recommendation Algorithm Flow for Distribute Candies

Solution Approach

Count distinct types with a hash set. Return min(distinct, n/2).

function solution(candies) {
  var set = {};
  for (var i = 0; i < candies.length; i++) set[candies[i]] = true;
  var distinct = Object.keys(set).length;
  return Math.min(distinct, candies.length / 2);
}

Time O(n), Space O(n).

Best Answers

java
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);
    }
}