This is a premium problem. We're working on making it available for free soon.
Use these hints if you're stuck. Try solving on your own first.
For every group of k consecutive candies, count the number of unique flavors not inside that group. Return the largest number of unique flavors.
When calculating an adjacent group of k consecutive candies, can you use some of your previous calculations?
Use a sliding window where the window is the group of k consecutive candies you are sharing. Use a hash map to store the number of candies of each type you can keep.
Solutions for this premium problem will be available for free soon.
Browse Free ProblemsWatch expert explanations and walkthroughs
Practice problems asked by these companies to ace your technical interviews.
Explore More ProblemsJot down your thoughts, approach, and key learnings
The sliding window works well because the candies given away must be a contiguous segment of length k. Instead of recalculating frequencies for every possible segment, the window updates counts incrementally as elements enter and leave the window.
Problems involving sliding windows, frequency maps, and unique element counting are common in FAANG-style interviews. While the exact problem may vary, the underlying techniques tested here are frequently used in real coding interviews.
A hash map (or dictionary) is ideal for storing the frequency of each candy flavor. It helps efficiently track when a flavor is completely removed inside the sliding window and when it reappears as the window moves.
The optimal approach uses a sliding window combined with a hash map to track flavor frequencies. By sliding a window of size k across the array, you can simulate giving away k consecutive candies and compute how many unique flavors remain. This allows the solution to run in linear time.