Intercepting Descending Aircraft and Counting User Sessions
Easy · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
Implement max_planes_and_count_sessions(altitude, descent, events, timeout) to solve two independent algorithmic tasks in one call and return [max_planes, session_count].
Task 1: Maximum Aircraft Intercepted Before Touchdown
You receive two equal-length lists of positive integers, altitude and descent (len(altitude) == len(descent) == n), where altitude[i] is aircraft i's initial height and descent[i] is the height aircraft i loses per second.
Time advances in discrete seconds t = 0, 1, 2, .... At the start of each second t:
1. You may immediately intercept at most one airborne aircraft (removing it before it loses height during second t).
2. Every remaining airborne aircraft then drops by its descent[i] value.
3. If any remaining aircraft reaches height <= 0 at the end of second t, that aircraft has touched down and the process terminates immediately (no shots can be fired in subsequent seconds).
Assuming optimal target selection at every second, compute max_planes, the maximum number of aircraft intercepted prior to the first touchdown (0 when n == 0).
Task 2: User Activity Session Count
You receive events, a list of [user_id, timestamp] pairs with integer timestamps in arbitrary order, along with an integer timeout >= 0.
Partition events by user_id and sort each user's timestamps in non-decreasing order. Within a single user's sorted timeline, two consecutive events belong to the same session when later_timestamp - earlier_timestamp <= timeout; when the gap is strictly larger than timeout, the later event starts a new session. Compute session_count, the sum of sessions across all distinct users present in events (0 when events is empty).
def max_planes_and_count_sessions(
altitude: List[int],
descent: List[int],
events: List[List],
timeout: int,
) -> List[int]:
Examples
Example 1
Input: altitude = [6, 2, 9, 6, 10], descent = [3, 2, 3, 2, 2], events = [[10, 2], [20, 4], [10, 5], [10, 12], [20, 7]], timeout = 3
Output: [3, 3]
Explanation:
- Aircraft: Unshot touchdown times ceil(altitude[i] / descent[i]) are [2, 1, 3, 3, 5], sorting to [1, 2, 3, 3, 5]. Intercepting deadlines 1, 2, and 3 at t = 0, 1, 2 succeeds (3 shots), after which the remaining deadline-3 aircraft reaches height 0 at the end of t = 2 and stops the run.
- Sessions: User 10 has sorted timestamps [2, 5, 12] (5 - 2 = 3 <= 3 stays together; 12 - 5 = 7 > 3 opens a second session -> 2 sessions). User 20 has [4, 7] (7 - 4 = 3 <= 3 -> 1 session), giving 3 total sessions.
Example 2
Input: altitude = [5, 3], descent = [5, 4], events = [[4, 8], [4, 8], [9, 2], [4, 10]], timeout = 0
Output: [1, 3]
Explanation:
- Aircraft: Both aircraft reach <= 0 at the end of t = 0 (deadlines = [1, 1]), so you intercept one at t = 0 before the other touches down (1 shot).
- Sessions: With timeout = 0, user 4's identical timestamps [8, 8] have difference 0 <= 0 (same session), while 10 - 8 = 2 > 0 starts a second session; user 9 has 1 session at timestamp 2, totaling 3 sessions.
Example 3
Input: altitude = [8, 15], descent = [4, 5], events = [], timeout = 5
Output: [2, 0]
Explanation: Deadlines [2, 3] allow intercepting both aircraft at t = 0 and t = 1 (2 shots), and an empty events list yields 0 sessions.
Constraints
0 <= len(altitude) == len(descent) <= 10^51 <= altitude[i], descent[i] <= 10^90 <= len(events) <= 10^5user_idmay be any hashable key (e.g.,intorstr),-10^9 <= timestamp <= 10^9, and0 <= timeout <= 10^10.
Step-by-step walkthrough
Split the call into two clean subproblems
max_planes_and_count_sessionsbundles two completely independent tasks into one function returning[planes_shot, session_count]:max_planes_shot(altitude, descent): At each second0, 1, 2, ..., intercept at most one aircraft before all remaining aircraft descend; stop immediately if any remaining aircraft reaches height<= 0.count_sessions(events, timeout): Group[user_id, timestamp]events per user, sort each user's timestamps, and count how many sessions exist when gaps<= timeoutstay in one session and gaps> timeoutstart a new session.
Giving each task its own helper function keeps the code modular and handles empty inputs (
[]->0) naturally.def max_planes_and_count_sessions( altitude: List[int], descent: List[int], events: List[List], timeout: int, ) -> List[int]: """Solve both independent tasks and return [max_planes, session_count].""" planes_shot = max_planes_shot(altitude, descent) session_count = count_sessions(events, timeout) return [planes_shot, session_count]Task 1: Turn each aircraft into a touchdown deadline
Simulating every aircraft's changing height second by second would take
O(n^2)(or worse when heights reach10^9). Instead, ask one simple question about aircrafti: if we never intercept aircrafti, when does it touch down?At the end of second
t(t = 0, 1, 2, ...), aircraftihas descendedt + 1times, so its height isaltitude[i] - (t + 1) * descent[i]. It touches down (<= 0) as soon as(t + 1) * descent[i] >= altitude[i], which meanst + 1 >= ceil(altitude[i] / descent[i]). Calld = ceil(altitude[i] / descent[i])aircrafti's deadline:Example A: altitude = 6, descent = 3 --> deadline d = ceil(6 / 3) = 2 Start of t = 0: alt = 6 (can shoot!) -> end of t = 0: alt = 3 (> 0, still airborne) Start of t = 1: alt = 3 (can shoot!) -> end of t = 1: alt = 0 (<= 0, TOUCHED DOWN!) Valid seconds to shoot: t = 0 or t = 1 (that is 0 .. d - 1) Example B: altitude = 7, descent = 3 --> deadline d = ceil(7 / 3) = 3 End of t = 0: alt = 4 | End of t = 1: alt = 1 | End of t = 2: alt = -2 (TOUCHED DOWN!) Valid seconds to shoot: t = 0, 1, or 2 (that is 0 .. d - 1)Notice we compute
ceil(alt / desc)with exact integer division(alt + desc - 1) // descrather thanmath.ceil(alt / desc)so large integers never suffer floating-point rounding errors.Task 1: Intercept the earliest deadline first
Once every aircraft is represented by its deadline
d, we get one shot per second (second = 0, 1, 2, ...). Which aircraft should we intercept first? Always the most urgent aircraft—the one with the smallest deadline!Sort
deadlinesin non-decreasing order and try interceptingdeadlines[second]at eachsecond: - Ifdeadlines[second] > second, aircraftsecondhas not touched down yet (it lands at the end ofdeadlines[second] - 1 >= second), so our shot succeeds! - As soon as we hit the first indexkwheredeadlines[k] <= k, aircraftkalready touched down at the end of seconddeadlines[k] - 1 <= k - 1, so we must stop and returnk.Why can no other targeting order ever beat
k? Look at the firstk + 1aircraft0 .. kin sorted order: every single one of thosek + 1aircraft has a deadline<= k, meaning allk + 1of them will touch down before secondkstarts unless intercepted during thekseconds0 .. k - 1. Withk + 1urgent aircraft and onlykshots, at least one is guaranteed to touch down and end the run after at mostkshots!def max_planes_shot(altitude: List[int], descent: List[int]) -> int: """Task 1: Return the maximum number of planes shot before any plane lands.""" # deadlines: list of positive ints where deadlines[i] = ceil(altitude[i] / descent[i]). # Plane i can be shot during seconds 0 .. deadlines[i] - 1 and lands at end of second deadlines[i] - 1. deadlines: List[int] = [] for i in range(len(altitude)): alt = altitude[i] desc = descent[i] # Exact integer ceiling division avoids float rounding on huge integers. seconds_until_landing = (alt + desc - 1) // desc deadlines.append(seconds_until_landing) # Earliest-deadline-first: always spend second t on the t-th most urgent plane. deadlines.sort() for second in range(len(deadlines)): # Use '<=' (not '<'): a plane with deadline d lands at the end of second d - 1, # so by the start of second == d it has already touched the ground. if deadlines[second] <= second: return second return len(deadlines)Task 2: Group by user, sort times, and count big gaps
Sessions belong to individual users, and
eventscan arrive out of order with users interleaved. So we process events in two straightforward steps:- Collect each user's event timestamps into a dictionary
times_by_user[user_id]. - For each user, sort their
timeslist:- Their very first event (
times[0]) always opens1session. - Each subsequent event
times[k]stays in the current session iftimes[k] - times[k - 1] <= timeout, and opens+1new session iftimes[k] - times[k - 1] > timeout.
- Their very first event (
User 10 sorted times: [2, 5, 12], timeout = 3 time 2 ----(gap = 3 <= 3: same)----> time 5 ----(gap = 7 > 3: NEW!)----> time 12 [========== Session 1 ==========] [Session 2]Identical timestamps like
[8, 8]in Example 2 have gap0 <= timeout(even whentimeout = 0), so they stay in the same session automatically.def count_sessions(events: List[List], timeout: int) -> int: """Task 2: Group events by user, sort timestamps, and count timeout-separated sessions.""" # times_by_user: dict mapping user_id -> list of timestamps, e.g. {10: [2, 5, 12], 20: [4, 7]} times_by_user: Dict[Any, List[int]] = {} for user_id, timestamp in events: if user_id not in times_by_user: times_by_user[user_id] = [] times_by_user[user_id].append(timestamp) total_sessions = 0 for times in times_by_user.values(): times.sort() # Every user who appears in events has at least 1 event, which starts their first session. total_sessions += 1 for k in range(1, len(times)): # Gap <= timeout stays in the same session; strictly > timeout starts a new session. if times[k] - times[k - 1] > timeout: total_sessions += 1 return total_sessions- Collect each user's event timestamps into a dictionary
Walk through Example 1 on both tasks
Inputs: altitude = [6, 2, 9, 6, 10], descent = [3, 2, 3, 2, 2] events = [[10, 2], [20, 4], [10, 5], [10, 12], [20, 7]], timeout = 3 Task 1 (Aircraft): deadlines = [(6+2)//3, (2+1)//2, (9+2)//3, (6+1)//2, (10+1)//2] = [2, 1, 3, 3, 5] sorted = [1, 2, 3, 3, 5] second = 0: deadlines[0] = 1 > 0 -> intercept! second = 1: deadlines[1] = 2 > 1 -> intercept! second = 2: deadlines[2] = 3 > 2 -> intercept! second = 3: deadlines[3] = 3 <= 3 -> STOP! (touched down at end of second 2) planes_shot = 3 Task 2 (Sessions): user 10 -> sorted [2, 5, 12]: gaps are 3 (<= 3) and 7 (> 3) -> 1 + 1 = 2 sessions user 20 -> sorted [4, 7]: gap is 3 (<= 3) -> 1 + 0 = 1 session session_count = 3 Output: [3, 3]Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def max_planes_shot(altitude: List[int], descent: List[int]) -> int: """Task 1: Return the maximum number of planes shot before any plane lands.""" # deadlines: list of positive ints where deadlines[i] = ceil(altitude[i] / descent[i]). # Plane i can be shot during seconds 0 .. deadlines[i] - 1 and lands at end of second deadlines[i] - 1. deadlines: List[int] = [] for i in range(len(altitude)): alt = altitude[i] desc = descent[i] # Exact integer ceiling division avoids float rounding on huge integers. seconds_until_landing = (alt + desc - 1) // desc deadlines.append(seconds_until_landing) # Earliest-deadline-first: always spend second t on the t-th most urgent plane. deadlines.sort() for second in range(len(deadlines)): # Use '<=' (not '<'): a plane with deadline d lands at the end of second d - 1, # so by the start of second == d it has already touched the ground. if deadlines[second] <= second: return second return len(deadlines) def count_sessions(events: List[List], timeout: int) -> int: """Task 2: Group events by user, sort timestamps, and count timeout-separated sessions.""" # times_by_user: dict mapping user_id -> list of timestamps, e.g. {10: [2, 5, 12], 20: [4, 7]} times_by_user: Dict[Any, List[int]] = {} for user_id, timestamp in events: if user_id not in times_by_user: times_by_user[user_id] = [] times_by_user[user_id].append(timestamp) total_sessions = 0 for times in times_by_user.values(): times.sort() # Every user who appears in events has at least 1 event, which starts their first session. total_sessions += 1 for k in range(1, len(times)): # Gap <= timeout stays in the same session; strictly > timeout starts a new session. if times[k] - times[k - 1] > timeout: total_sessions += 1 return total_sessions def max_planes_and_count_sessions( altitude: List[int], descent: List[int], events: List[List], timeout: int, ) -> List[int]: """Solve both independent tasks and return [max_planes, session_count].""" planes_shot = max_planes_shot(altitude, descent) session_count = count_sessions(events, timeout) return [planes_shot, session_count]✅ Submit now — all tests should pass.
Intuition & how it works
For Task 1, imagine catching falling water balloons one per second before any balloon hits the floor: neither a balloon's starting height nor its falling speed matters by itself—all that matters is how many seconds remain until it hits the ground (its deadline). Once every aircraft is converted into deadline = ceil(altitude / descent), we use earliest-deadline-first—a greedy algorithm (a step-by-step rule that always picks the single most urgent choice right now) that sorts deadlines from smallest to largest and intercepts them in that order. For Task 2, think of sorting mixed chat messages into separate folders per person: once one user's messages are lined up in chronological order, their first message starts session 1 and every silence strictly longer than timeout starts a new session.
Simulating every aircraft's height drop second-by-second is much too slow when heights reach 10^9 or n = 100,000, and greedily shooting the lowest-altitude or fastest-descending aircraft fails whenever a low, slow aircraft (alt = 2, desc = 2, lands in 1s) touches down sooner than a high, fast aircraft (alt = 100, desc = 10, lands in 10s). Similarly, sorting all events in a single flat list without grouping by user_id measures gaps between different users and produces wrong session counts.
Walk through Example 1 on altitude = [6, 2, 9, 6, 10], descent = [3, 2, 3, 2, 2], and user 10's events [[10, 2], [10, 5], [10, 12]] with timeout = 3:
1. Aircraft: Deadlines are [ceil(6/3), ceil(2/2), ceil(9/3), ceil(6/2), ceil(10/2)] = [2, 1, 3, 3, 5], sorting to [1, 2, 3, 3, 5]. At second = 0, 1, 2, 1 > 0, 2 > 1, and 3 > 2 (3 shots); at second = 3, deadlines[3] = 3 <= 3 (this aircraft already reached height 0 at the end of second 2), so we stop with 3 aircraft intercepted.
2. Sessions: User 10 has sorted times [2, 5, 12]. Time 2 starts session #1; 5 - 2 = 3 <= 3 stays in session #1; 12 - 5 = 7 > 3 starts session #2 (2 sessions for user 10, plus 1 for user 20, giving 3 total).
Complexity
Let n be the number of aircraft (len(altitude)) and E be the number of events (len(events)).
- Time:
O(n log n + E log E). Computingninteger deadlines takesO(n)work, sorting them takesO(n log n), and scanning them once takesO(n). GroupingEevents into dictionary lists takesO(E)average time, and sorting each user's list of sizeE_utakessum(E_u log E_u) <= E log Etotal time across all users. - Space:
O(n + E). Storing thedeadlineslist usesO(n)memory, and storing all timestamps acrosstimes_by_userusesO(E)memory.
Edge cases
- Empty arrays (
altitude = []orevents = []): An emptyeventslist produces0sessions (Example 3), and when both inputs are empty[0, 0]is returned cleanly. - Height hitting exact
0: Because<= 0counts as a touchdown,altitude = 6, descent = 3reaches0at the end of second1(deadline = 2), leaving only seconds0and1to intercept it. - Tied urgent deadlines (
[5, 3]with[5, 4], Example 2): Both aircraft havedeadline = 1; you intercept one atsecond = 0and the other touches down at the end ofsecond = 0, returning1. - Every aircraft can be intercepted (Example 3): When
deadlines[second] > secondholds for every index, the loop finishes and returnsn. - Gap equal to
timeoutand identical timestamps: A gap oftimeoutsatisfies<= timeoutand stays in the same session; duplicate events at the exact same timestamp have gap0 <= timeouteven whentimeout = 0(Example 2). - Negative timestamps and string user IDs: Dictionary grouping works for any hashable
user_id(intorstr), and subtractiontimes[k] - times[k - 1]works identically for negative integers.
Common mistakes
- Using
math.ceil(alt / desc)with floating-point division: Large 64-bit integers above2^53lose precision when converted tofloat;(alt + desc - 1) // descis exact for all positive integers. - Writing
deadlines[second] < secondinstead of<=: Off-by-one error! An aircraft withdeadline = 2touches down at the end of second1, so at the start ofsecond = 2it is already on the ground. - Sorting aircraft by
altitudeordescentalone: Neither quantity determines touchdown order; only their ceiling ratioceil(altitude / descent)does. - Writing
>= timeoutinstead of> timeoutfor new sessions: Splits events that aretimeoutapart into two sessions when the rule says<= timeoutstays together. - Forgetting the
+1initial session per active user: Counting onlygap > timeouttransitions undercounts every user by1.
Alternative approaches
- Linear-time
O(n)bucket counting for aircraft: Because you can intercept at mostnaircraft total, any deadline> ncan be capped or ignored! Using bucket counting (an arraycounts[1 .. n]recording how many aircraft have each deadline), walktfrom1tonaccumulatingurgent_so_far += counts[t]: the firsttwhereurgent_so_far > tmeanst + 1aircraft needed to be intercepted withintseconds, so the answer ist(ornifurgent_so_far <= teverywhere). - Min-heap simulation (
O(n log n)): A min-heap is a priority queue data structure that pops its smallest element inO(log n)time; pushing all deadlines and popping one per second untilsmallest <= secondgives the exact same result as sorting.
Follow-up questions
- How does the optimal strategy change if you can intercept up to k aircraft per second instead of just one? Earliest-deadline-first still yields the exact maximum! After sorting
deadlines, you fire up tokshots during second0(indices0 .. k - 1),kshots during second1(indicesk .. 2k - 1), and in general aircraftiis scheduled during secondi // k. Scanning for the first indexiwithdeadlines[i] <= i // k(or returningnif none fails) remains optimal: by the pigeonhole principle (if more items than available slots must finish before a cutoff, at least one misses it),i + 1aircraft with deadlines<= i // kcannot all be intercepted insidei // kseconds ofkshots each. - How would you count sessions over an unbounded, chronologically ordered event stream using bounded memory? Maintain a hash map
last_seen[user_id]storing only each user's latest timestamp alongside one runningtotal_sessionscounter. When(user_id, time)arrives, incrementtotal_sessionsifuser_idis absent fromlast_seenortime - last_seen[user_id] > timeout, and updatelast_seen[user_id] = timeinO(1)average time. To bound memory, periodically evict entries older thancurrent_time - timeout(for example using an insertion-ordered queue/dict), since any future event from an evicted user is guaranteed to open a fresh session. - How could you maintain the exact session count dynamically when streaming events arrive out of order? Keep each user's recent timestamps in a balanced binary search tree (a sorted tree supporting
O(log E_u)insertion and neighbor lookup) and updatetotal_sessionslocally around each newly insertedtime. Check its immediate predecessorprev_tand successornext_t: if both exist andnext_t - prev_t <= timeout, they already belonged to the same session so the count changes by0; otherwise, start with+1for the new event and subtract1for each neighbor (prev_tornext_t) withintimeout—yielding+1(isolated new session),0(extends one existing session), or-1(merges two separate sessions into one!). Combine this with a watermark (a moving cutoff timestamp beyond which late records go to batch backfill) so old timestamps can be pruned safely.
Follow-up questions
- How does the optimal strategy change if you can intercept up to k aircraft per second instead of just one?
- How would you count sessions over an unbounded, chronologically ordered event stream using bounded memory?
- How could you maintain the exact session count dynamically when streaming events arrive out of order?
Similar questions
- Troubleshooting and Extending a Streaming LLM Chat UI
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One