Best Currency Conversion Path and Alternating-Category Paging

Medium · Coding & Algorithms · Software Engineer · Onsite

Problem Statement

Implement two standalone functions in the same module:

1. Best Directed Currency Conversion (can_convert)

def can_convert(source_currency: str, target_currency: str, rates: List[List]) -> float:

You receive a collection of directed foreign-exchange quotes rates, where each element [from_code, to_code, multiplier] states that 1.0 unit of from_code trades directly for multiplier units of to_code (quotes are one-way unless the reverse quote is also listed).

Multi-step trades multiply their individual multipliers along the chosen directed route. Compute and return the highest total multiplier obtainable from source_currency to target_currency:

  • Converting a currency to itself (source_currency == target_currency) requires zero trades and returns 1.0, even if rates is empty or omits that code.
  • If target_currency cannot be reached from source_currency along directed quotes, return 0.0.

2. Category-Alternating Pagination (get_page)

def get_page(items: List[Dict], page_size: int, page_number: int) -> List[Dict]:

You receive a sequence of item dictionaries items, where each dictionary stores an 'id' and a category label under key 'cat' (or 'category'). Before slicing into pages, rearrange the entire list so that no two adjacent items in the full sequence have the same category (including across page boundaries):

  • Order preservation: Among all valid full-list rearrangements without back-to-back matching categories, choose the one that keeps earlier items as near the front as possible—specifically, the valid arrangement whose sequence of original indices is lexicographically smallest (comparing slot by slot from left to right).
  • Infeasible fallback: When no valid full-list rearrangement exists (for example, one category dominates too many positions), leave items in its original order.
  • 0-indexed slicing: Return page page_number of size page_size, corresponding to slice [page_number * page_size : (page_number + 1) * page_size] of the resulting full list. Return [] if page_number lies beyond the available pages, page_number < 0, or page_size <= 0.

Examples

Example 1

Input:
  source_currency = "CAD"
  target_currency = "JPY"
  rates = [["CAD", "AUD", 1.1], ["AUD", "JPY", 105.0], ["CAD", "JPY", 110.0]]
Output: 115.5

Trading CAD -> JPY directly yields 110.0, whereas routing CAD -> AUD -> JPY yields 1.1 * 105.0 = 115.5. The function returns the larger multiplier 115.5.

Example 2

Input:
  items = [
      {"id": 10, "cat": "news"},
      {"id": 20, "cat": "news"},
      {"id": 30, "cat": "sports"},
      {"id": 40, "cat": "music"},
  ]
  page_size = 2
  page_number = 0
Output: [{"id": 10, "cat": "news"}, {"id": 30, "cat": "sports"}]

Keeping original order would place two "news" items side by side (10, 20). Promoting item 30 ("sports") ahead of item 20 produces the full alternating sequence [10 ("news"), 30 ("sports"), 20 ("news"), 40 ("music")]. Slicing page 0 of length 2 returns [10, 30] (and page 1 would return [20, 40]).

Example 3

Input:
  items = [
      {"id": 1, "cat": "tech"},
      {"id": 2, "cat": "tech"},
      {"id": 3, "cat": "tech"},
      {"id": 4, "cat": "art"},
  ]
  page_size = 2
  page_number = 0
Output: [{"id": 1, "cat": "tech"}, {"id": 2, "cat": "tech"}]

Three "tech" items cannot sit in four slots without at least two touching. Because no valid alternating arrangement exists, the original sequence is kept unchanged and page 0 returns items 1 and 2.

Constraints

  • Currency quotes (can_convert):
    • All multipliers are positive floats (multiplier > 0).
    • Directed cycles may appear in rates, but every directed cycle has a product <= 1.0 (no unbounded gain loop).
  • Pagination (get_page):
    • 0 <= len(items) <= 10,000
    • 1 <= page_size <= 50 for normal calls (return [] if page_size <= 0 or page_number < 0).
    • Relative arrival order within each category, and earliest-index priority across distinct categories whenever unforced, must be preserved.

