You have an even number of candies. candyType[i] is the type of candy i, and two candies of the same type count as the same kind.
You may eat exactly half of the candies and want as much variety as possible. Return the largest number of different types you can eat.
Example 1
Input: candyType = [2, 9, 2, 5, 9, 1] Output: 3 Why: 4 types exist, but only 3 candies may be eaten
2 more examples and the constraints
Example 2
Input: candyType = [4, 8, 4, 4, 8, 4, 8, 4] Output: 2 Why: 4 candies may be eaten, but there are only 2 types
Example 3
Input: candyType = [−3, 7] Output: 1 Why: only one candy may be eaten
Constraints
- 2 ≤ length of candyType ≤ 10,000, and the length is even
- −100,000 ≤ candyType[i] ≤ 100,000
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Sort and count typesO(n log n)
- Hash set of typesO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 10,000 candies | Verdict |
|---|---|---|---|
| Sort and count types | O(n log n) | Fine; extra sort | |
| Hash set of types | O(n) | Best; one pass |
n = number of candies.
Edge cases to test
- Every candy is the same type. [6, 6, 6, 6] gives 1, even though 2 candies may be eaten.
- Every candy is a different type. The count limit wins: the answer is n / 2.
- Only two candies. One may be eaten, so the answer is 1.
- Negative types. Types are just labels; −3 and 3 are different types.
Common mistakes
- Returning the number of types without capping it at n / 2.
- Returning n / 2 without checking that enough types exist.
- Counting how often each type appears; only whether it appears matters.
How to talk through it
- 1Clarify. Is n always even? Do equal values mean the same type, and can types be negative?
- 2Find the two limits. You cannot eat more types than exist, and you cannot eat more than n / 2 candies.
- 3Argue it is reachable. Eat one of each type until one limit hits; fill the rest with any candies.
- 4Count types. A hash set gives the number of types in one pass; return min(size, n / 2).
- 5Test out loud. Try all the same type, all different, and a pair of candies.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?