problems / 134

The Tasting Flight

medium two-pointers sliding-window hashing arrays 1000 ms · 256 MB

The Tasting Flight

Sommelier Alice keeps n open bottles on one long shelf, numbered 1 to n from left to right. Each bottle carries a label with the code of its grape variety; bottle i has variety c_i. Several bottles may share a variety, and bottles of the same variety need not stand next to each other.

For tonight's guests Alice pours a flight: she picks two positions l ≤ r and pours one glass from every bottle l, l+1, …, r, without skipping any bottle in between. A flight is balanced if the glasses in it come from exactly K different varieties (how many glasses each variety contributes does not matter).

Two flights are different if they start or end at a different bottle, even if they happen to contain the same varieties. How many different balanced flights can Alice pour?

Input

The first line contains two integers n and K (1 ≤ K ≤ n ≤ 2·10^5).

The second line contains n integers c_1, c_2, …, c_n (1 ≤ c_i ≤ 10^9), the variety codes of the bottles from left to right.

Output

Print one integer: the number of pairs (l, r) with 1 ≤ l ≤ r ≤ n such that bottles l through r contain exactly K distinct varieties. Print 0 if there are none. The answer may not fit in a 32-bit integer.

Notes

In the first example the shelf is 1 2 1 2 3 and K = 2. The balanced flights are bottles 1–2, 1–3, 1–4, 2–3, 2–4, 3–4 and 4–5: seven in total. Flights such as 3–5 contain three varieties and do not count.

In the second example only one variety exists on the shelf, so no flight can contain three.

Example 1

Input

5 2
1 2 1 2 3

Output

7

Example 2

Input

4 3
7 7 7 7

Output

0

Hints · reveal one at a time if you're stuck

Hint 1

You are counting subarrays with exactly K distinct values. Which is easier to count with a sliding window, subarrays with at most K distinct values, or exactly K? Could the exact count be built from the easier kind?

Hint 2

For a fixed right end, the number of distinct values in a window only grows as the left end moves left, so the valid left ends form a range found with two pointers and a frequency table. Compress the codes first, since they can be as large as 10^9.

Hint 3

Count subarrays with at most k distinct values in linear time with a sliding window, then combine the count for K with the count for K minus one. Use 64-bit counters, because all flights of one variety can number about 2 times 10^10.

report an issue Prefer your own editor? sooks prep 134 (CLI)
Sign in to run code

Run your code on the examples, or submit it against every test.