Number of Unique Flavors After Sharing K Candies - Problem

You're a candy enthusiast with a collection of various flavored candies! ๐Ÿญ Your mom wants you to share k consecutive candies with your little sister, but being the flavor connoisseur you are, you want to maximize the variety of flavors you get to keep.

Given an array candies where candies[i] represents the flavor of the i-th candy, you need to determine which k consecutive candies to give away so that you retain the maximum number of unique flavors.

Goal: Find the optimal subarray of length k to remove that leaves you with the most diverse flavor collection.

Example: If you have candies [1,2,1,3,4,3,2] and need to share k=3 candies, you could give away [1,3,4] (indices 2-4) and keep flavors [1,2,3,2] which has 3 unique flavors!

Input & Output

example_1.py โ€” Basic Case
$ Input: candies = [1,2,1,3,4,3,2], k = 3
โ€บ Output: 3
๐Ÿ’ก Note: Remove subarray [1,3,4] (indices 2-4) to keep [1,2,3,2] which has 3 unique flavors (1,2,3). This is optimal.
example_2.py โ€” All Same Flavors
$ Input: candies = [1,1,1,1,1], k = 2
โ€บ Output: 1
๐Ÿ’ก Note: All candies have the same flavor, so removing any k=2 consecutive candies leaves us with only 1 unique flavor.
example_3.py โ€” Edge Case
$ Input: candies = [1,2,3], k = 1
โ€บ Output: 2
๐Ÿ’ก Note: Remove any single candy to keep 2 unique flavors. For example, remove [2] to keep [1,3] with 2 unique flavors.

Visualization

Tap to expand
Your Candy CollectionGoal: Give away k consecutive candies while keeping maximum flavor variety๐ŸŽ๐ŸŠ๐Ÿ‡๐Ÿ“๐Ÿ‹๐Ÿ’Give Away (k=3)Keep: ๐ŸŽ๐Ÿ“๐Ÿ‹๐Ÿ’ = 4 unique flavors!
Understanding the Visualization
1
Survey Collection
Count all flavor types in your candy collection
2
Try Each Section
Consider each possible consecutive group of k candies to give away
3
Calculate Remaining
For each section, determine how many unique flavors you'd keep
4
Choose Optimal
Select the section that leaves you with maximum flavor variety
Key Takeaway
๐ŸŽฏ Key Insight: Use sliding window with frequency counting to efficiently try all possible consecutive removals without recalculating everything each time.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n)

Single pass through array with constant time operations for each element

n
2n
โœ“ Linear Growth
Space Complexity
O(n)

Hash maps store at most n unique flavors

n
2n
โšก Linearithmic Space

Constraints

  • 1 โ‰ค candies.length โ‰ค 105
  • 1 โ‰ค candies[i] โ‰ค 105
  • 1 โ‰ค k โ‰ค candies.length
  • All array values are positive integers
Asked in
Google 42 Amazon 35 Meta 28 Microsoft 21
42.6K Views
High Frequency
~18 min Avg. Time
1.3K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen