Leetcode #2107: Number of Unique Flavors After Sharing K Candies
In this guide, we solve Leetcode #2107 Number of Unique Flavors After Sharing K Candies in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
You are given a 0-indexed integer array candies, where candies[i] represents the flavor of the ith candy. Your mom wants you to share these candies with your little sister by giving her k consecutive candies, but you want to keep as many flavors of candies as possible.
Quick Facts
- Difficulty: Medium
- Premium: Yes
- Tags: Array, Hash Table, Sliding Window
Intuition
Fast membership checks and value lookups are the heart of this problem, which makes a hash map the natural choice.
By storing what we have already seen (or counts/indexes), we can answer the question in one pass without backtracking.
Approach
Scan the input once, using the map to detect when the condition is satisfied and to update state as you go.
This keeps the solution linear while remaining easy to explain in an interview setting.
Steps:
- Initialize a hash map for seen items or counts.
- Iterate through the input, querying/updating the map.
- Return the first valid result or the final computed value.
Example
Input: candies = [1,2,2,3,4,3], k = 3
Output: 3
Explanation:
Give the candies in the range [1, 3] (inclusive) with flavors [2,2,3].
You can eat candies with flavors [1,4,3].
There are 3 unique flavors, so return 3.
Python Solution
class Solution:
def shareCandies(self, candies: List[int], k: int) -> int:
cnt = Counter(candies[k:])
ans = len(cnt)
for i in range(k, len(candies)):
cnt[candies[i - k]] += 1
cnt[candies[i]] -= 1
if cnt[candies[i]] == 0:
cnt.pop(candies[i])
ans = max(ans, len(cnt))
return ans
Complexity
The time complexity is , and the space complexity is . The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.