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^5
  • 1 <= altitude[i], descent[i] <= 10^9
  • 0 <= len(events) <= 10^5
  • user_id may be any hashable key (e.g., int or str), -10^9 <= timestamp <= 10^9, and 0 <= timeout <= 10^10.

Step-by-step walkthrough

  1. Split the call into two clean subproblems

    max_planes_and_count_sessions bundles two completely independent tasks into one function returning [planes_shot, session_count]:

    1. max_planes_shot(altitude, descent): At each second 0, 1, 2, ..., intercept at most one aircraft before all remaining aircraft descend; stop immediately if any remaining aircraft reaches height <= 0.
    2. count_sessions(events, timeout): Group [user_id, timestamp] events per user, sort each user's timestamps, and count how many sessions exist when gaps <= timeout stay in one session and gaps > timeout start 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]
    
  2. 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 reach 10^9). Instead, ask one simple question about aircraft i: if we never intercept aircraft i, when does it touch down?

    At the end of second t (t = 0, 1, 2, ...), aircraft i has descended t + 1 times, so its height is altitude[i] - (t + 1) * descent[i]. It touches down (<= 0) as soon as (t + 1) * descent[i] >= altitude[i], which means t + 1 >= ceil(altitude[i] / descent[i]). Call d = ceil(altitude[i] / descent[i]) aircraft i'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) // desc rather than math.ceil(alt / desc) so large integers never suffer floating-point rounding errors.

  3. 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 deadlines in non-decreasing order and try intercepting deadlines[second] at each second: - If deadlines[second] > second, aircraft second has not touched down yet (it lands at the end of deadlines[second] - 1 >= second), so our shot succeeds! - As soon as we hit the first index k where deadlines[k] <= k, aircraft k already touched down at the end of second deadlines[k] - 1 <= k - 1, so we must stop and return k.

    Why can no other targeting order ever beat k? Look at the first k + 1 aircraft 0 .. k in sorted order: every single one of those k + 1 aircraft has a deadline <= k, meaning all k + 1 of them will touch down before second k starts unless intercepted during the k seconds 0 .. k - 1. With k + 1 urgent aircraft and only k shots, at least one is guaranteed to touch down and end the run after at most k shots!

    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)
    
  4. Task 2: Group by user, sort times, and count big gaps

    Sessions belong to individual users, and events can arrive out of order with users interleaved. So we process events in two straightforward steps:

    1. Collect each user's event timestamps into a dictionary times_by_user[user_id].
    2. For each user, sort their times list:
      • Their very first event (times[0]) always opens 1 session.
      • Each subsequent event times[k] stays in the current session if times[k] - times[k - 1] <= timeout, and opens +1 new session if times[k] - times[k - 1] > timeout.
    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 gap 0 <= timeout (even when timeout = 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
    
  5. 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]
    
  6. 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). Computing n integer deadlines takes O(n) work, sorting them takes O(n log n), and scanning them once takes O(n). Grouping E events into dictionary lists takes O(E) average time, and sorting each user's list of size E_u takes sum(E_u log E_u) <= E log E total time across all users.
  • Space: O(n + E). Storing the deadlines list uses O(n) memory, and storing all timestamps across times_by_user uses O(E) memory.

Edge cases

  • Empty arrays (altitude = [] or events = []): An empty events list produces 0 sessions (Example 3), and when both inputs are empty [0, 0] is returned cleanly.
  • Height hitting exact 0: Because <= 0 counts as a touchdown, altitude = 6, descent = 3 reaches 0 at the end of second 1 (deadline = 2), leaving only seconds 0 and 1 to intercept it.
  • Tied urgent deadlines ([5, 3] with [5, 4], Example 2): Both aircraft have deadline = 1; you intercept one at second = 0 and the other touches down at the end of second = 0, returning 1.
  • Every aircraft can be intercepted (Example 3): When deadlines[second] > second holds for every index, the loop finishes and returns n.
  • Gap equal to timeout and identical timestamps: A gap of timeout satisfies <= timeout and stays in the same session; duplicate events at the exact same timestamp have gap 0 <= timeout even when timeout = 0 (Example 2).
  • Negative timestamps and string user IDs: Dictionary grouping works for any hashable user_id (int or str), and subtraction times[k] - times[k - 1] works identically for negative integers.

Common mistakes

  • Using math.ceil(alt / desc) with floating-point division: Large 64-bit integers above 2^53 lose precision when converted to float; (alt + desc - 1) // desc is exact for all positive integers.
  • Writing deadlines[second] < second instead of <=: Off-by-one error! An aircraft with deadline = 2 touches down at the end of second 1, so at the start of second = 2 it is already on the ground.
  • Sorting aircraft by altitude or descent alone: Neither quantity determines touchdown order; only their ceiling ratio ceil(altitude / descent) does.
  • Writing >= timeout instead of > timeout for new sessions: Splits events that are timeout apart into two sessions when the rule says <= timeout stays together.
  • Forgetting the +1 initial session per active user: Counting only gap > timeout transitions undercounts every user by 1.

Alternative approaches

  • Linear-time O(n) bucket counting for aircraft: Because you can intercept at most n aircraft total, any deadline > n can be capped or ignored! Using bucket counting (an array counts[1 .. n] recording how many aircraft have each deadline), walk t from 1 to n accumulating urgent_so_far += counts[t]: the first t where urgent_so_far > t means t + 1 aircraft needed to be intercepted within t seconds, so the answer is t (or n if urgent_so_far <= t everywhere).
  • Min-heap simulation (O(n log n)): A min-heap is a priority queue data structure that pops its smallest element in O(log n) time; pushing all deadlines and popping one per second until smallest <= second gives 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 to k shots during second 0 (indices 0 .. k - 1), k shots during second 1 (indices k .. 2k - 1), and in general aircraft i is scheduled during second i // k. Scanning for the first index i with deadlines[i] <= i // k (or returning n if 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 + 1 aircraft with deadlines <= i // k cannot all be intercepted inside i // k seconds of k shots 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 running total_sessions counter. When (user_id, time) arrives, increment total_sessions if user_id is absent from last_seen or time - last_seen[user_id] > timeout, and update last_seen[user_id] = time in O(1) average time. To bound memory, periodically evict entries older than current_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 update total_sessions locally around each newly inserted time. Check its immediate predecessor prev_t and successor next_t: if both exist and next_t - prev_t <= timeout, they already belonged to the same session so the count changes by 0; otherwise, start with +1 for the new event and subtract 1 for each neighbor (prev_t or next_t) within timeout—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

Similar questions

More Supio interview questions

All 2 Supio questions →