🚀 AI-Powered Mock Interviews Launching Soon - Join the Waitlist for Early Access

codingmedium

Design a data structure to efficiently manage a sliding window of the last N model predictions, supporting O(1) time complexity for adding new predictions and retrieving the average prediction value within the window. Explain the space complexity of your solution.

Interview

How to structure your answer

To solve this, use a deque to store the sliding window elements and maintain a running sum. When adding a new prediction, append it to the deque and update the sum. If the window exceeds size N, remove the oldest element and subtract it from the sum. The average is computed by dividing the sum by the current number of elements. This ensures O(1) time for both add and average operations. Space complexity is O(N) due to storing up to N elements.

Sample answer

Implement a sliding window using a deque and a running sum. Adding a prediction involves appending to the deque and updating the sum. If the window size exceeds N, remove the oldest element and adjust the sum accordingly. The average is calculated by dividing the sum by the deque's length, achieving O(1) time for both operations. Space complexity is O(N) as the deque stores up to N elements. This approach ensures efficient management of the window and quick average retrieval without iterating through all elements.

Key points to mention

  • • deque/circular buffer data structure
  • • O(1) time for add and average operations
  • • space complexity O(N) for storing window elements

Common mistakes to avoid

  • ✗ Using a list instead of deque for O(1) additions
  • ✗ Forgetting to update running sum when removing elements
  • ✗ Incorrectly calculating average without proper sum tracking