Intercept Aircraft and Count User Sessions
Greedy & IntervalsAuto-graded · 23 test casesLast updated
Tests greedy deadline scheduling for time-critical interception tasks and event grouping with gap-based sessionization.
You must solve two independent problems and return both answers as a list [aircraft_intercepted, session_count].
Problem A: Maximum Aircraft Interceptions
You operate an anti-aircraft defense system. Each aircraft i is characterized by:
altitude[i]: its starting height in meters (positive integer)descent[i]: how many meters it drops each second (positive integer)
Time proceeds in discrete one-second steps starting from t = 0. At each second, the following happens in order:
- You may intercept exactly one aircraft (your choice), removing it immediately from the simulation, OR you may choose to do nothing
- Then all remaining aircraft descend by their respective
descentvalues
An aircraft lands if its altitude becomes <= 0 after the descent step of any second. When any aircraft lands, the entire process terminates immediately—no further interceptions are possible.
Your goal: Compute the maximum number of aircraft you can intercept before any aircraft lands, assuming you make optimal decisions each second.
Key rules:
- Interception happens before descent each second
- You intercept at most one aircraft per second
- The process stops the instant any aircraft's altitude drops to 0 or below after descent
- At second
t, aircraft have already descendedttimes (at the end of seconds 0 through t-1) before you act
Problem B: Total Session Count
You are given a log of user activity events. Each event is a pair [user_id, timestamp] where:
user_idcan be any hashable value (integer, string, etc.)timestampis a non-negative integer representing seconds- Events may appear in any order in the input
For each user, define sessions as follows:
- Sort that user's events by timestamp
- The first event starts a new session
- Each subsequent event either continues the current session or starts a new one:
- If the time gap from the previous event is
<= timeout, it continues the same session - If the gap is
> timeout, it starts a new session
- If the time gap from the previous event is
Your goal: Return the total number of sessions across all users.
Key rules:
- Sessions are per-user (different users never share a session)
- Events with identical timestamps for the same user belong to the same session (gap = 0)
- An empty event list produces 0 sessions
Constraints
0 <= len(altitude) <= 10^4len(altitude) == len(descent)1 <= altitude[i], descent[i] <= 10^60 <= len(events) <= 10^40 <= timeout <= 10^6- User IDs are hashable (integers, strings, etc.)
- Timestamps are non-negative integers
- Events may be in any order
Examples
Example 1
Input: intercept_and_count_sessions([4, 2, 5, 3], [2, 1, 1, 3], [[1, 1], [2, 1], [1, 3], [1, 10], [2, 5]], 2)
Output: [2, 4]
Example 2
Input: intercept_and_count_sessions([], [], [], 0)
Output: [0, 0]
Example 3
Input: intercept_and_count_sessions([10, 20], [3, 5], [[7, 4], [7, 4], [8, 1], [7, 7]], 0)
Output: [2, 3]
Hints
Hint 1
For aircraft: each plane will land after a specific number of seconds if not intercepted. Calculate this survival time for each aircraft.
Hint 2
The most urgent aircraft is the one that will land soonest. Always intercept the aircraft with the earliest landing time to maximize total interceptions.
Hint 3
For sessions: process each user independently by sorting their timestamps, then count how many consecutive pairs have a time gap exceeding the timeout.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Part A: Aircraft Interception Strategy
The core insight is to translate each aircraft into a deadline: the last second at which you can intercept it before it lands.
An aircraft at height h descending at rate d per second will reach altitude <= 0 after k descents, where k is the smallest integer with k * d >= h. Using integer ceiling division:
deadline = ⌈h / d⌉ = (h + d - 1) // d
At the beginning of second t, all aircraft have already descended t times (from seconds 0 through t-1). Aircraft i can be intercepted at second t only if t < deadline[i]. Once an aircraft's deadline expires, it lands.
Greedy algorithm:
- Compute the deadline for each aircraft
- Sort deadlines in ascending order
- Process deadlines sequentially: intercept the
k-th aircraft (0-indexed) at secondk - Stop when the next deadline satisfies
deadline <= k(aircraft already landed)
Correctness: By prioritizing the most urgent aircraft (earliest deadline), we minimize the risk of any aircraft landing prematurely. Using an exchange argument: if we ever intercept a less-urgent aircraft while a more-urgent one remains, swapping their interception order cannot make things worse (the urgent one is saved earlier, the less-urgent one is still intercepted before its later deadline). Skipping a second never helps—it only delays all future interceptions.
Time complexity: O(n log n) for sorting
Space complexity: O(n) for deadline storage
Part B: Session Counting
Sessions are user-specific and time-gap-based. We handle each user independently:
- Group events by
user_idusing a dictionary - Sort each user's timestamps in ascending order
- Count sessions: Start with 1 session per user (for their first event), then add 1 for each consecutive pair where
current_timestamp - previous_timestamp > timeout
Correctness: After sorting, session boundaries occur exactly where the time gap exceeds the threshold. A user with g gaps larger than timeout has g + 1 sessions. Summing across all users gives the total.
Time complexity: O(E log E) where E = number of events
Space complexity: O(E) for grouping
Combined Complexity
Time: O(n log n + E log E)
Space: O(n + E)
Edge Cases
- Ceiling division: Use
(h + d - 1) // dto correctly compute the number of seconds until landing - Immediate threat: If
altitude[i] <= descent[i], the aircraft lands after 1 second, giving deadline = 1 (can be intercepted at t=0) - Multiple aircraft with deadline 1: Only one can be intercepted before at least one lands
- All aircraft interceptable: Loop completes without breaking, returning
n - Empty aircraft arrays: Return 0 intercepted
- Duplicate timestamps: Events at the same time (gap = 0 ≤ timeout) share a session
- timeout = 0: Only identical timestamps share a session
- Empty event list: Return 0 sessions
Solution
from collections import defaultdict
from typing import List
def intercept_and_count_sessions(altitude, descent, events, timeout):
# Part A: Compute landing time for each aircraft (deadline for interception)
# Aircraft i lands after ceil(altitude[i] / descent[i]) seconds
deadlines = sorted((h + d - 1) // d for h, d in zip(altitude, descent))
intercepted = 0
for deadline in deadlines:
# The k-th interception (0-indexed) happens at second k
# Aircraft must still be airborne: deadline > k
if deadline <= intercepted:
break
intercepted += 1
# Part B: Group events by user, sort timestamps, count session boundaries
user_timestamps = defaultdict(list)
for user_id, timestamp in events:
user_timestamps[user_id].append(timestamp)
sessions = 0
for timestamps in user_timestamps.values():
timestamps.sort()
if timestamps:
sessions += 1 # First event starts first session
for prev, curr in zip(timestamps, timestamps[1:]):
if curr - prev > timeout:
sessions += 1 # Gap exceeds timeout, new session starts
return [intercepted, sessions]