Implement Four Standalone Stateful Coding Utilities

Medium · Coding & Algorithms · Software Engineer · Onsite

Problem Statement

Implement solve_four_design_tasks, which executes four standalone coding utilities and returns their outputs in a four-element list [rps_result, cache_result, billing_result, overlap_result]:

def solve_four_design_tasks(
    rounds: List[List[str]],
    capacity: int,
    operations: List[str],
    operation_args: List[List],
    counts: List[int],
    free_limit: int,
    unit_price: int,
    channel_to_followers: Dict[str, List],
    target_channel: str,
) -> List:

The four independent parts do not share state:

  1. Match Scorer for Rock-Paper-Scissors (rounds)

    • rounds contains chronological pairs [player_move, opponent_move], where every move belongs to {"R", "P", "S"} ("R" defeats "S", "P" defeats "R", "S" defeats "P", and identical symbols produce a tie).
    • Base points per round: a win awards 1 point, whereas a tie or a loss awards 0 points.
    • Streak bonus: whenever the player wins at least two consecutive rounds, every consecutive win after the initial win of that streak awards +1 additional point. Any tie or loss resets the consecutive-win counter to 0.
    • Tie-breaker bonus: winning a round immediately after a tied round awards +1 additional point on that winning round.
    • Produce rps_result = [total_score, per_round_scores], where per_round_scores[i] is the final point value earned on round i and total_score is the sum of per_round_scores.
  2. Fixed-Capacity LRU Cache (capacity, operations, operation_args)

    • Simulate an in-memory cache with maximum entry count capacity using Least Recently Used (LRU) eviction, running in O(1) average time per call.
    • Process parallel lists operations and operation_args:
      • "get" with [key]: if key is present, promote key to most recently used and record its stored value; otherwise record -1 without altering recency order.
      • "put" with [key, value]: record None. When capacity <= 0, nothing can be retained. When key already exists, replace its value and promote key to most recently used. When key is new, insert it as most recently used and, if the entry count now exceeds capacity, remove the least recently used key.
    • Produce cache_result, the list of recorded outputs across all operations.
  3. Daily Alert Metering (counts, free_limit, unit_price)

    • counts has length 24, where counts[h] is the volume of alerts sent during hour h (0 <= h <= 23).
    • A single daily allowance of free_limit free alerts is consumed chronologically from hour 0 through hour 23. An hour's volume may be split between free and paid alerts if the remaining allowance runs out mid-hour.
    • Every alert beyond the free allowance is billed at unit_price.
    • Produce billing_result = [total_cost, hourly_costs], where hourly_costs is the 24-element list of charges per hour and total_cost is their sum.
  4. Shared-Subscriber Channel Finder (channel_to_followers, target_channel)

    • channel_to_followers maps each channel identifier to a list of subscriber IDs, and target_channel is a key in channel_to_followers.
    • Identify every distinct channel other than target_channel that shares at least one subscriber ID with target_channel.
    • Produce overlap_result, the list of matching channel names (excluding target_channel).

Examples

Example 1

Input:
  rounds = [["S", "P"], ["R", "S"], ["P", "P"], ["P", "R"], ["S", "R"]]
  capacity = 2
  operations = ["put", "put", "put", "get", "put", "get", "get"]
  operation_args = [[10, 100], [20, 200], [10, 150], [20], [30, 300], [10], [30]]
  counts = [4, 6, 3, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
  free_limit = 8
  unit_price = 5
  channel_to_followers = {
      "chess": ["u1", "u2", "u3"],
      "art": ["u3", "u9"],
      "cooking": ["u8"],
      "speedrun": ["u2", "u1"],
  }
  target_channel = "chess"

Output:
  [
    [5, [1, 2, 0, 2, 0]],
    [None, None, None, 200, None, -1, 300],
    [35, [0, 10, 15, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]],
    ["art", "speedrun"]
  ]

Explanation: - Part 1: Outcomes are Win (1), Win (1 + 1 = 2 from the streak bonus), Tie (0, resetting the streak), Win (1 + 1 = 2 from breaking the tie), and Loss (0), summing to 5. - Part 2: Overwriting key 10 with 150 refreshes it, then get(20) returns 200 and makes key 10 least recently used. Inserting key 30 evicts key 10, so get(10) returns -1 and get(30) returns 300. - Part 3: Hour 0 uses 4 free alerts (4 left, cost 0). Hour 1 uses the last 4 free alerts and pays for 6 - 4 = 2 alerts (2 * 5 = 10). Hours 2 and 4 pay 3 * 5 = 15 and 2 * 5 = 10, totaling 35. - Part 4: "chess" has {"u1", "u2", "u3"}, which overlaps with "art" ("u3") and "speedrun" ("u1", "u2"), but not "cooking".

Example 2

Input:
  rounds = [["R", "R"], ["S", "P"], ["S", "P"], ["S", "P"]]
  capacity = 1
  operations = ["put", "get", "put", "get", "get"]
  operation_args = [["alpha", 0], ["alpha"], ["beta", 9], ["alpha"], ["beta"]]
  counts = [2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]
  free_limit = 100
  unit_price = 3
  channel_to_followers = {"solo": [10, 20], "peer_a": [30], "peer_b": []}
  target_channel = "solo"

Output:
  [
    [6, [0, 2, 2, 2]],
    [None, 0, None, -1, 9],
    [0, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]],
    []
  ]

