Dropped Server Requests Under One-Time Thread Allocation

Medium · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

Implement count_dropped_requests(events: list[int]) -> int to simulate one-shot thread allocation on a server.

An integer array events records server activity in strict chronological order from index 0 to len(events) - 1. At the start of the stream, the server holds 0 idle worker threads. Each entry in events has one of two meanings:

  • Positive integer k (k >= 1): A batch of k new worker threads joins the server's idle pool.
  • -1: A client request arrives at the server:
    • When at least one idle thread is present, the request claims 1 idle thread for good—once assigned, a thread is never recycled back into the pool.
    • When 0 idle threads are present, the request cannot be handled and is immediately dropped.

Capacity added later in the array never retroactively rescues requests that were already dropped at earlier indices. Return the total count of dropped requests across the entire event stream.

Examples

Example 1

Input: events = [2, -1, -1, -1, 1, -1, -1, -1]
Output: 3

The initial batch of 2 threads handles the first two requests, leaving the pool empty when the third request arrives (drop #1). Afterward, 1 thread is added and handles the next request, and the final two requests arrive at an empty pool (drops #2 and #3), totaling 3 dropped requests.

Example 2

Input: events = [-1, 4, -1, -1]
Output: 1

The opening request arrives while the pool is still empty and is dropped. Next, 4 threads join the pool; two of them handle the trailing two requests and 2 threads remain idle.

Example 3

Input: events = [3, -1, 2, -1, -1, -1]
Output: 0

Pool size evolves as 0 -> 3 -> 2 -> 4 -> 3 -> 2 -> 1. Every arriving request finds an idle thread, so 0 requests are dropped.

Constraints

  • 1 <= len(events) <= 10^5
  • Every events[i] is either -1 or an integer satisfying 1 <= events[i] <= 10^9.
  • Total idle threads can accumulate up to 10^14 (above the 32-bit signed maximum 2^31 - 1), so fixed-width languages require a 64-bit integer counter (long long / long), whereas Python int grows automatically.
  • The returned count lies between 0 and len(events) inclusive.

Step-by-step walkthrough

  1. Understand the event stream and rules

    We are given an integer array events representing server activity in chronological order from left to right:

    • event > 0: event new worker threads are added to the free pool.
    • event == -1: an incoming client request arrives.
      • If at least one free thread exists, the request claims 1 thread permanently (the thread never returns).
      • If zero threads are free at that moment, the request is dropped.

    Two rules govern every tricky test case:

    Example 2: events = [-1, 4, -1, -1]
    
      [-1] -> 0 free threads -> DROPPED (#1)
      [ 4] -> +4 free threads (cannot rescue the already-dropped first request!)
      [-1] -> 1 thread consumed permanently -> 3 free threads remain
      [-1] -> 1 thread consumed permanently -> 2 free threads remain
      Total dropped = 1
    
    1. Order matters: Future threads never retroactively serve requests that were already dropped.
    2. Permanent consumption: Once a request takes a thread, that thread is gone forever.
  2. Why summing totals or simulating individual threads fails

    Before writing code, let's rule out two tempting traps:

    1. Comparing totals at the end (max(0, total_requests - total_threads)): On Example 2 ([-1, 4, -1, -1]), there are 3 requests and 4 threads in total, so subtracting totals predicts 0 drops — missing the fact that the first request arrived before the 4 threads existed.
    2. Keeping a list of individual thread objects: Appending "thread" to a list k times when event = k and calling .pop() on -1 obeys the ordering rules, but a single event can have k = 10^9. Looping a billion times for one array element runs out of both time and memory.
  3. Key idea: collapse identical threads into a single counter

    Every free thread is interchangeable — an incoming request only cares how many free threads exist right now, not which specific thread it gets. So we can replace the entire thread pool with a single non-negative integer available_threads:

    • Start with available_threads = 0 and dropped_requests = 0.
    • On a positive batch event: add the whole batch in one step (available_threads += event).
    • On a request -1:
      • If available_threads > 0, decrement available_threads -= 1.
      • Otherwise (available_threads == 0), leave available_threads at 0 and increment dropped_requests += 1. Never let available_threads go below 0, or a dropped request would act like a debt that steals a future thread!

    Watch the number size: With up to 10^5 events of up to 10^9 threads each, available_threads can reach 10^5 * 10^9 = 10^14. That exceeds the maximum 32-bit signed integer (2^31 - 1 ≈ 2.15 * 10^9). Python's int automatically grows to arbitrary precision, while in C++, Java, or Rust you would use a 64-bit long long / long / i64.

  4. Write the single-pass simulation

    Putting those rules into a single loop processes each event in O(1) time and O(1) extra memory:

    from typing import List
    
    
    def count_dropped_requests(events: list[int]) -> int:
        # available_threads: count of unused threads ready right now (0 <= available_threads <= 10^14)
        available_threads = 0
        # dropped_requests: total count of -1 events that arrived when available_threads == 0
        dropped_requests = 0
    
        # Scan strictly left-to-right because later thread batches cannot rescue earlier drops.
        for event in events:
            if event == -1:
                # A request consumes 1 thread permanently if available; otherwise drop immediately
                # without letting available_threads go negative ("borrowing" a future thread).
                if available_threads > 0:
                    available_threads -= 1
                else:
                    dropped_requests += 1
            else:
                # Add the whole batch of k positive threads in O(1) instead of looping k times.
                available_threads += event
    
        return dropped_requests
    
  5. Trace Example 1 and Example 3 step by step

    Let's trace events = [2, -1, -1, -1, 1, -1, -1, -1] (Example 1):

    Step  event  available (before)  Action                   available (after)  dropped
    -------------------------------------------------------------------------------------
     1      2            0           +2 threads added                 2             0
     2     -1            2           request takes 1 thread           1             0
     3     -1            1           request takes 1 thread           0             0
     4     -1            0           no free thread -> DROP           0             1
     5      1            0           +1 thread added                  1             1
     6     -1            1           request takes 1 thread           0             1
     7     -1            0           no free thread -> DROP           0             2
     8     -1            0           no free thread -> DROP           0             3
    

    At the end of the array, dropped_requests is 3, matching Example 1.

    In Example 3 (events = [3, -1, 2, -1, -1, -1]), available_threads moves 0 -> 3 -> 2 -> 4 -> 3 -> 2 -> 1 and dropped_requests stays 0; the unused thread at the end simply remains idle.

  6. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    def count_dropped_requests(events: list[int]) -> int:
        # available_threads: count of unused threads ready right now (0 <= available_threads <= 10^14)
        available_threads = 0
        # dropped_requests: total count of -1 events that arrived when available_threads == 0
        dropped_requests = 0
    
        # Scan strictly left-to-right because later thread batches cannot rescue earlier drops.
        for event in events:
            if event == -1:
                # A request consumes 1 thread permanently if available; otherwise drop immediately
                # without letting available_threads go negative ("borrowing" a future thread).
                if available_threads > 0:
                    available_threads -= 1
                else:
                    dropped_requests += 1
            else:
                # Add the whole batch of k positive threads in O(1) instead of looping k times.
                available_threads += event
    
        return dropped_requests
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Picture a reception desk handing out single-use visitor badges. The desk starts empty (0 badges). Whenever a courier drops off a box of k new badges (event > 0), you add k to the stack on the desk; whenever a visitor walks up (event == -1), they either take 1 badge forever (shrinking the stack by 1) or get turned away at the door if the desk is empty right then. Using a single-pass simulation (scanning the array once from left to right while updating a compact state), we only need two integers: how many badges are currently on the desk (available_threads) and how many visitors were turned away (dropped_requests).

Simply comparing total requests against total threads at the end fails because arrival order matters: in [-1, 4, -1, -1], the opening request arrives before the 4 threads exist and is permanently lost even though total threads exceed total requests. Conversely, modeling each thread as an individual element inside a list fails because a single batch of 10^9 threads would allocate a billion objects and run out of memory and time.

Let's trace events = [-1, 4, -1, -1] (Example 2): 1. Start with available_threads = 0 and dropped_requests = 0. 2. First -1: available_threads is 0, so the request is dropped (dropped_requests = 1, available_threads stays 0). 3. Event 4: adds 4 threads (available_threads = 4). 4. Next -1: consumes 1 thread (available_threads = 3). 5. Final -1: consumes 1 thread (available_threads = 2), returning dropped_requests = 1.

Complexity

Let n = len(events).

  • Time: O(n). We visit each of the n events exactly once and perform one comparison plus one integer addition or subtraction per step.
  • Space: O(1) auxiliary space. Regardless of whether 10 or 10^14 threads are created, we only store two integer counters (available_threads and dropped_requests).

Edge cases

  • Requests arrive before any threads ([-1, 1, -1]): The first request sees available_threads == 0 and is dropped; the 1 arrives afterward and serves only the second request (answer: 1).
  • All requests ([-1, -1, -1]): available_threads stays 0 throughout, so every element is dropped (len(events)).
  • All thread additions ([3, 10**9, 1]): dropped_requests is never incremented and returns 0.
  • Single-element input: [-1] returns 1; [7] returns 0.
  • Thread totals exceeding 32 bits (10^5 batches of 10^9 = 10^14): Safe in Python because Python uses arbitrary-precision integers (integers that automatically expand in memory so they never wrap around), whereas in C++, Java, or Go on 32-bit int types this would suffer 32-bit signed integer overflow (wrapping past 2^31 - 1 ≈ 2.15 * 10^9 into negative numbers, causing bogus drops).
  • Unused threads at the end ([3, -1, 2, -1, -1, -1]): Extra threads left in available_threads do not change dropped_requests.

Common mistakes

  • Subtracting totals (max(0, requests - threads)): Ignores chronological order and undercounts drops whenever threads arrive after earlier requests already failed.
  • Allowing available_threads to go negative: Doing available_threads -= 1 unconditionally on -1 lets a dropped request "reserve" a future thread that has not arrived yet.
  • Appending k items in a loop for each batch: Turns an O(n) scan into O(sum of thread counts), timing out on event = 10^9.
  • Using a 32-bit int for available_threads in typed languages: available_threads must be a 64-bit integer (long / long long / i64), even though dropped_requests itself never exceeds len(events) <= 10^5.
  • Releasing threads back into the pool: The problem specifies permanent one-shot thread consumption; threads are never recycled.

Alternative approaches

  • Maximum prefix deficit: Define the prefix deficit after index i as (requests seen in 0..i) - (threads added in 0..i). Across any event sequence, dropped_requests equals the maximum value this prefix deficit reaches (clamped at 0 if it stays negative). Why? Whenever the very last drop occurs, available_threads is 0, meaning every thread added up to that point was consumed by a served request, so (requests so far) - (threads so far) at that exact moment equals total drops. Both views take one O(n) pass and O(1) space, though tracking available_threads directly mirrors the problem rules.

Follow-up questions

  • How would the simulation change if unserved requests wait in a bounded FIFO buffer of size Q before being rejected? Track an extra counter waiting_requests = 0 (0 <= waiting_requests <= Q). When -1 arrives with available_threads == 0, increment waiting_requests if waiting_requests < Q, and increment dropped_requests only when waiting_requests == Q. When a batch of k threads arrives, immediately match served = min(k, waiting_requests) threads to the waiting queue (waiting_requests -= served) and add only the leftover k - served to available_threads, keeping O(n) time and O(1) space.

python def count_dropped_with_buffer(events: list[int], queue_capacity: int) -> int: available_threads = 0 waiting_requests = 0 dropped_requests = 0 for event in events: if event == -1: if available_threads > 0: available_threads -= 1 elif waiting_requests < queue_capacity: waiting_requests += 1 else: dropped_requests += 1 else: matched = min(event, waiting_requests) waiting_requests -= matched available_threads += event - matched return dropped_requests

  • Suppose worker threads return to the pool once each request's processing duration elapses—how would you track capacity? Each event now carries a timestamp t (and each request carries a duration). Maintain a min-heap (a binary tree structure that keeps the smallest element at the top so finding or popping the earliest timestamp takes O(log n) time) of active requests' completion times t + duration. Before processing any event at timestamp t, pop all completion times <= t from the min-heap and return that count to available_threads; admitting a request decrements available_threads and pushes t + duration, giving O(n log n) total time and O(n) space.
  • How could you compute the exact drop count across billions of log entries partitioned across a cluster? Use the maximum-prefix-deficit equivalence! Have each worker scan its chunk independently in O(chunk_size) time to produce a two-number summary (net_deficit, max_prefix_deficit), where net_deficit = requests_in_chunk - threads_in_chunk. A coordinator then combines all chunk summaries in order (global_max = max(global_max, running_deficit + chunk_max_prefix), running_deficit += chunk_net_deficit), giving the exact drop count with just two 64-bit integers sent per machine.

Follow-up questions

Similar questions

More J.P. Morgan interview questions

All 53 J.P. Morgan questions →