Skip to content

ORIGINAL CODING QUESTION

Longest focused practice window

Each activity is labeled by an integer topic ID. Find the longest contiguous window containing at most k distinct topics.

Open practice workspace

Original exercise · medium. Editorial role relevance does not imply a company has asked this question.

Input and output

n, then n topic IDs, then k. Print the maximum window length.

Constraints

1 ≤ n ≤ 10,000; 0 ≤ k ≤ n; -100,000 ≤ topic ID ≤ 100,000.

Example 1

Input

6
1 2 1 3 3 2
2

Output

3

The window 3, 3, 2 has length 3; no length-4 window qualifies.

Example 2

Input

4
7 7 7 7
0

Output

0

No nonempty window can contain zero distinct topics.

Explain your approach

Explain your time and auxiliary space complexity. Which input makes your algorithm work hardest?

Private grading inputs, expected outputs and canonical reference implementations are withheld. Authored expected outputs were cross-checked with independent reference oracles; compiler/runtime behavior still needs a verified execution provider.

Hint 1

A valid window can expand until its distinct-topic count exceeds k.

Hint 2

Maintain topic frequencies and move the left boundary until the window is valid.

Hint 3

Remove a topic from the frequency map only when its count becomes zero.

Practice this question

Save your work privately, explain decisions and return to your revision queue.

Open practice workspaceBrowse the question library →