Explanation: - Part 1: Round 0 ties (0), round 1 wins right after a tie (1 + 1 = 2), and rounds 2 and 3 extend the consecutive win streak (1 + 1 = 2 each), giving 6. - Part 2: Caching 0 under "alpha" is a valid entry (get("alpha") returns 0). Inserting "beta" into a capacity-1 cache evicts "alpha". - Part 3: Only 48 alerts are sent all day, well within free_limit = 100, so every hour costs 0. - Part 4: Neither "peer_a" nor "peer_b" shares any subscriber with "solo", yielding [].

Constraints

  • 1 <= len(rounds) <= 2 * 10^5, with each entry [player_move, opponent_move] using "R", "P", or "S".
  • 0 <= capacity <= 2 * 10^5 and 0 <= len(operations) == len(operation_args) <= 2 * 10^5.
  • len(counts) == 24, 0 <= counts[h] <= 10^9, 0 <= free_limit <= 10^12, and 0 <= unit_price <= 10^6.
  • 1 <= len(channel_to_followers) <= 10^5, total subscriber entries across all channels <= 10^6, and target_channel in channel_to_followers.

Step-by-step walkthrough

  1. Break the problem into four independent modules

    We are given four standalone coding tasks bundled behind one judge entry point, solve_four_design_tasks(...). Keeping each task in its own small, self-contained helper function prevents state from leaking between tasks and makes each piece easy to test and explain:

    solve_four_design_tasks(...)
      |-- [0] score_rounds(rounds)                                  -> [total_score, per_round_scores]
      |-- [1] run_lru(capacity, operations, operation_args)         -> [op_result_0, op_result_1, ...]
      |-- [2] bill_day(counts, free_limit, unit_price)              -> [total_cost, hourly_costs]
      +-- [3] overlapping_channels(channel_to_followers, target)    -> sorted list of channel names
    

    In Task 4, any order of matching channels is valid according to the prompt; sorting the final list makes our output deterministic across runs and languages (and matches both samples).

  2. Task 1: Score Rock-Paper-Scissors with a rules map and state variables

    Instead of writing a 9-branch if/elif chain for all (player, opponent) pairs, a 3-entry dictionary BEATS = {"R": "S", "P": "R", "S": "P"} captures the rules cleanly: equal moves tie ("T"), BEATS[player] == opponent is a win ("W"), and everything else is a loss ("L").

    To score bonuses in one O(N) pass, we maintain just two pieces of state: - win_streak: increments on "W" and resets to 0 on "T" or "L". Bonus A adds +1 whenever win_streak >= 2 (every consecutive win after the first). - previous_outcome: remembers the last round's result so Bonus B adds +1 whenever outcome == "W" and previous_outcome == "T".

    Round:      1     2     3     4     5
    Outcome:    W     W     W     T     W
    win_streak: 1     2     3     0     1
    prev:     None    W     W     W     T
    Score:      1   1+1=2 1+1=2   0   1+1=2   (Bonus A on rounds 2,3; Bonus B on round 5)
    
    # BEATS[move] is the opponent move that `move` defeats in Rock-Paper-Scissors.
    BEATS = {"R": "S", "P": "R", "S": "P"}
    
    
    def round_outcome(player_move: str, opponent_move: str) -> str:
        """Return 'W' (win), 'T' (tie), or 'L' (loss) from the player's perspective."""
        if player_move not in BEATS or opponent_move not in BEATS:
            raise ValueError(f"unknown move in round ({player_move!r}, {opponent_move!r})")
        if player_move == opponent_move:
            return "T"
        if BEATS[player_move] == opponent_move:
            return "W"
        return "L"
    
    
    def score_rounds(rounds: List[List[str]]) -> List:
        per_round_scores: List[int] = []
        win_streak = 0
        previous_outcome: Optional[str] = None
    
        for player_move, opponent_move in rounds:
            outcome = round_outcome(player_move, opponent_move)
            round_score = 0
    
            if outcome == "W":
                win_streak += 1
                round_score = 1
                # Bonus A: every consecutive win after the first (streak >= 2) earns +1.
                if win_streak >= 2:
                    round_score += 1
                # Bonus B: winning immediately after a tie earns +1.
                if previous_outcome == "T":
                    round_score += 1
            else:
                # Either a tie or a loss breaks any active consecutive win streak.
                win_streak = 0
    
            per_round_scores.append(round_score)
            previous_outcome = outcome
    
        return [sum(per_round_scores), per_round_scores]
    
  3. Task 2: Build an O(1) LRU cache with OrderedDict

    Storing keys in a plain Python list makes order.remove(key) and order.pop(0) cost O(capacity) time because elements must shift. To achieve O(1) average time per get and put, we combine a hash map with a doubly linked list ordered from least recently used (front) to most recently used (back). Python's collections.OrderedDict provides this exact structure out of the box:

    Front (evict here: popitem(last=False))        Back (refresh/insert here: move_to_end)
            [ least recent ]  <--->  ...  <--->  [ most recent ]
    
    • get(key): if key not in self.data, return -1 without modifying order. Otherwise call move_to_end(key) and return self.data[key].
    • put(key, value): if capacity <= 0, store nothing. If key already exists, call move_to_end(key). Set self.data[key] = value, and if len(self.data) > self.capacity, evict the oldest key with popitem(last=False).

    For the thread-safety prompt in Task 2: note that even get mutates the linked list (move_to_end), so a read-write lock cannot let multiple get calls run concurrently. Wrap both get and put in a single mutual-exclusion lock (threading.Lock), or shard keys by hash(key) % S across S independent locked caches under high contention.

    class LRUCache:
        def __init__(self, capacity: int):
            self.capacity = capacity
            # data: OrderedDict mapping key -> value in recency order:
            # front (first item) = least recently used; back (last item) = most recently used.
            self.data: OrderedDict = OrderedDict()
    
        def get(self, key: Any) -> Any:
            # Check membership explicitly so stored falsy values like 0 are not treated as misses.
            if key not in self.data:
                return -1
            self.data.move_to_end(key)
            return self.data[key]
    
        def put(self, key: Any, value: Any) -> None:
            if self.capacity <= 0:
                return
            if key in self.data:
                # Refresh recency before updating; size does not grow on an overwrite.
                self.data.move_to_end(key)
            self.data[key] = value
            if len(self.data) > self.capacity:
                # Evict from the front (last=False), which is the least recently used entry.
                self.data.popitem(last=False)
    
    
    def run_lru(capacity: int, operations: List[str], operation_args: List[List]) -> List:
        cache = LRUCache(capacity)
        results: List[Any] = []
        for op, args in zip(operations, operation_args):
            if op == "get":
                results.append(cache.get(args[0]))
            elif op == "put":
                cache.put(args[0], args[1])
                results.append(None)
            else:
                raise ValueError(f"unknown operation {op!r}")
        return results
    
  4. Task 3: Bill 24-hour notifications with a running free quota

    Simulating notifications one message at a time would take up to 24 * 10^9 iterations. Instead, we track free_remaining across the 24 hours from hour 0 to hour 23. In each hour, the number of free notifications used is min(sent, free_remaining), and the rest are billed at unit_price:

    Example 1: counts = [4, 6, 3, 0, 2, ...], free_limit = 8, unit_price = 5
      Hour 0 (sent=4): free_used = min(4, 8) = 4 | free_remaining = 4 | paid = 0 -> cost = 0
      Hour 1 (sent=6): free_used = min(6, 4) = 4 | free_remaining = 0 | paid = 2 -> cost = 10
      Hour 2 (sent=3): free_used = min(3, 0) = 0 | free_remaining = 0 | paid = 3 -> cost = 15
    

    At maximum constraints (24 * 10^9 * 10^6 = 2.4 * 10^16), Python's arbitrary-precision int stays exact (whereas 32-bit integers or 64-bit floats would overflow or round).

    def bill_day(counts: List[int], free_limit: int, unit_price: int) -> List:
        # free_remaining tracks how much of the daily free quota is still unused as hours advance.
        free_remaining = free_limit
        hourly_costs: List[int] = []
    
        for sent in counts:
            # Apply as much remaining free quota as possible to this hour in O(1) arithmetic.
            free_used = min(sent, free_remaining)
            free_remaining -= free_used
            paid_notifications = sent - free_used
            hourly_costs.append(paid_notifications * unit_price)
    
        return [sum(hourly_costs), hourly_costs]
    
  5. Task 4: Find overlapping channels with a follower hash set

    Checking follower in target_list on a plain list scans target_list repeatedly. Instead, convert target_channel's followers into a set (target_followers) once in O(|target|) time. Then iterate over every other channel (channel != target_channel), check each follower in O(1) average time, and break out of that channel's loop on the very first match so we never add a channel twice or do wasted checks.

    def overlapping_channels(channel_to_followers: Dict[str, List], target_channel: str) -> List[str]:
        # target_followers: hash set of follower IDs in target_channel for O(1) membership lookups.
        target_followers = set(channel_to_followers.get(target_channel, []))
        if not target_followers:
            return []
    
        matching_channels: List[str] = []
        for channel, followers in channel_to_followers.items():
            if channel == target_channel:
                continue
            for follower in followers:
                if follower in target_followers:
                    matching_channels.append(channel)
                    # Stop scanning this channel as soon as one shared follower is confirmed.
                    break
    
        matching_channels.sort()
        return matching_channels
    
  6. Wire the wrapper and trace Example 1

    solve_four_design_tasks calls the four helpers in order and returns their outputs in a four-element list:

    def solve_four_design_tasks(
        rounds: List[List[str]],
        capacity: int,
        operations: List[str],
        operation_args: List[List],
        counts: List[int],
        free_limit: int,
        unit_price: int,
        channel_to_followers: Dict[str, List],
        target_channel: str,
    ) -> List:
        return [
            score_rounds(rounds),
            run_lru(capacity, operations, operation_args),
            bill_day(counts, free_limit, unit_price),
            overlapping_channels(channel_to_followers, target_channel),
        ]
    

    Tracing Example 1 across all four tasks:

    1) RPS:  (S,P)->W(1), (R,S)->W(1+1=2), (P,P)->T(0), (P,R)->W(1+1=2), (S,R)->L(0)
             --> [5, [1, 2, 0, 2, 0]]
    
    2) LRU:  capacity = 2
             put(10,100) -> [10:100]            | None
             put(20,200) -> [10:100, 20:200]    | None
             put(10,150) -> [20:200, 10:150]    | None   (overwrites & promotes key 10)
             get(20)     -> [10:150, 20:200]    | 200    (promotes key 20)
             put(30,300) -> [20:200, 30:300]    | None   (evicts front key 10)
             get(10)     -> miss                | -1
             get(30)     -> [20:200, 30:300]    | 300
             --> [None, None, None, 200, None, -1, 300]
    
    3) Bill: counts = [4, 6, 3, 0, 2, 0...], free_limit = 8, unit_price = 5
             Hour 0 uses 4 free (cost 0); Hour 1 uses 4 free + pays 2*5=10;
             Hour 2 pays 3*5=15; Hour 4 pays 2*5=10
             --> [35, [0, 10, 15, 0, 10, 0, ...]]
    
    4) Fans: chess has {'u1', 'u2', 'u3'}
             art has 'u3' (match), cooking has 'u8' (no), speedrun has 'u2' (match)
             --> ['art', 'speedrun']
    
  7. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    from collections import OrderedDict
    
    # BEATS[move] is the opponent move that `move` defeats in Rock-Paper-Scissors.
    BEATS = {"R": "S", "P": "R", "S": "P"}
    
    
    # ---- Task 1: Rock-Paper-Scissors scoring with bonuses ----
    
    def round_outcome(player_move: str, opponent_move: str) -> str:
        """Return 'W' (win), 'T' (tie), or 'L' (loss) from the player's perspective."""
        if player_move not in BEATS or opponent_move not in BEATS:
            raise ValueError(f"unknown move in round ({player_move!r}, {opponent_move!r})")
        if player_move == opponent_move:
            return "T"
        if BEATS[player_move] == opponent_move:
            return "W"
        return "L"
    
    
    def score_rounds(rounds: List[List[str]]) -> List:
        per_round_scores: List[int] = []
        win_streak = 0
        previous_outcome: Optional[str] = None
    
        for player_move, opponent_move in rounds:
            outcome = round_outcome(player_move, opponent_move)
            round_score = 0
    
            if outcome == "W":
                win_streak += 1
                round_score = 1
                # Bonus A: every consecutive win after the first (streak >= 2) earns +1.
                if win_streak >= 2:
                    round_score += 1
                # Bonus B: winning immediately after a tie earns +1.
                if previous_outcome == "T":
                    round_score += 1
            else:
                # Either a tie or a loss breaks any active consecutive win streak.
                win_streak = 0
    
            per_round_scores.append(round_score)
            previous_outcome = outcome
    
        return [sum(per_round_scores), per_round_scores]
    
    
    # ---- Task 2: O(1) Least Recently Used (LRU) cache ----
    
    class LRUCache:
        def __init__(self, capacity: int):
            self.capacity = capacity
            # data: OrderedDict mapping key -> value in recency order:
            # front (first item) = least recently used; back (last item) = most recently used.
            self.data: OrderedDict = OrderedDict()
    
        def get(self, key: Any) -> Any:
            # Check membership explicitly so stored falsy values like 0 are not treated as misses.
            if key not in self.data:
                return -1
            self.data.move_to_end(key)
            return self.data[key]
    
        def put(self, key: Any, value: Any) -> None:
            if self.capacity <= 0:
                return
            if key in self.data:
                # Refresh recency before updating; size does not grow on an overwrite.
                self.data.move_to_end(key)
            self.data[key] = value
            if len(self.data) > self.capacity:
                # Evict from the front (last=False), which is the least recently used entry.
                self.data.popitem(last=False)
    
    
    def run_lru(capacity: int, operations: List[str], operation_args: List[List]) -> List:
        cache = LRUCache(capacity)
        results: List[Any] = []
        for op, args in zip(operations, operation_args):
            if op == "get":
                results.append(cache.get(args[0]))
            elif op == "put":
                cache.put(args[0], args[1])
                results.append(None)
            else:
                raise ValueError(f"unknown operation {op!r}")
        return results
    
    
    # ---- Task 3: 24-hour notification billing with daily free quota ----
    
    def bill_day(counts: List[int], free_limit: int, unit_price: int) -> List:
        # free_remaining tracks how much of the daily free quota is still unused as hours advance.
        free_remaining = free_limit
        hourly_costs: List[int] = []
    
        for sent in counts:
            # Apply as much remaining free quota as possible to this hour in O(1) arithmetic.
            free_used = min(sent, free_remaining)
            free_remaining -= free_used
            paid_notifications = sent - free_used
            hourly_costs.append(paid_notifications * unit_price)
    
        return [sum(hourly_costs), hourly_costs]
    
    
    # ---- Task 4: Find channels with overlapping followers ----
    
    def overlapping_channels(channel_to_followers: Dict[str, List], target_channel: str) -> List[str]:
        # target_followers: hash set of follower IDs in target_channel for O(1) membership lookups.
        target_followers = set(channel_to_followers.get(target_channel, []))
        if not target_followers:
            return []
    
        matching_channels: List[str] = []
        for channel, followers in channel_to_followers.items():
            if channel == target_channel:
                continue
            for follower in followers:
                if follower in target_followers:
                    matching_channels.append(channel)
                    # Stop scanning this channel as soon as one shared follower is confirmed.
                    break
    
        matching_channels.sort()
        return matching_channels
    
    
    def solve_four_design_tasks(
        rounds: List[List[str]],
        capacity: int,
        operations: List[str],
        operation_args: List[List],
        counts: List[int],
        free_limit: int,
        unit_price: int,
        channel_to_followers: Dict[str, List],
        target_channel: str,
    ) -> List:
        return [
            score_rounds(rounds),
            run_lru(capacity, operations, operation_args),
            bill_day(counts, free_limit, unit_price),
            overlapping_channels(channel_to_followers, target_channel),
        ]
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Each of these four mini-problems replaces a slow "re-scan from scratch" loop with one small state variable or one constant-time lookup structure: - Task 1 (Rock–Paper–Scissors): Like a scoreboard operator who only tracks win_streak and previous_outcome, because both bonuses depend solely on how the current win relates to the immediately preceding rounds. - Task 2 (LRU cache): Like a desk stack of folders paired with an index-card directory. We use Python's OrderedDict (a dictionary backed by a hash table plus a doubly linked list—a chain of nodes with forward and backward pointers so any key can be pulled out and moved to the most-recent end in O(1) time). - Task 3 (Quota billing): Like spending down a gift card chronologically from hour 0 to hour 23—each hour deducts min(sent, free_remaining) from the card and pays unit_price for any leftover notifications. - Task 4 (Overlapping channels): Like loading the target channel's followers into a badge scanner (set) once, then scanning every other channel's roster and stopping at the very first matching badge.