Step-by-step walkthrough

  1. Understand both problems and edge rules

    This interview prompt combines two independent problems in one file:

    1. Part 1 (can_convert): Each entry [source, target, rate] means 1 unit of source buys rate units of target (one-way). Chaining conversions multiplies the rates along the path. Return the largest conversion rate from source_currency to target_currency, or 0.0 if no path exists. No cycle has a product strictly greater than 1.0.
    2. Part 2 (get_page): Given a list of items, reorder the entire list so no two adjacent items share a category while keeping items as close to their original positions as possible, then return slice page_number of length page_size. If no diverse arrangement exists, slice the original list unchanged.

    To handle every practical input cleanly, we pin down the small details:

    • In Part 1, converting a currency to itself (source_currency == target_currency) returns 1.0, and unknown or unreachable currencies return 0.0.
    • In Part 2, items may store their category under either 'cat' or 'category', so we accept both keys. page_number is 0-indexed, and out-of-range pages return [].
    • For order preservation in Part 2, if two valid full arrangements exist, we prefer the one that picks an earlier original index at the first slot where they differ.
  2. Part 1: Why Dijkstra fails when exchange rates exceed 1

    Model currencies as nodes in a directed graph (a network of one-way arrows) where each arrow carries its exchange rate. Trying every simple path with backtracking can take exponential time, so we want a graph-relaxation method.

    It is tempting to adapt Dijkstra's algorithm by always locking in the currency with the largest amount found so far. That works when every rate is <= 1.0, because extending a path can only shrink the amount. However, real currency rates often exceed 1.0 (for example, 1 GBP buys more than 1 USD, or 1 USD buys 150 JPY), so a path that starts smaller can jump ahead later:

    Direct path:   AAA ----(0.5)----> BBB ----(1.0)----> DDD   (gives 0.5)
    Two-hop path:  AAA --(0.4)--> CCC --(2.0)--> BBB --(1.0)--> DDD   (gives 0.8)
    

    If we lock in BBB at 0.5 before expanding CCC (which only has 0.4), DDD gets stuck at 0.5 instead of 0.8.

    Bellman-Ford avoids locking anything in early. We store best_rate[c], the best amount of currency c reachable from 1.0 unit of source_currency so far, and sweep through all rates in rounds:

    • Whenever best_rate[src] * rate > best_rate[dst], we update best_rate[dst].
    • Because no cycle has a product above 1.0, the best path never needs to repeat a currency, so it uses at most V - 1 edges (where V is the number of distinct currencies).
    • Running at most V - 1 rounds guarantees we find the optimal path, and stopping early when a round changes nothing makes typical inputs very fast. The V - 1 cap also protects against tiny floating-point rounding above 1.0 on break-even cycles (such as 0.1 * 3.0 * (1 / 0.3) = 1.0000000000000002).
  3. Code Part 1: Bellman-Ford for maximum product

    Let's translate the round-by-round update directly into Python. Any currency never reached stays absent from best_rate, so best_rate.get(target_currency, 0.0) cleanly returns 0.0.

    def can_convert(source_currency: str, target_currency: str, rates: List[List]) -> float:
        # Converting a currency to itself requires zero trades and keeps 1.0 unit.
        if source_currency == target_currency:
            return 1.0
    
        # Collect every distinct currency code so we know the maximum simple-path length.
        currencies: Set[str] = set()
        for src, dst, rate in rates:
            currencies.add(src)
            currencies.add(dst)
    
        # best_rate: maps currency -> largest amount reachable from 1.0 unit of source_currency,
        # e.g. {"CAD": 1.0, "AUD": 1.1, "JPY": 115.5}.
        best_rate: Dict[str, float] = {source_currency: 1.0}
    
        # Bellman-Ford relaxation: because no cycle has a product > 1.0, an optimal path
        # never needs to repeat a currency and therefore uses at most V - 1 edges.
        max_rounds = max(0, len(currencies) - 1)
        for _ in range(max_rounds):
            updated_in_round = False
            for src, dst, rate in rates:
                if src not in best_rate:
                    continue
                candidate_rate = best_rate[src] * rate
                if candidate_rate > best_rate.get(dst, 0.0):
                    best_rate[dst] = candidate_rate
                    updated_in_round = True
            # Stop early once a full pass over all rates finds no better conversion.
            if not updated_in_round:
                break
    
        return best_rate.get(target_currency, 0.0)
    
  4. Part 2: When is a diverse order possible, and when is a category forced?

    In Part 2, pagination must happen after reordering the entire list. If we reordered each page on its own, the last item of page 0 and the first item of page 1 could share a category, or page 0 could greedily leave page 1 with two identical categories stuck together.

    What if we build the full list left to right by always picking the earliest remaining item whose category differs from the previous slot? Look at what happens on [A1, B2, C3, A4, A5]:

    Naive greedy:  A1 -> B2 -> C3 -> A4 -> [stuck! only A5 is left, right next to A4]
    Valid order:   A1 -> B2 -> A4 -> C3 -> A5   (A4 had to jump ahead of C3!)
    

    Why did A4 have to jump ahead of C3 at slot 3? At that moment 3 slots remained (3, 4, 5) and 2 of them were A's (A4, A5). To keep two A's apart inside 3 slots, they must sit at slots 3 and 5!

    Counting remaining items gives us the exact rule at every step:

    1. Overall feasibility (at the start): In n total slots, at most (n + 1) // 2 non-adjacent slots exist (slots 0, 2, 4, ...). So a diverse order exists if and only if every category satisfies 2 * count <= n + 1. If any category breaks this, return list(items) unchanged.
    2. Forced majority choice (with remaining slots left): If some category holds strictly more than half of the remaining items (2 * count > remaining), it must take the current slot (and every second slot after). At most one category can exceed half, and it can never equal prev_group because we maintained 2 * count[prev_group] <= remaining when placing prev_group one step ago.
    3. Free choice (when no category exceeds half): Placing any category different from prev_group leaves every category with 2 * count <= remaining for the remaining remaining - 1 slots, so we can never get stuck! To preserve original order as much as possible, we pick the category (!= prev_group) whose next unused item has the smallest original index.
  5. Part 2: Keep choices fast with queues and two heaps

    Scanning all categories at each of the n slots would take O(n * k) time for k categories, which is slow when n = 10,000 and there are thousands of distinct categories. Instead, we keep:

    • group_queues[g]: a deque of original indices for category g in arrival order.
    • heads_heap: a min-heap of (earliest_index, group_idx) to find the earliest available item not in prev_group.
    • largest_heap: a min-heap of (-remaining_count, group_idx) (negated so the largest count rises to the top) to check whether any category has 2 * count > remaining.
    Items: [B1, A2, A3, A4, C5]   (indices 0..4)
    
    group_queues:
      group 0 ('B'): deque([0])
      group 1 ('A'): deque([1, 2, 3])
      group 2 ('C'): deque([4])
    
    largest_heap top -> (-3, group 1): 2 * 3 = 6 > 5 remaining, so group 1 ('A') is forced!
    

    When a category places an item, its front index and count change. Instead of searching inside the heaps to delete old tuples, we push updated tuples and use lazy deletion: whenever we inspect the top of a heap, if its cached position or count no longer matches group_queues[g], we pop and discard it.

    def _get_category(item: Dict) -> Any:
        """Return an item's category value from either 'cat' or 'category'."""
        if "cat" in item:
            return item["cat"]
        return item["category"]
    
    
    def find_forced_group(
        largest_heap: List[Tuple[int, int]],
        group_queues: List[deque],
        remaining: int,
    ) -> Optional[int]:
        """Return the category ID holding strictly more than half of the remaining items, if any."""
        # Lazy deletion: discard heap entries whose cached count no longer matches the live queue size.
        while largest_heap:
            neg_count, group_idx = largest_heap[0]
            cached_count = -neg_count
            actual_count = len(group_queues[group_idx])
            if cached_count == actual_count:
                break
            heapq.heappop(largest_heap)
    
        if largest_heap:
            neg_count, group_idx = largest_heap[0]
            majority_count = -neg_count
            # Strictly > remaining / 2 (written as 2 * count > remaining to avoid float division)
            # means this category must occupy every other slot starting right now.
            if 2 * majority_count > remaining:
                return group_idx
        return None
    
    
    def find_earliest_allowed_group(
        heads_heap: List[Tuple[int, int]],
        group_queues: List[deque],
        prev_group: int,
    ) -> int:
        """Return the category ID (other than prev_group) whose next item appeared earliest."""
        # Temporarily hold the single live entry of prev_group if it sits at the top of the heap.
        skipped_prev: Optional[Tuple[int, int]] = None
        chosen_group = -1
    
        while heads_heap:
            next_pos, group_idx = heapq.heappop(heads_heap)
            # Skip stale entries pointing to an item position that was already placed earlier.
            if not group_queues[group_idx] or group_queues[group_idx][0] != next_pos:
                continue
            if group_idx == prev_group:
                skipped_prev = (next_pos, group_idx)
                continue
            chosen_group = group_idx
            break
    
        # Restore prev_group's live entry so it is available again on the following slot.
        if skipped_prev is not None:
            heapq.heappush(heads_heap, skipped_prev)
    
        return chosen_group
    
  6. Code Part 2: Build the full diverse order and slice the page

    Now we connect the pieces: group indices by category, verify the 2 * count <= n + 1 rule, initialize both heaps, fill all n slots one by one, and slice out the requested page. Guarding page_size <= 0 or page_number < 0 ensures negative page numbers return [] rather than wrapping around from the back of the Python list.

    def build_diverse_order(items: List[Dict]) -> List[Dict]:
        """Reorder items so adjacent categories differ while staying as close to original order
        as possible, or return a copy of items unchanged if no diverse arrangement exists."""
        total_items = len(items)
    
        group_id_by_cat: Dict[Any, int] = {}
        group_queues: List[deque] = []
        for pos, item in enumerate(items):
            cat = _get_category(item)
            if cat not in group_id_by_cat:
                group_id_by_cat[cat] = len(group_queues)
                group_queues.append(deque())
            group_queues[group_id_by_cat[cat]].append(pos)
    
        for queue in group_queues:
            if 2 * len(queue) > total_items + 1:
                return list(items)
    
        heads_heap: List[Tuple[int, int]] = []
        largest_heap: List[Tuple[int, int]] = []
        for group_idx, queue in enumerate(group_queues):
            heads_heap.append((queue[0], group_idx))
            largest_heap.append((-len(queue), group_idx))
        heapq.heapify(heads_heap)
        heapq.heapify(largest_heap)
    
        ordered_items: List[Dict] = []
        prev_group = -1
        remaining = total_items
    
        while remaining > 0:
            chosen_group = find_forced_group(largest_heap, group_queues, remaining)
            if chosen_group is None:
                chosen_group = find_earliest_allowed_group(heads_heap, group_queues, prev_group)
    
            item_pos = group_queues[chosen_group].popleft()
            ordered_items.append(items[item_pos])
            remaining -= 1
            prev_group = chosen_group
    
            if group_queues[chosen_group]:
                heapq.heappush(heads_heap, (group_queues[chosen_group][0], chosen_group))
                heapq.heappush(largest_heap, (-len(group_queues[chosen_group]), chosen_group))
    
        return ordered_items
    
    
    def get_page(items: List[Dict], page_size: int, page_number: int) -> List[Dict]:
        if page_size <= 0 or page_number < 0:
            return []
    
        ordered_items = build_diverse_order(items)
        start = page_number * page_size
        end = start + page_size
        return ordered_items[start:end]
    
  7. Trace Part 2 step by step on a tricky example

    Let's trace items = [A1, B2, C3, A4, A5] with page_size = 2:

    Start: counts A=3, B=1, C=1, total n=5.
    Feasibility: max 2 * 3 = 6 <= 5 + 1, so a diverse order exists.
    
    Slot 0 (remaining=5, prev=none): 2*count(A) = 6 > 5 -> A is FORCED  -> place A1
    Slot 1 (remaining=4, prev=A):    2*count(A) = 4 <= 4 -> free choice -> earliest non-A is B2
    Slot 2 (remaining=3, prev=B):    2*count(A) = 4 > 3 -> A is FORCED  -> place A4
    Slot 3 (remaining=2, prev=A):    2*count(A) = 2 <= 2 -> free choice -> earliest non-A is C3
    Slot 4 (remaining=1, prev=C):    2*count(A) = 2 > 1 -> A is FORCED  -> place A5
    
    Full diverse order: [A1, B2, A4, C3, A5]
      page 0 (slice 0:2) -> [A1, B2]
      page 1 (slice 2:4) -> [A4, C3]   (boundary B2 | A4 is also diverse!)
      page 2 (slice 4:6) -> [A5]
    

    On Example 2 ([10(news), 20(news), 30(sports), 40(music)], n = 4): slot 0 has no forced majority (2 * 2 <= 4) and picks earliest item 10(news); slot 1 excludes news and picks earliest allowed item 30(sports); slot 2 picks 20(news); slot 3 places 40(music). The full order is [10, 30, 20, 40], so page 0 of size 2 is [10(news), 30(sports)].

  8. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    from collections import deque
    import heapq
    
    
    # ---------- Part 1: Maximum currency conversion rate ----------
    
    def can_convert(source_currency: str, target_currency: str, rates: List[List]) -> float:
        # Converting a currency to itself requires zero trades and keeps 1.0 unit.
        if source_currency == target_currency:
            return 1.0
    
        # Collect every distinct currency code so we know the maximum simple-path length.
        currencies: Set[str] = set()
        for src, dst, rate in rates:
            currencies.add(src)
            currencies.add(dst)
    
        # best_rate: maps currency -> largest amount reachable from 1.0 unit of source_currency,
        # e.g. {"CAD": 1.0, "AUD": 1.1, "JPY": 115.5}.
        best_rate: Dict[str, float] = {source_currency: 1.0}
    
        # Bellman-Ford relaxation: because no cycle has a product > 1.0, an optimal path
        # never needs to repeat a currency and therefore uses at most V - 1 edges.
        # Capping at V - 1 rounds also prevents floating-point drift on 1.0-product cycles
        # from looping forever.
        max_rounds = max(0, len(currencies) - 1)
        for _ in range(max_rounds):
            updated_in_round = False
            for src, dst, rate in rates:
                if src not in best_rate:
                    continue
                candidate_rate = best_rate[src] * rate
                if candidate_rate > best_rate.get(dst, 0.0):
                    best_rate[dst] = candidate_rate
                    updated_in_round = True
            # Stop early once a full pass over all rates finds no better conversion.
            if not updated_in_round:
                break
    
        return best_rate.get(target_currency, 0.0)
    
    
    # ---------- Part 2: Diversity-aware pagination ----------
    
    def _get_category(item: Dict) -> Any:
        """Return an item's category value from either 'cat' or 'category'."""
        if "cat" in item:
            return item["cat"]
        return item["category"]
    
    
    def find_forced_group(
        largest_heap: List[Tuple[int, int]],
        group_queues: List[deque],
        remaining: int,
    ) -> Optional[int]:
        """Return the category ID holding strictly more than half of the remaining items, if any."""
        # Lazy deletion: discard heap entries whose cached count no longer matches the live queue size.
        while largest_heap:
            neg_count, group_idx = largest_heap[0]
            cached_count = -neg_count
            actual_count = len(group_queues[group_idx])
            if cached_count == actual_count:
                break
            heapq.heappop(largest_heap)
    
        if largest_heap:
            neg_count, group_idx = largest_heap[0]
            majority_count = -neg_count
            # Strictly > remaining / 2 (written as 2 * count > remaining to avoid float division)
            # means this category must occupy every other slot starting right now.
            if 2 * majority_count > remaining:
                return group_idx
        return None
    
    
    def find_earliest_allowed_group(
        heads_heap: List[Tuple[int, int]],
        group_queues: List[deque],
        prev_group: int,
    ) -> int:
        """Return the category ID (other than prev_group) whose next item appeared earliest."""
        # Temporarily hold the single live entry of prev_group if it sits at the top of the heap.
        skipped_prev: Optional[Tuple[int, int]] = None
        chosen_group = -1
    
        while heads_heap:
            next_pos, group_idx = heapq.heappop(heads_heap)
            # Skip stale entries pointing to an item position that was already placed earlier.
            if not group_queues[group_idx] or group_queues[group_idx][0] != next_pos:
                continue
            if group_idx == prev_group:
                skipped_prev = (next_pos, group_idx)
                continue
            chosen_group = group_idx
            break
    
        # Restore prev_group's live entry so it is available again on the following slot.
        if skipped_prev is not None:
            heapq.heappush(heads_heap, skipped_prev)
    
        return chosen_group
    
    
    def build_diverse_order(items: List[Dict]) -> List[Dict]:
        """Reorder items so adjacent categories differ while staying as close to original order
        as possible, or return a copy of items unchanged if no diverse arrangement exists."""
        total_items = len(items)
    
        # Assign each distinct category an integer ID 0, 1, ... so heap tuples never compare
        # raw category values directly, and store each category's item indices in arrival order.
        # group_queues[g]: deque of original indices, e.g. deque([0, 3, 4]) for category g.
        group_id_by_cat: Dict[Any, int] = {}
        group_queues: List[deque] = []
        for pos, item in enumerate(items):
            cat = _get_category(item)
            if cat not in group_id_by_cat:
                group_id_by_cat[cat] = len(group_queues)
                group_queues.append(deque())
            group_queues[group_id_by_cat[cat]].append(pos)
    
        # Pigeonhole feasibility check: n slots have ceil(n / 2) = (n + 1) // 2 alternating spots,
        # so any category with 2 * count > n + 1 must place two items side by side.
        for queue in group_queues:
            if 2 * len(queue) > total_items + 1:
                return list(items)
    
        # heads_heap: min-heap of (front_item_index, group_idx) ordered by earliest original position.
        # largest_heap: min-heap of (-remaining_count, group_idx) acting as a max-heap by count.
        heads_heap: List[Tuple[int, int]] = []
        largest_heap: List[Tuple[int, int]] = []
        for group_idx, queue in enumerate(group_queues):
            heads_heap.append((queue[0], group_idx))
            largest_heap.append((-len(queue), group_idx))
        heapq.heapify(heads_heap)
        heapq.heapify(largest_heap)
    
        ordered_items: List[Dict] = []
        prev_group = -1
        remaining = total_items
    
        # Fill slots left to right: place a forced majority category if one exists,
        # otherwise pick the earliest available item whose category differs from prev_group.
        while remaining > 0:
            chosen_group = find_forced_group(largest_heap, group_queues, remaining)
            if chosen_group is None:
                chosen_group = find_earliest_allowed_group(heads_heap, group_queues, prev_group)
    
            item_pos = group_queues[chosen_group].popleft()
            ordered_items.append(items[item_pos])
            remaining -= 1
            prev_group = chosen_group
    
            # Push updated entries for chosen_group; older entries are cleaned up lazily when popped.
            if group_queues[chosen_group]:
                heapq.heappush(heads_heap, (group_queues[chosen_group][0], chosen_group))
                heapq.heappush(largest_heap, (-len(group_queues[chosen_group]), chosen_group))
    
        return ordered_items
    
    
    def get_page(items: List[Dict], page_size: int, page_number: int) -> List[Dict]:
        # Guard against non-positive page sizes or negative page numbers (which would slice from the end).
        if page_size <= 0 or page_number < 0:
            return []
    
        ordered_items = build_diverse_order(items)
        start = page_number * page_size
        end = start + page_size
        return ordered_items[start:end]
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of Part 1 like shopping across airport currency booths: each booth turns 1 unit of one currency into rate units of another, so walking through a chain of booths multiplies the rates together. Think of Part 2 like seating a waiting line of people wearing team jerseys so no two teammates sit side by side: normally you seat whoever arrived earliest from a different team than the last person seated, unless one team has more than half of the remaining seats—in which case that team must take the very next seat (and every other seat after) or two of its members will be forced together at the end.

