Skip to content
MediumSliding WindowAI interview only

Number Of Unique Flavors After Sharing K Candies

Asked atamazongooglemeta

01 · Problem

You are given an integer array candies, where candies[i] is the flavor id of the i-th candy, and an integer k.

You must give away exactly k consecutive candies (a contiguous subarray of length k) and keep all the rest. Return the maximum number of distinct flavors among the candies you keep.

If k = 0 you keep every candy; if k equals the array length you keep nothing and the answer is 0.

02 · Examples

Example 01
Input
candies = [5,1,5,2,7,1], k = 2
Output
4

Give away indices 0-1 = [5,1]. You keep [5,2,7,1], which still has all 4 flavors.

Example 02
Input
candies = [2,2,2,2,3,3], k = 2
Output
2

Giving away any 2 consecutive candies still leaves at least one 2 and one 3, e.g. give away [2,2] at indices 0-1 and keep flavors {2,3}.

Example 03
Input
candies = [2,4,5], k = 0
Output
3

Nothing is given away, so all 3 flavors are kept.

03 · Constraints

  • 011 <= candies.length <= 105
  • 021 <= candies[i] <= 105
  • 030 <= k <= candies.length

04 · Optimal complexity

Time
O(n)
Space
O(n)
05 · Two ways to work on it

Practice it alone or rehearse it as an interview.

Practice Mode gives you an editor and test runs, nothing else. AI Interview Mode puts a voice interviewer on the other side, adds a clock, and ends with a scored summary of the round.