Naive implementations fail under the given constraints: storing LRU keys in a plain list shifts up to capacity elements per access, simulating notification billing one message at a time loops billions of times when counts[i] = 10^9, and testing membership against a follower list instead of a set turns a linear pass into a quadratic scan.

Walk through a tiny trace from our examples: - Task 1: Outcomes W, W, T, W, L in Example 1 score 1 (first win), 1 + 1 = 2 (streak bonus), 0 (tie resets win_streak to 0), 1 + 1 = 2 (win right after a tie triggers the tie-breaker bonus), and 0, totaling 5. - Task 2: With capacity = 1 in Example 2, put("alpha", 0) caches 0, get("alpha") returns 0, put("beta", 9) evicts "alpha", and get("alpha") returns -1. - Task 3: With counts = [4, 6, 3, 0, 2, ...], free_limit = 8, unit_price = 5: hour 0 uses 4 free (4 left, cost 0); hour 1 uses the last 4 free and pays for 6 - 4 = 2 (cost = 10); hours 2 and 4 pay 15 and 10, totaling 35. - Task 4: Target "chess" has ["u1", "u2", "u3"]; "art" hits "u3" (match), "cooking" has ["u8"] (no hit), and "speedrun" hits "u2" (match), returning ["art", "speedrun"].

Complexity

  • Task 1 (RPS): O(N) time and O(N) output space (with O(1) auxiliary space) for N rounds, because we inspect each round once using two scalar variables (win_streak and previous_outcome).
  • Task 2 (LRU cache): O(1) average time per get and put (one hash-table lookup plus O(1) pointer updates in OrderedDict), and O(capacity) space inside the cache (plus O(Q) output space to record Q operation results).
  • Task 3 (Notification billing): O(H) time and space where H = 24 hours—each hour performs constant-time min, subtraction, and multiplication regardless of how large counts[i] or free_limit is.
  • Task 4 (Overlapping channels): O(C + M + R log R) time and O(|target| + R) space, where C is the number of channels, M is the total number of follower memberships across all channels, and R is the number of matching channels sorted at the end; building the set checks |target| entries and scanning other channels checks each membership in O(1) average time.

