Skip to content

ORIGINAL CODING QUESTION

Exactly k topic windows

Count nonempty contiguous segments containing exactly k distinct values.

Open practice workspace

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

Input and output

n, then n topic IDs, then k.

Constraints

1 ≤ n ≤ 200; -100 ≤ ID ≤ 100; 0 ≤ k ≤ n.

Example 1

Input

5 1 2 1 2 3 2

Output

7

Seven segments contain exactly two topics.

Example 2

Input

3 1 1 1 0

Output

0

No nonempty segment contains zero 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

Counting at most k is often simpler than exactly k.

Hint 2

Exactly k equals atMost(k) minus atMost(k-1).

Hint 3

A valid at-most window contributes right-left+1 ending segments.

Practice this question

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

Open practice workspaceBrowse the question library →