The sliding window algorithm helps you efficiently process parts of data step-by-step without repeating work. It saves time by moving a 'window' over data instead of starting fresh each time.
Sliding window algorithm in Rest API
class SlidingWindow: def __init__(self, size): self.size = size self.window = [] def add(self, value): if len(self.window) == self.size: self.window.pop(0) # Remove oldest value self.window.append(value) def get_window(self): return self.window
This class keeps a fixed-size window of the most recent values.
When adding a new value, it removes the oldest if the window is full.
sw = SlidingWindow(3) sw.add(1) sw.add(2) sw.add(3) print(sw.get_window()) # Output: [1, 2, 3]
sw.add(4) print(sw.get_window()) # Output: [2, 3, 4]
empty_sw = SlidingWindow(2) print(empty_sw.get_window()) # Output: []
single_sw = SlidingWindow(1) single_sw.add(10) print(single_sw.get_window()) # Output: [10] single_sw.add(20) print(single_sw.get_window()) # Output: [20]
This program shows how the sliding window moves as new values are added. It starts empty, then fills up to size 3, and slides forward by removing the oldest value each time a new one is added.
class SlidingWindow: def __init__(self, size): self.size = size self.window = [] def add(self, value): if len(self.window) == self.size: self.window.pop(0) # Remove oldest value self.window.append(value) def get_window(self): return self.window # Create a sliding window of size 3 sliding_window = SlidingWindow(3) # Add values and print window each time print('Initial window:', sliding_window.get_window()) values_to_add = [5, 10, 15, 20, 25] for value in values_to_add: sliding_window.add(value) print(f'Window after adding {value}:', sliding_window.get_window())
Time complexity of adding a value is O(1) because removing and appending are fast operations.
Space complexity is O(window size) since we only store a fixed number of elements.
A common mistake is forgetting to remove the oldest element when the window is full, which makes the window grow indefinitely.
Use sliding window when you want to process continuous chunks of data efficiently instead of recalculating from scratch.
The sliding window algorithm helps process data in fixed-size chunks efficiently.
It moves forward by removing the oldest data and adding new data.
This saves time and memory compared to recalculating over the entire data repeatedly.