Skip to content
Search lessons, topics, tests…
Esc

    ↑ ↓ moveEnter openEsc close

    Coding problem

    Count the events in a sliding time window

    MediumAbout 25 minFull AccessLearn it: Queues and Deques in C#: Queue<T>, Two-Stack Queues and Sliding Window Maximum

    The task

    A monitoring dashboard shows how many requests a service received in the last few seconds, and updates the number with every new request.

    Complete the class RecentEvents. The constructor takes the window length window, at least 1. Add(int time) records one event at time and returns how many recorded events, this one included, have a time from time - window + 1 to time, both included. Times are 0 or more and never decrease from one call to the next; several events may share a time. Each RecentEvents object keeps its own events.

    Signature

    public RecentEvents(int window)
    public int Add(int time)

    Examples

    • window 10, then Add(1), Add(5), Add(10), Add(11), Add(20) → 1, 2, 3, 3, 2. At 11 the window is 2 to 11, so the event at 1 has left; at 20 only 11 and 20 are inside.
    • window 1, then Add(7), Add(7), Add(8) → 1, 2, 1. Two events at 7 both count; at 8 they have left.

    Limits: Up to 400,000 calls; the window can be as large as int.MaxValue.

    The tests check: events at the same time, an event exactly a window old, several events leaving at once, a long gap, windows near int.MaxValue, and 400,000 calls with a small and with a large window in time.

    Hints

      Your code

      C#Solution.csLoading the editor…

      Already included: using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Threading; using System.Threading.Tasks;

      public sealed class RecentEvents
      {
          // window: how many time units an event stays in the count (at least 1).
          public RecentEvents(int window)
          {
              throw new NotImplementedException();
          }
      
          // Records an event at time and returns how many recorded events fall in [time - window + 1, time].
          public int Add(int time)
          {
              throw new NotImplementedException();
          }
      }

      This problem comes with TechInterviewNotes Full Access

      Unlock all paid content on TechInterviewNotes.