Edge cases

  • RPS: Single-round inputs never trigger bonuses; both "L" and "T" reset win_streak to 0; "T", "T", "W" still earns the +1 tie-break bonus; Bonus A and Bonus B cannot fire on the same round because the previous round cannot be both "W" and "T".
  • LRU cache: A missed get returns -1 without modifying recency; storing falsy values like 0 or "" still counts as a cache hit; overwriting an existing key refreshes its recency without evicting anything; capacity = 0 rejects all storage cleanly.
  • Billing: free_limit can run out mid-hour; free_limit = 0 bills every notification; free_limit exceeding the daily sum bills 0 everywhere; maximum daily cost 24 * 10^9 * 10^6 = 2.4 * 10^16 stays exact in Python int (whereas an IEEE-754 double-precision float, the standard 64-bit floating-point type, loses exact integer precision above 2^53 ≈ 9 * 10^15).
  • Overlapping channels: target_channel itself is always skipped; duplicate follower IDs inside a channel list do not produce duplicate channel names because of break; an empty target follower list immediately returns [].

Common mistakes

  • Awarding the streak bonus on the very first win: Bonus A applies only when win_streak >= 2 (W, W, W gives +0, +1, +1 bonus, not +1, +1, +1).
  • Letting a tie preserve a win streak: W, T, W is not two wins in a row—the second win gets Bonus B (tie-break), not Bonus A, and a third win after that (W, T, W, W) starts streak counting from the post-tie win.
  • Checking truthiness (if not self.data.get(key):) in LRUCache: Treats a valid cached value of 0 as a cache miss. Always check if key not in self.data:.
  • Evicting before checking key existence in put: If the cache is full and put updates an existing key, evicting first wrongly deletes the oldest key even though the key count did not grow.
  • Applying free_limit per hour instead of across the whole day: Resetting the free quota every hour underbills whenever multiple hours send notifications.
  • Forgetting to exclude target_channel in Task 4: Any non-empty channel shares followers with itself, so skipping channel == target_channel is essential.

