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 ofknew 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
1idle thread for good—once assigned, a thread is never recycled back into the pool. - When
0idle threads are present, the request cannot be handled and is immediately dropped.
- When at least one idle thread is present, the request claims
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-1or an integer satisfying1 <= events[i] <= 10^9. - Total idle threads can accumulate up to
10^14(above the 32-bit signed maximum2^31 - 1), so fixed-width languages require a 64-bit integer counter (long long/long), whereas Pythonintgrows automatically. - The returned count lies between
0andlen(events)inclusive.
Step-by-step walkthrough
Understand the event stream and rules
We are given an integer array
eventsrepresenting server activity in chronological order from left to right:event > 0:eventnew 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- Order matters: Future threads never retroactively serve requests that were already dropped.
- Permanent consumption: Once a request takes a thread, that thread is gone forever.
Why summing totals or simulating individual threads fails
Before writing code, let's rule out two tempting traps:
- 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 predicts0drops — missing the fact that the first request arrived before the 4 threads existed. - Keeping a list of individual thread objects: Appending
"thread"to a listktimes whenevent = kand calling.pop()on-1obeys the ordering rules, but a single event can havek = 10^9. Looping a billion times for one array element runs out of both time and memory.
- Comparing totals at the end (
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 = 0anddropped_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, decrementavailable_threads -= 1. - Otherwise (
available_threads == 0), leaveavailable_threadsat0and incrementdropped_requests += 1. Never letavailable_threadsgo below0, or a dropped request would act like a debt that steals a future thread!
- If
Watch the number size: With up to
10^5events of up to10^9threads each,available_threadscan reach10^5 * 10^9 = 10^14. That exceeds the maximum 32-bit signed integer (2^31 - 1 ≈ 2.15 * 10^9). Python'sintautomatically grows to arbitrary precision, while in C++, Java, or Rust you would use a 64-bitlong long/long/i64.- Start with
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_requestsTrace 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 3At the end of the array,
dropped_requestsis3, matching Example 1.In Example 3 (
events = [3, -1, 2, -1, -1, -1]),available_threadsmoves0 -> 3 -> 2 -> 4 -> 3 -> 2 -> 1anddropped_requestsstays0; the unused thread at the end simply remains idle.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
nevents exactly once and perform one comparison plus one integer addition or subtraction per step. - Space: O(1) auxiliary space. Regardless of whether
10or10^14threads are created, we only store two integer counters (available_threadsanddropped_requests).
Edge cases
- Requests arrive before any threads (
[-1, 1, -1]): The first request seesavailable_threads == 0and is dropped; the1arrives afterward and serves only the second request (answer:1). - All requests (
[-1, -1, -1]):available_threadsstays0throughout, so every element is dropped (len(events)). - All thread additions (
[3, 10**9, 1]):dropped_requestsis never incremented and returns0. - Single-element input:
[-1]returns1;[7]returns0. - Thread totals exceeding 32 bits (
10^5batches of10^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-bitinttypes this would suffer 32-bit signed integer overflow (wrapping past2^31 - 1 ≈ 2.15 * 10^9into negative numbers, causing bogus drops). - Unused threads at the end (
[3, -1, 2, -1, -1, -1]): Extra threads left inavailable_threadsdo not changedropped_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_threadsto go negative: Doingavailable_threads -= 1unconditionally on-1lets a dropped request "reserve" a future thread that has not arrived yet. - Appending
kitems in a loop for each batch: Turns an O(n) scan into O(sum of thread counts), timing out onevent = 10^9. - Using a 32-bit
intforavailable_threadsin typed languages:available_threadsmust be a 64-bit integer (long/long long/i64), even thoughdropped_requestsitself never exceedslen(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
ias(requests seen in 0..i) - (threads added in 0..i). Across any event sequence,dropped_requestsequals the maximum value this prefix deficit reaches (clamped at0if it stays negative). Why? Whenever the very last drop occurs,available_threadsis0, 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 trackingavailable_threadsdirectly 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-1arrives withavailable_threads == 0, incrementwaiting_requestsifwaiting_requests < Q, and incrementdropped_requestsonly whenwaiting_requests == Q. When a batch ofkthreads arrives, immediately matchserved = min(k, waiting_requests)threads to the waiting queue (waiting_requests -= served) and add only the leftoverk - servedtoavailable_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 aduration). 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 timest + duration. Before processing any event at timestampt, pop all completion times<= tfrom the min-heap and return that count toavailable_threads; admitting a request decrementsavailable_threadsand pushest + 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), wherenet_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
- How would the simulation change if unserved requests wait in a bounded FIFO buffer of size Q before being rejected?
- Suppose worker threads return to the pool once each request's processing duration elapses—how would you track capacity?
- How could you compute the exact drop count across billions of log entries partitioned across a cluster?
Similar questions
- Course Prerequisite Feasibility
- Longest Palindromic Subsequence Length
- Circular Window Maximum and Single-Deletion Indices
- Grouped Binary Substrings and Outline Numbering
- Largest Sum of a Contiguous Subarray
- Anagram Bucketing and Orthogonal Grid Paths
More J.P. Morgan interview questions
- Delivering Software Under Ambiguous Specifications Medium
- Career Summary, Standout Project, and Peer Disagreement Easy
- Resumable Large-File Transfer with Scoped Token Auth Medium Pro
- Multimodal RAG Architecture for Financial Research Medium Pro
- Distributed API Rate Limiter: Algorithms and High Availability Medium Pro
- Idempotent and Fault-Tolerant Bank Transfer Backend Medium Pro
- Compliance-Grade Enterprise Knowledge Chatbot Easy Pro
- Modular AI Skills vs. Stateful Agents in LangChain and LangGraph Medium Pro
- Daily Quantitative Signal Design and Forecasting Pipeline Medium Pro
- CPython Concurrency, Conditional HTTP Writes, GC, and Deadlocks Medium Pro