Skip to the code
cf.
+50 XP

#141 Sessions With Exactly k Pages

hard

An analytics tool records the page id of every page view in a visit, in order, in views. The team wants to know how many slices of the visit (runs of neighboring views) touch exactly k different pages.

Write countExactPages(views, k) that returns the number of non-empty runs of neighboring views that contain exactly k distinct page ids.

Example 1

Input: views = [1,2,1,2,3], k = 2
Output: 7

[1,2], [2,1], [1,2], [2,3], [1,2,1], [2,1,2], [1,2,1,2].

Example 2

Input: views = [1,2,1,3,4], k = 3
Output: 3

[1,2,1,3], [2,1,3], and [1,3,4].

Constraints

  • 0 <= views.length <= 20000
  • 1 <= views[i] <= views.length
  • 1 <= k <= views.length (or k = 1 when views is empty)
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).