Alternative approaches

  • Hand-rolled doubly linked list + dict for LRUCache: If an interviewer asks not to use OrderedDict, define a Node(key, val, prev, next) class with dummy head (LRU) and tail (MRU) sentries plus a nodes: Dict[Any, Node] map. Unlinking a node and inserting it before tail each take four pointer assignments in O(1) time.
  • Thread-safe concurrent LRUCache: Because get reorders the underlying linked list, cache reads mutate internal pointers, making a plain reader-writer lock unsafe. Start with a single mutex (a mutual-exclusion lock allowing one thread inside the critical section at a time) around get and put; under heavy multi-core contention, use lock sharding by splitting keys via hash(key) % S across S independent locked sub-caches of capacity capacity / S.
  • Prefix sums for Task 3 billing: Compute cumulative alerts prefix[i] and free usage min(prefix[i], free_limit) - min(prefix[i - 1], free_limit). This matches the greedy free_remaining loop and extends naturally if queries ask for arbitrary hour ranges after precomputation.

Follow-up questions

  • How would you preprocess the data in Part 4 if the service must answer thousands of repeated overlap queries across different target channels? Build an inverted index (a lookup map flipped inside out so each subscriber_id maps to the list of channels they subscribe to) once in O(M) time and space. To answer a query for target_channel, iterate over each subscriber u of target_channel, collect all channels in inverted[u] into an answer set, and discard target_channel. For high-degree users subscribed to tens of thousands of channels, you can precompute overlaps for heavy nodes or cache per-channel results and invalidate on subscribe/unsubscribe updates.
  • What are the asymptotic runtime and memory bounds of your single-query and multi-query solutions? For a single Part 4 lookup, building target_followers and scanning all channel memberships takes O(C + M + R log R) time and O(|target| + R) space, where C is the channel count, M is total memberships, and R is matching channels. With the inverted index for repeated queries, preprocessing takes O(C + M) time and space once, and each query runs in O(sum of len(inverted[u]) for u in target_channel + R log R) time. Parts 1, 2, and 3 take O(N) total time, O(1) average time per cache operation with O(capacity) cache memory, and O(24) time respectively.
  • How does your Part 4 design perform at a scale of 100,000 channels and 1,000,000 total follower-channel pairs? At C = 10^5 and M = 10^6, the average channel has just 10 subscribers, so a single linear pass with hash-set lookups inspects at most 10^6 entries and finishes in tens of milliseconds in Python. However, serving 10,000 queries back-to-back via full scans would perform 10^10 checks and stall for minutes, making the one-time O(M) inverted index well worth its ~10^6-entry memory footprint.

Follow-up questions

Similar questions

More Twitch interview questions

All 5 Twitch questions →