The obvious approaches fail in subtle ways on both parts. In Part 1, trying every simple path is exponentially slow, while Dijkstra's algorithm (a graph search that permanently locks in the highest-value node at each step) fails because exchange rates can exceed 1.0, allowing a path that starts smaller (0.4) to multiply by 2.0 later and beat 0.5. In Part 2, reordering only one page at a time can put identical categories side by side across page boundaries, and greedily picking the earliest non-matching item without checking category counts gets trapped when a majority category runs out of separators.

Let's trace tiny examples of how our two algorithms solve these traps:

  • Part 1 (Bellman-Ford): We use the Bellman-Ford algorithm (a method that repeatedly sweeps through all edges to improve the best known value at each node, called edge relaxation). On Example 1 (CAD -> AUD (1.1), AUD -> JPY (105.0), CAD -> JPY (110.0)), best_rate starts at {"CAD": 1.0}, updates AUD to 1.1 and JPY to 1.1 * 105.0 = 115.5 (beating the direct 110.0), sees no further improvements on the next round, and returns 115.5. Even if AAA -> BBB (0.5) competes with AAA -> CCC (0.4) -> BBB (2.0), round 1 finds BBB = 0.5 and CCC = 0.4, and round 2 relaxes CCC -> BBB to 0.4 * 2.0 = 0.8.
  • Part 2 (Count-aware greedy with two heaps): On Example 2 ([10(news), 20(news), 30(sports), 40(music)], 4 items), no category exceeds half (2 * 2 <= 4), so slot 0 picks 10(news), slot 1 skips news to pick the earliest non-news item 30(sports), slot 2 picks 20(news), and slot 3 places 40(music), giving [10, 30, 20, 40] and page 0 (size 2) = [10, 30] (while on [A1, A2, B3], 2 * 2 > 3 forces A1 into slot 0 right away). To avoid scanning all categories at every slot, we maintain a min-heap (a priority queue that pops the smallest tuple in O(log n) time) of earliest indices (heads_heap) and a max-heap via negation (largest_heap) for remaining counts, using lazy deletion (leaving outdated tuples inside the heap and discarding them only when they reach the top). This produces the valid list with the smallest lexicographical order of original indices (comparing two arrangements slot by slot from left to right).

