← All problems

Sliding Window Median Filter

Hard · Sequential · SystemVerilog

Design a streaming sliding-window median filter that accepts one DATA_W-bit sample per cycle and outputs the median of the WIN most-recent samples.

**Shift register and fill count**

The module maintains an internal shift register of depth WIN. On each rising clock edge where {valid_in} is high, {data_in} is shifted into the register: the newest sample occupies position $0$, all older samples shift up by one position, and the oldest sample is discarded once the register is full. When {valid_in} is low, the shift register holds its current values without change.

An internal fill counter tracks how many samples have been accepted since reset. It increments by one on every cycle where {valid_in} is high, up to a maximum of WIN, and does not wrap.

**Median computation**

On each cycle where {valid_in} is high and the window is full (fill count $\geq$ WIN), the module sorts the WIN entries of the shift register and drives {median_out} with the element at the middle index $\lfloor WIN/2 \rfloor$ ($0$-indexed from the smallest). WIN is always odd, so the median is unambiguous. The sorted order and median are registered: {median_out} is updated on the rising clock edge, so the output reflects the window contents that were present when {valid_in} was asserted.

Open this challenge in the editor →