Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Sliding window

Distinct values in every window

Medium · Target 15 minutes · Sliding window· Type asked at

Given an array nums and a window length k, return an array whose entry i is the number of distinct values in nums[i .. i + k − 1].

Examples

InputOutputWhy
nums = [1,2,1,3,4,2,3], k = 4[3, 4, 4, 3]{1,2,3}, {1,2,3,4}, {1,2,3,4}, {2,3,4}.
nums = [4,4,4], k = 2[1, 1]Every window holds one value.
nums = [1,2,3], k = 1[1, 1, 1]

Constraints

  • 1 ≤ k ≤ n ≤ 10⁵
  • −10⁹ ≤ nums[i] ≤ 10⁹

Hints

Hint 1

Rebuilding a set for each window is O(nk). Only two elements change between windows.

Hint 2

Why is a set not enough? Removing the leaving value is wrong if another copy is still inside.

Hint 3

Keep a map from value to its count in the window; delete a key when its count reaches 0. The map's size is the answer.

Where people lose marks

  • Using a set and removing the leaving value even when another copy remains inside.
  • Leaving keys with count 0 in the map, so its size overstates the answer.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.