Complexity

Part 1 (V distinct currencies, E rate entries):

  • Time: O(V * E) in the worst case because we run at most V - 1 rounds and scan all E rate entries in each round, stopping early as soon as a full round makes no updates.
  • Space: O(V) because we store at most one entry per currency in currencies and best_rate.

Part 2 (n total items, k distinct categories):

  • Time: O(n log n) per call because grouping the n items takes O(n) time, and each of the n placements pushes at most three tuples onto the heaps and pops each tuple at most once, with every heap operation costing O(log k) <= O(log n).
  • Space: O(n) because the per-category queues, the two heaps, and ordered_items each hold O(n) elements in total. (If a service serves many pages of the same static list, ordered_items can be computed once and cached so each page slice takes O(page_size) time.)

Edge cases

  • Part 1, source_currency == target_currency: Returns 1.0 immediately, even when rates is empty or does not mention that currency.
  • Part 1, unreachable or unknown currency: Stays absent from best_rate and returns 0.0. Quotes are one-way (CAD -> AUD does not imply AUD -> CAD).
  • Part 1, duplicate pairs: If two entries list the same (src, dst) pair with different rates, the larger rate naturally wins the > comparison.
  • Part 1, break-even cycles (product == 1.0): Floating-point rounding can turn a product of 1.0 into 1.0000000000000002; capping the outer loop at V - 1 rounds guarantees termination.
  • Part 2, empty list, negative page_number, or page past the end: Returns [] cleanly without Python negative-index wrap-around.
  • Part 2, impossible diversity (such as Example 3 [tech, tech, tech, art], where 2 * 3 = 6 > 4 + 1): Falls back to slicing the original list unchanged.
  • Part 2, page boundaries: Because we reorder the full list before slicing, the last item of page p and the first item of page p + 1 also have different categories.

