DSAHashingSliding window

Distinct in Window Visualizer

What is Distinct Count in a Window

Slide a window of size k across the array and report how many unique values sit inside it. A frequency map is the window’s memory: increment the entering value, decrement the leaving value, and delete a key when its count hits 0. The answer each time is len(freq).

  • Enter, then maybe leave: after index k-1 every step both adds and removes one element.
  • Delete on zero: a key with count 0 is no longer in the window.
  • O(n) total: each index enters once and leaves once.

How this visualizer works

Array 1, 2, 1, 3, 4, 2, 3, k = 4. Windows produce distinct counts 3, 4, 4, 3.

Interactive trace

hash_table.state

Input
Hash table
Current look-up
Match / window
Stored entry

current_action

Load an input, then press Play or Step.

live_trace.py

1def distinctInWindow(arr, k):
2freq, out = {}, []
3for i, x in enumerate(arr):
4freq[x] = freq.get(x,0)+1
5if i >= k:
6old = arr[i-k]; freq[old] -= 1
7if freq[old] == 0: del freq[old]
8if i >= k-1: out.append(len(freq))
9return out

stdout — decision log

// each hash probe is recorded here
Speed Ready

Pseudocode & Complexity

idea.txt

1def distinctInWindow(arr, k):
2freq, out = {}, []
3for i, x in enumerate(arr):
4freq[x] = freq.get(x,0)+1
5if i >= k:
6old = arr[i-k]; freq[old] -= 1
7if freq[old] == 0: del freq[old]
8if i >= k-1: out.append(len(freq))
9return out

complexity.md

OperationTime
Each enter / leaveO(1) expected
Full scanO(n)
SpaceO(n)

Python implementation

solution.py

1def distinctInWindow(arr, k):
2 freq, out = {}, []
3 for i, x in enumerate(arr):
4 freq[x] = freq.get(x, 0) + 1
5 if i >= k:
6 old = arr[i - k]
7 freq[old] -= 1
8 if freq[old] == 0:
9 del freq[old]
10 if i >= k - 1:
11 out.append(len(freq))
12 return out