Common mistakes

  • Using Dijkstra's algorithm when rates can exceed 1.0: Locking in a currency the first time it is popped misses paths that start smaller and multiply by a rate > 1.0 later.
  • Relaxing until convergence without a V - 1 round cap: Tiny floating-point rounding above 1.0 on a break-even cycle can cause an uncapped while updated: loop to run forever.
  • Reordering one page at a time instead of the whole list: Adjacent pages can collide on the same category at their boundary, or earlier pages can starve later pages of separator items.
  • Skipping the 2 * count > remaining majority check: Picking the earliest item of a different category turns [A1, B2, C3, A4, A5] into a dead end at the last two A's.
  • Always picking the most frequent category: A standard "most frequent first" heap finds some valid arrangement, but breaks stability on inputs like [A1, B2, C3, C4] by starting with C3 instead of [A1, C3, B2, C4].

Alternative approaches

  • Part 1, negative-log shortest paths: Replacing each rate r with -log(r) converts maximizing a product r1 * r2 into minimizing a sum (-log r1) + (-log r2). Bellman-Ford then runs in log space, avoiding overflow on huge chains of multiplications and directly connecting to negative-cycle arbitrage detection.
  • Part 1, Floyd-Warshall algorithm: Computes maximum conversion rates between all pairs of currencies in O(V^3) time, which is handy when V is small (for example <= 200) and you answer many queries on a fixed rate table.
  • Part 2, count buckets instead of largest_heap: Because category counts only decrease by 1 per step, maintaining buckets of categories grouped by current count lets a max_count pointer walk strictly downward in O(n) total time, though heads_heap still uses O(n log k) for index order.

Follow-up questions

  • How could you identify a profitable cycle of trades whose combined multiplier exceeds 1.0? Initialize best_rate[c] = 1.0 for every currency c (acting like a virtual starting node connected to every currency so disconnected loops are not missed), run V - 1 rounds of Bellman-Ford, and then run one extra V-th check over all edges. If any edge still improves best_rate[dst] by more than a tiny relative tolerance (such as 1 + 1e-9 to ignore floating-point rounding noise on break-even loops), a profitable arbitrage cycle exists—equivalent to a negative cycle (a loop whose edge weights sum to less than zero) under -log(rate) weights. To reconstruct the loop itself, store parent[dst] = src on each improvement, step backward V times from the improved node to guarantee landing inside the cycle, and trace back until a currency repeats.
  • What happens to time and memory guarantees if items arrive from an unbounded live stream instead of a finite array? No online algorithm can strictly guarantee category alternation across an unbounded stream with finite memory, because the stream could suddenly send thousands of items of the same category in a row after you have already emitted all potential separators. In practice, systems maintain a sliding lookahead buffer of B items: read one new item into the buffer, pick the next output item using the exact same 2 * count > B majority check (or emit the earliest item if the buffer itself is impossible), and repeat. Because item arrivals increase counts as well as decrease them, replace lazy deletion with a balanced tree or indexed heap of size at most B so each item takes O(log B) time (O(N log B) over N streamed items) and O(B) memory.
  • How would you adapt the rate-lookup engine when quote updates stream in continuously? Cache the computed best_rate table per heavily queried source currency alongside a version stamp so readers see a consistent snapshot. When a batch of rates only increases, existing paths remain valid lower bounds, so you can push the endpoints of the raised edges into a queue and propagate improvements outward (queue-based Bellman-Ford / SPFA) without starting from 1.0 everywhere. When any rate decreases, paths that relied on that edge may become invalid and cannot be lowered by "max" relaxations alone, so recompute affected sources from scratch in O(V * E) (fast for the ~150 real-world currencies) and re-run the V-th-round arbitrage check on each update batch.

Follow-up questions

Similar questions

More Mavenclinic interview questions

All 1 Mavenclinic questions →