Multi-Hop Currency Conversion and Best Simple Route

Easy · Software Engineering Fundamentals · Software Engineer · Technical Screen

Problem Statement

Given a collection of foreign-exchange quotes where each tuple (a, b, rate) states that 1 unit of currency a converts into rate units of currency b, implement two functions—one for consistent exchange tables and a second for finding the highest-yielding simple conversion path when quotes can disagree:

NO_ROUTE = -1
Quote = Tuple[str, str, float]

def convert(
    quotes: List[Quote],
    queries: List[Tuple[str, str, float]],
    reciprocal: bool = True,
) -> List[float]: ...

def max_amount(
    quotes: List[Quote],
    source: str,
    target: str,
    amount: float,
    reciprocal: bool = True,
) -> float: ...

Both functions follow these shared rules:

  • Directionality (reciprocal): When reciprocal=True (the default), a quote (a, b, r) can be traversed forward as a -> b with multiplier r and in reverse as b -> a with multiplier 1 / r. When reciprocal=False, only the forward edge a -> b exists.
  • Rate validation: Every quote rate must be strictly positive (rate > 0, rejecting 0, negatives, and NaN with ValueError even if queries is empty).
  • Zero-hop identity: Whenever source == target, return amount unchanged, even if that currency code does not appear in quotes.
  • Unreachable destinations: Return NO_ROUTE (-1) when no valid path connects source to target.
  • Numeric generality: Rates and amounts may be passed as float or exact fractions.Fraction objects, so stick to standard arithmetic (*, /, >) without forcing conversions to float.

The two parts differ in their path assumptions:

  1. convert(quotes, queries, reciprocal=True): Assumes all quotes are path-consistent (every valid path between two currencies yields the same multiplier). For each (source, target, amount) tuple in queries, return the converted amount in target (or -1 if unreachable).
  2. max_amount(quotes, source, target, amount, reciprocal=True): Quotes need not be path-consistent, and multiple parallel quotes for the same pair may exist. Return the largest target amount obtainable over all simple paths from source to target—routes that visit each currency at most once.

Examples

Example 1

Input:

from fractions import Fraction

quotes = [("CAD", "CHF", Fraction(3, 4)), ("CHF", "SGD", Fraction(8, 5))]
queries = [
    ("CAD", "SGD", 50),
    ("SGD", "CAD", 60),
    ("JPY", "JPY", 25),
    ("CAD", "AUD", 50),
]
convert(quotes, queries, reciprocal=True)

Output:

[Fraction(60, 1), Fraction(50, 1), 25, -1]

Explanation: 50 CAD converts via CHF into 50 * (3/4) * (8/5) = 60 SGD. Using reciprocal edges (5/8 and 4/3), 60 SGD converts back into 50 CAD. "JPY" -> "JPY" takes the 0-hop empty route (25), and "AUD" is disconnected (-1).

Example 2

Input:

from fractions import Fraction

quotes = [
    ("CAD", "CHF", Fraction(3, 4)),
    ("CHF", "SGD", Fraction(8, 5)),
    ("CAD", "SGD", Fraction(5, 4)),
]
best_forward = max_amount(quotes, "CAD", "SGD", 80, reciprocal=True)
best_reverse = max_amount(quotes, "SGD", "CAD", 90, reciprocal=True)

Output:

best_forward == Fraction(100, 1)
best_reverse == Fraction(75, 1)

Explanation: Going CAD -> SGD, the direct quote gives 80 * (5/4) = 100, beating the two-hop route through CHF (80 * (3/4) * (8/5) = 96). Going in reverse (SGD -> CAD), routing via CHF yields 90 * (5/8) * (4/3) = 75, beating the direct reciprocal 90 * (4/5) = 72. Neither route is allowed to loop around the triangle twice.

Example 3

Input:

quotes = [
    ("CAD", "CHF", 2.0),
    ("CAD", "AUD", 1.0),
    ("CHF", "AUD", 0.5),
    ("CHF", "SGD", 1.0),
    ("AUD", "CHF", 4.0),
    ("AUD", "SGD", 1.0),
]
max_amount(quotes, "CAD", "SGD", 10.0, reciprocal=False)

Output:

40.0

Explanation: With one-way quotes (reciprocal=False), four simple paths connect CAD to SGD: CAD -> CHF -> SGD (20.0), CAD -> CHF -> AUD -> SGD (10.0), CAD -> AUD -> SGD (10.0), and CAD -> AUD -> CHF -> SGD (10.0 * 1.0 * 4.0 * 1.0 = 40.0). Path-local backtracking explores all four and selects 40.0.

Constraints

  • Build the graph once per call so convert runs in O(E + Q * (V + E)) time across Q queries on V currencies and E quotes.
  • In max_amount, keep visitation path-local (backtracking) rather than global, and never recurse past target since simple paths cannot visit target twice.
  • Preserve all parallel quotes when constructing the graph: even when one quote has a lower forward rate r, its reciprocal 1 / r is higher in the reverse direction.

Step-by-step walkthrough

  1. Ask the clarifying questions that decide the algorithm

    In interviews, currency-conversion prompts purposefully leave several rules unstated because those rules decide which graph algorithm is valid and whether a finite answer even exists. Before writing code, align on six questions:

    Clarifying question Contract in this solution Why it changes the design
    Does a -> b at rate also allow b -> a at 1 / rate? Configurable via reciprocal=True (default) Decides whether quotes form one-way or two-way edges.
    Are rates always positive? Can parallel quotes exist? Rates must be > 0 (else ValueError); parallel quotes kept 1 / 0 crashes; negative rates flip min/max; parallel quotes compete in Part 2.
    What if source == target? Return amount unchanged (the 0-hop empty route) Avoids needing a separate "unknown currency" rule on self-queries.
    Are rates path-consistent? Part 1 assumes yes; Part 2 assumes no If two routes disagree, Part 1 has no single answer unless a tie-breaker is defined.
    May a route revisit a currency in Part 2? No — Part 2 searches simple paths (no repeated currencies) Allowing repeats makes the maximum infinite whenever a profitable loop exists!
    Exact numbers or binary floats? Code uses only *, /, and >, so Fraction is exact and float rounds Binary float rounding can create fake profit out of exact ties.

    To see why path consistency matters, look at three quotes: CAD -> CHF = 0.75, CHF -> SGD = 1.6, and CAD -> SGD = 1.25:

    Direct route:   80 CAD ----------------(x 1.25)----------------> 100 SGD
    Two-hop route:  80 CAD ---(x 0.75)---> 60 CHF ---(x 1.6)---> 96 SGD
    

    In Part 1, rates are consistent (for instance, CAD -> SGD would be 1.20), so any route gives the exact same answer. In Part 2, routes disagree and we must compare all valid simple routes to pick 100 SGD.

  2. Model currencies and quotes as a weighted directed graph

    We model currencies as nodes in a directed weighted graph — a network of nodes connected by one-way arrows where each arrow carries a multiplication factor (rate). Converting along a multi-step route multiplies the rates along its arrows.

    We store the graph as an adjacency list — a dictionary mapping each currency string to a list of (neighbor_currency, rate) tuples:

    Quotes: [("CAD", "CHF", 0.75), ("CHF", "SGD", 1.6)]
    
    reciprocal=False:                        reciprocal=True:
      "CAD": [("CHF", 0.75)]                   "CAD": [("CHF", 0.75)]
      "CHF": [("SGD", 1.6)]                    "CHF": [("CAD", 1.333...), ("SGD", 1.6)]
                                               "SGD": [("CHF", 0.625)]
    

    Two details inside build_graph prevent subtle bugs:

    • Reject non-positive and NaN rates with not rate > 0: In IEEE-754 floating point, NaN <= 0 is False AND NaN > 0 is False! Writing if not rate > 0: catches 0, negatives, and NaN in one test.
    • Keep parallel quotes instead of overwriting: If two liquidity providers quote CAD -> CHF at 0.75 and 0.80, 0.80 wins going CAD -> CHF, whereas 1 / 0.75 ≈ 1.333 beats 1 / 0.80 = 1.25 going CHF -> CAD!
    NO_ROUTE = -1
    
    # Quote shape: ("CAD", "CHF", 0.75) means 1 unit of "CAD" buys 0.75 units of "CHF".
    # Because the code only uses *, /, and >, fractions.Fraction rates give exact answers.
    Quote = Tuple[str, str, float]
    # Graph shape: {"CAD": [("CHF", 0.75), ("SGD", 1.25)], ...} mapping currency -> outgoing (neighbor, rate) edges.
    Graph = Dict[str, List[Tuple[str, float]]]
    
    
    def add_edge(graph: Graph, source: str, target: str, rate: float) -> None:
        """Append one directed conversion edge source -> target with multiplier rate."""
        if source not in graph:
            graph[source] = []
        graph[source].append((target, rate))
    
    
    def build_graph(quotes: List[Quote], reciprocal: bool = True) -> Graph:
        """graph[a] lists (b, rate) for every usable conversion a -> b.
    
        With reciprocal=True a quote a -> b at rate r also allows b -> a at rate 1 / r.
        Parallel quotes are all kept. Raises ValueError for a rate that is not positive.
        """
        graph: Graph = {}
        for source, target, rate in quotes:
            # Write `not rate > 0` instead of `rate <= 0` so NaN rates are rejected too (NaN > 0 is False).
            if not rate > 0:
                raise ValueError(f"rate must be positive: {source} -> {target} at {rate!r}")
            # Keep parallel quotes as separate edges: Part 2 compares them, and worse forward = better 1/rate!
            add_edge(graph, source, target, rate)
            if reciprocal:
                add_edge(graph, target, source, 1 / rate)
        return graph
    
  3. Part 1: Find any valid route with iterative DFS

    When rates are path-consistent, every route from source to target produces the same final amount. We only need to find one route, or confirm none exists.

    We run an iterative depth-first search (DFS) — a graph traversal that keeps a stack of (currency, accumulated_amount) states, popping the most recently discovered currency and multiplying by outgoing edge rates:

    • If source == target, return amount immediately (0 conversions).
    • Maintain a seen set of currencies already pushed onto the stack so we never walk around a cycle. Because all routes agree, visiting each currency once is 100% sufficient.
    • Using an explicit Python list as our stack avoids hitting Python's 1,000-frame recursion limit on deep chains of currencies.
    • Return NO_ROUTE (-1) only after stack becomes completely empty, proving target is unreachable.
    def convert_one(graph: Graph, source: str, target: str, amount: float) -> float:
        """Amount in target along the first route a depth-first search finds, or NO_ROUTE."""
        # Empty 0-hop route: converting a currency to itself leaves the starting amount unchanged.
        if source == target:
            return amount
        # seen: currencies already reached in this query (safe in Part 1 because rates are path-consistent).
        seen: Set[str] = {source}
        # stack: DFS frontier of (current_currency, accumulated_amount) pairs.
        stack: List[Tuple[str, float]] = [(source, amount)]
        while stack:
            currency, value = stack.pop()
            for neighbor, rate in graph.get(currency, []):
                if neighbor in seen:
                    continue
                next_value = value * rate
                if neighbor == target:
                    return next_value
                seen.add(neighbor)
                stack.append((neighbor, next_value))
        return NO_ROUTE
    
    
    def convert(quotes: List[Quote], queries: List[Tuple[str, str, float]],
                reciprocal: bool = True) -> List[float]:
        """Part 1: answer each (source, target, amount) query, assuming path-consistent rates."""
        # Build the adjacency list once and reuse it across all queries in the batch.
        graph = build_graph(quotes, reciprocal)
        results: List[float] = []
        for source, target, amount in queries:
            results.append(convert_one(graph, source, target, amount))
        return results
    
  4. Choose number types and rounding rules carefully

    Binary floating-point numbers (float) cannot represent most base-10 decimals (0.9, 0.51, 0.89) exactly, rounding slightly at every multiplication or division. Even when quotes are mathematically consistent, binary floats can invent tiny phantom differences:

    Quotes: CAD -> CHF = 0.51,  CHF -> SGD = 0.89,  CAD -> SGD = 0.4539
    True math:   0.51 * 0.89 = 0.4539  -->  round-trip multiplier is EXACTLY 1
    Binary float: 0.4539 * (1 / 0.89) * (1 / 0.51) == 1.0000000000000002  (phantom gain!)
    Exact Fraction: Fraction("0.4539") / Fraction("0.89") / Fraction("0.51") == Fraction(1, 1)
    

    How to choose the numeric representation in practice:

    • fractions.Fraction (exact rationals): Stores exact integer numerator / denominator pairs, so even reciprocals like 1 / Fraction(3, 4) == Fraction(4, 3) lose zero precision. Because our functions only use *, /, and >, passing Fraction rates works out of the box!
    • decimal.Decimal (fixed-precision base 10): Exact for multiplying short decimals within its configured precision (default 28 digits), though reciprocals like 1 / Decimal("0.75") or 1 / Decimal("0.9") can still require an agreed precision and rounding mode when non-terminating.
    • 64-bit float: Fast and standard when approximate answers are fine; never round intermediate hops — round once at the very end to the target currency's minor unit (e.g., 2 decimal places for CAD, 0 for JPY).
  5. Part 2: Why Part 1's global visited set fails

    In Part 2, different paths can yield different amounts, and we want the maximum over all simple paths — routes that visit each currency at most once.

    Reusing Part 1's query-wide seen set gives wrong answers in Part 2! Trace converting 10.0 units from CAD to SGD on these six one-way quotes (reciprocal=False):

    Quotes:  CAD -> CHF (x2),  CAD -> AUD (x1),  CHF -> AUD (x0.5),
             CHF -> SGD (x1),  AUD -> CHF (x4),  AUD -> SGD (x1)
    
    All 4 simple routes from CAD to SGD:
      1. CAD -> CHF -> SGD         : 10 * 2 * 1       = 20
      2. CAD -> CHF -> AUD -> SGD  : 10 * 2 * 0.5 * 1 = 10
      3. CAD -> AUD -> SGD         : 10 * 1 * 1       = 10
      4. CAD -> AUD -> CHF -> SGD  : 10 * 1 * 4 * 1   = 40   <-- TRUE MAXIMUM!
    
    What happens with a GLOBAL seen set if CAD explores CHF before AUD:
      - Visits CAD -> CHF -> AUD -> SGD, leaving seen = {CAD, CHF, AUD}.
      - Back at CAD, looks at CAD -> AUD: AUD is ALREADY in seen, so CAD -> AUD -> CHF -> SGD (40) is skipped!
    

    Caching "best multiplier from CHF to SGD" keyed only on CHF fails for the exact same reason: when reached via CAD -> AUD -> CHF, AUD is already used so CHF goes straight to SGD (x1), whereas when reached via CAD -> CHF, AUD is still available as a candidate branch!

    Instead, we need backtracking: keep a path-local set on_path containing only the currencies on the currently active chain from source. Add neighbor to on_path before exploring out of it, and remove neighbor from on_path as soon as that recursive call returns.

  6. Part 2: Backtracking over all simple routes

    Our recursive helper best_from(graph, currency, target, value, on_path) explores every valid continuation of the current simple route:

    1. Start best = None (using None rather than -1 keeps "no route found" cleanly separated from a valid 0.0 starting amount).
    2. Loop over every (neighbor, rate) edge from currency, skipping any neighbor already in on_path.
    3. If neighbor == target, record candidate = value * rate without recursing further — because a simple route cannot pass through target and later arrive at target a second time!
    4. Otherwise add neighbor to on_path, recurse to find the best completion, and remove neighbor on return.
    def best_from(graph: Graph, currency: str, target: str, value: float,
                  on_path: Set[str]) -> Optional[float]:
        """Largest amount of target reachable from currency, never entering a currency in on_path."""
        # Use None for "no route found yet" so a valid 0.0 amount is never confused with NO_ROUTE (-1).
        best: Optional[float] = None
        for neighbor, rate in graph.get(currency, []):
            # Skip currencies already on the active route so simple paths never loop.
            if neighbor in on_path:
                continue
            next_value = value * rate
            if neighbor == target:
                # Stop this branch at target: continuing past target and returning would repeat target.
                candidate: Optional[float] = next_value
            else:
                # Backtrack: mark neighbor on entry and unmark on exit so other routes can still use it.
                on_path.add(neighbor)
                candidate = best_from(graph, neighbor, target, next_value, on_path)
                on_path.remove(neighbor)
            if candidate is not None and (best is None or candidate > best):
                best = candidate
        return best
    
    
    def max_amount(quotes: List[Quote], source: str, target: str, amount: float,
                   reciprocal: bool = True) -> float:
        """Part 2: the largest target amount over routes that never repeat a currency, or NO_ROUTE."""
        graph = build_graph(quotes, reciprocal)
        # Only simple route from source to itself is the 0-hop empty route.
        if source == target:
            return amount
        best = best_from(graph, source, target, amount, {source})
        if best is None:
            return NO_ROUTE
        return best
    

    How many routes does backtracking explore? In a complete graph of V currencies (after keeping the best parallel quote per directed pair), choosing k intermediate currencies (0 <= k <= V - 2) in order gives sum over k = 0..V-2 of (V - 2)! / (V - 2 - k)! simple routes: just 5 routes for V = 4, 1,957 for V = 8, and 9,864,101 for V = 12. If memoization is ever wanted for moderate V, the cache key must include the full subset (currency, frozenset(on_path)), bounding work by O(2^V × V^2) (~590,000 operations at V = 12).

  7. What if repeated currencies are allowed? Profitable cycles and walkthrough

    If an interviewer changes the rule so routes may repeat currencies, check for arbitrage (profitable) cycles — closed loops of conversions whose edge rates multiply to strictly greater than 1:

    • If a cycle with product > 1 is reachable from source AND can reach target, walking around that loop k times multiplies your money by product^k, growing without bound! The API must report an unbounded result explicitly (for example, returning math.inf or raising UnboundedConversionError — never -1, which means unreachable).
    • If every reachable cycle has product <= 1, repeating currencies never helps, so the best simple path is still optimal.

    Notice that with reciprocal=True, any inconsistent triangle creates a profitable cycle in one of the two directions! Let's trace our triangle quotes (CAD -> CHF = 3/4, CHF -> SGD = 8/5, CAD -> SGD = 5/4) with reciprocal=True:

    Cycle clockwise:        CAD -> CHF -> SGD -> CAD = (3/4) * (8/5) * (4/5) = 24/25 = 0.96
    Cycle counter-clockwise: CAD -> SGD -> CHF -> CAD = (5/4) * (5/8) * (4/3) = 25/24 ≈ 1.0417 (> 1!)
    
    Simple-route trace for max_amount(quotes, source="SGD", target="CAD", amount=90):
      Start at SGD (value = 90, on_path = {"SGD"})
        |-- Edge SGD -> CHF (rate 5/8): value = 225/4, on_path = {"SGD", "CHF"}
        |     |-- Edge CHF -> CAD (rate 4/3): hits target CAD! candidate = 75
        |     |-- Edge CHF -> SGD (rate 8/5): skipped ("SGD" is in on_path)
        |   Backtrack: remove "CHF" -> on_path = {"SGD"}, best = 75
        |-- Edge SGD -> CAD (rate 4/5): hits target CAD! candidate = 72
      Winner: Fraction(75, 1) CAD
    
  8. Complete solution

    from typing import Dict, List, Optional, Set, Tuple
    
    NO_ROUTE = -1
    
    # Quote shape: ("CAD", "CHF", 0.75) means 1 unit of "CAD" buys 0.75 units of "CHF".
    # Because the code only uses *, /, and >, fractions.Fraction rates give exact answers.
    Quote = Tuple[str, str, float]
    # Graph shape: {"CAD": [("CHF", 0.75), ("SGD", 1.25)], ...} mapping currency -> outgoing (neighbor, rate) edges.
    Graph = Dict[str, List[Tuple[str, float]]]
    
    
    def add_edge(graph: Graph, source: str, target: str, rate: float) -> None:
        """Append one directed conversion edge source -> target with multiplier rate."""
        if source not in graph:
            graph[source] = []
        graph[source].append((target, rate))
    
    
    def build_graph(quotes: List[Quote], reciprocal: bool = True) -> Graph:
        """graph[a] lists (b, rate) for every usable conversion a -> b.
    
        With reciprocal=True a quote a -> b at rate r also allows b -> a at rate 1 / r.
        Parallel quotes are all kept. Raises ValueError for a rate that is not positive.
        """
        graph: Graph = {}
        for source, target, rate in quotes:
            # Write `not rate > 0` instead of `rate <= 0` so NaN rates are rejected too (NaN > 0 is False).
            if not rate > 0:
                raise ValueError(f"rate must be positive: {source} -> {target} at {rate!r}")
            # Keep parallel quotes as separate edges: Part 2 compares them, and worse forward = better 1/rate!
            add_edge(graph, source, target, rate)
            if reciprocal:
                add_edge(graph, target, source, 1 / rate)
        return graph
    
    
    def convert_one(graph: Graph, source: str, target: str, amount: float) -> float:
        """Amount in target along the first route a depth-first search finds, or NO_ROUTE."""
        # Empty 0-hop route: converting a currency to itself leaves the starting amount unchanged.
        if source == target:
            return amount
        # seen: currencies already reached in this query (safe in Part 1 because rates are path-consistent).
        seen: Set[str] = {source}
        # stack: DFS frontier of (current_currency, accumulated_amount) pairs.
        stack: List[Tuple[str, float]] = [(source, amount)]
        while stack:
            currency, value = stack.pop()
            for neighbor, rate in graph.get(currency, []):
                if neighbor in seen:
                    continue
                next_value = value * rate
                if neighbor == target:
                    return next_value
                seen.add(neighbor)
                stack.append((neighbor, next_value))
        return NO_ROUTE
    
    
    def convert(quotes: List[Quote], queries: List[Tuple[str, str, float]],
                reciprocal: bool = True) -> List[float]:
        """Part 1: answer each (source, target, amount) query, assuming path-consistent rates."""
        # Build the adjacency list once and reuse it across all queries in the batch.
        graph = build_graph(quotes, reciprocal)
        results: List[float] = []
        for source, target, amount in queries:
            results.append(convert_one(graph, source, target, amount))
        return results
    
    
    def best_from(graph: Graph, currency: str, target: str, value: float,
                  on_path: Set[str]) -> Optional[float]:
        """Largest amount of target reachable from currency, never entering a currency in on_path."""
        # Use None for "no route found yet" so a valid 0.0 amount is never confused with NO_ROUTE (-1).
        best: Optional[float] = None
        for neighbor, rate in graph.get(currency, []):
            # Skip currencies already on the active route so simple paths never loop.
            if neighbor in on_path:
                continue
            next_value = value * rate
            if neighbor == target:
                # Stop this branch at target: continuing past target and returning would repeat target.
                candidate: Optional[float] = next_value
            else:
                # Backtrack: mark neighbor on entry and unmark on exit so other routes can still use it.
                on_path.add(neighbor)
                candidate = best_from(graph, neighbor, target, next_value, on_path)
                on_path.remove(neighbor)
            if candidate is not None and (best is None or candidate > best):
                best = candidate
        return best
    
    
    def max_amount(quotes: List[Quote], source: str, target: str, amount: float,
                   reciprocal: bool = True) -> float:
        """Part 2: the largest target amount over routes that never repeat a currency, or NO_ROUTE."""
        graph = build_graph(quotes, reciprocal)
        # Only simple route from source to itself is the 0-hop empty route.
        if source == target:
            return amount
        best = best_from(graph, source, target, amount, {source})
        if best is None:
            return NO_ROUTE
        return best
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of currencies as airports and exchange quotes as flight legs where each flight multiplies your money by that leg's rate. In Part 1, the market is consistent — every itinerary from CAD to SGD lands with the exact same multiplier — so finding any connected sequence of flights with a standard depth-first search (DFS) (exploring along one chain of connections with a stack while marking visited airports) answers the query immediately. In Part 2, rates can disagree across routes, so finding the highest-paying simple path (a route that visits each currency at most once) requires backtracking: writing each currency onto your active itinerary when you enter it so you never fly in circles, then crossing it off when you step back so other candidate itineraries can still pass through it.

Both common shortcuts fail in Part 2. If you keep Part 1's single global seen set across the whole search, the first mediocre route that touches CHF permanently locks CHF, blocking a higher-paying route that arrives at CHF from another direction later. Conversely, if you drop the visited set altogether, the search loops forever between any two convertible currencies — and if a loop multiplies money by more than 1.0 (an arbitrage or profitable cycle), repeating the loop pushes the target amount to infinity!

Let's trace 90 SGD to CAD on three reciprocal quotes: CAD -> CHF = 3/4, CHF -> SGD = 8/5, and CAD -> SGD = 5/4:

  1. Build the graph: Adding reverse edges (1 / rate) gives SGD -> CHF = 5/8, CHF -> CAD = 4/3, and SGD -> CAD = 4/5.
  2. Route 1 (SGD -> CHF -> CAD): Start at SGD (on_path = {"SGD"}), step to CHF with 90 × 5/8 = 225/4 (on_path = {"SGD", "CHF"}), then hit CAD with (225/4) × 4/3 = 75. Backtrack by removing "CHF" from on_path.
  3. Route 2 (SGD -> CAD): Step directly from SGD to CAD with 90 × 4/5 = 72.
  4. Pick the winner: 75 beats 72, so max_amount returns 75.

Complexity

  • Time:
    • Graph construction (build_graph): O(E), where E is the number of quotes, because we scan the quote list once and append one (or two, when reciprocal=True) tuple to a dictionary list per quote.
    • Part 1 (convert): O(E + Q × (V + E)) across Q queries on V currencies and E edges. We build the graph once in O(E), and for each query seen lets every currency enter the DFS stack at most once, scanning each currency's outgoing edges at most once.
    • Part 2 (max_amount): O(E + P × D) in general, where P is the number of simple paths starting at source (without passing through target) and D is the maximum outgoing degree of a currency. In the worst case (a complete graph on V currencies), P grows factorially up to O((V - 2)!) (for example, 5 routes at V = 4, 1,957 at V = 8, and 9,864,101 at V = 12).
  • Space: O(V + E) to store the adjacency list, plus O(V) auxiliary memory per search for the iterative DFS stack and seen set in Part 1, or the recursion call stack and on_path set of depth at most V in Part 2.

Edge cases

  • Same source and target (source == target): Returns amount unchanged via the 0-hop empty route, even if that currency code never appeared in quotes (confirm this convention with the interviewer, since returning -1 for unlisted currencies is an equally reasonable alternative).
  • Disconnected components or unknown currencies: Returns -1 (NO_ROUTE) only after exhausting every reachable currency from source.
  • Starting amount of 0: best_from tracks Optional[float] (None for unreachable) rather than -1, so a reachable route with amount = 0 properly returns 0 while an unreachable route returns -1.
  • Directed vs reciprocal quotes (reciprocal=False): CAD -> CHF allows converting CAD into CHF, while CHF -> CAD returns -1 unless explicitly quoted.
  • Parallel quotes for the same pair: Keeping all edges ensures Part 2 picks the larger forward rate, and when reciprocal=True, the smaller forward quote r automatically supplies the larger reverse rate 1 / r!
  • Zero, negative, or NaN rates: Rejected immediately with ValueError during build_graph via if not rate > 0.

Common mistakes

  • Assuming quotes are two-way without asking: Real foreign-exchange desks quote separate bid and ask rates (a spread), so 1 / rate is only valid if the problem specifies mid-market reciprocal quotes.
  • Using a global visited set in Part 2: Permanently marking an intermediate currency after exploring a suboptimal route prevents later, higher-paying simple routes from passing through that currency.
  • Memoizing Part 2 by currency alone: The best remaining multiplier from currency to target depends on which currencies are already forbidden in on_path; memoization is only valid if keyed on (currency, frozenset(on_path)).
  • Continuing recursion past target in Part 2: A simple path cannot leave target and return to target later without visiting target twice, so neighbor == target must terminate that branch.
  • Returning -1 when a profitable cycle makes the answer infinite: -1 already means "no route exists"; overloading it for "unbounded profit" makes the two opposite extremes indistinguishable.
  • Testing float products with exact > 1.0 for arbitrage: Binary float rounding on consistent decimal quotes (0.51 × 0.89 == 0.4539) can produce 1.0000000000000002; use Fraction or a small epsilon tolerance.

Alternative approaches

  • Breadth-first search (BFS) for Part 1: Replacing the LIFO stack with collections.deque visits routes in order of hop count (1 conversion, then 2, then 3) in the same O(V + E) time — giving a clean "fewest intermediate conversions" tie-breaker if real-world quotes have small spreads or per-hop fees.
  • Subset dynamic programming (Held-Karp style) for Part 2: Deduplicating parallel edges to keep only the maximum rate per (u, v) pair and memoizing (currency, bitmask_of_visited_currencies) caps time at O(2^V × V^2), which beats raw O(V!) backtracking on dense graphs around V = 10..18.
  • Bellman-Ford in log space when repeated currencies ARE allowed: Because log(a × b) = log(a) + log(b) and log is strictly increasing, maximizing a product of rates equals maximizing a sum of log(rate) (or minimizing -log(rate)), turning the problem into standard shortest/longest paths in O(V × E) time whenever no reachable profitable cycle can reach target.

Follow-up questions

  • If repeated currencies were allowed, how would you check whether an arbitrage loop lies along some valid walk from source to target? Convert each edge multiplier rate into additive weight math.log(rate) (so multiplying rates becomes summing logs without overflowing huge products to inf or underflowing tiny ones to 0.0), then run the Bellman-Ford algorithm — a dynamic-programming path algorithm that relaxes all edges V - 1 times so every simple path settles to its best value. On one extra V-th pass, any edge (u -> v) reachable from source whose log-sum still improves (best_log[u] + log(rate) > best_log[v] + eps) must sit on or downstream of a reachable profitable cycle; running a quick DFS/BFS from all such v checks in O(V × E) total time whether target can be reached afterward.

```python import math

def reachable_from(graph, starts): seen = set(starts) stack = list(starts) while stack: currency = stack.pop() for neighbor, _ in graph.get(currency, []): if neighbor not in seen: seen.add(neighbor) stack.append(neighbor) return seen

def is_unbounded(quotes, source, target, reciprocal=True, eps=1e-12): """True if a walk source -> target can loop a cycle whose rate product exceeds 1.""" graph = build_graph(quotes, reciprocal) currencies = {source, target} for a, b, _ in quotes: currencies.add(a) currencies.add(b) # Sum log(rate) instead of multiplying rates so 100^200 never overflows float64 to inf. best_log = {source: 0.0} for _ in range(len(currencies) - 1): for currency, cur_log in list(best_log.items()): for neighbor, rate in graph.get(currency, []): cand_log = cur_log + math.log(rate) if neighbor not in best_log or cand_log > best_log[neighbor] + eps: best_log[neighbor] = cand_log cycling = [] for currency, cur_log in best_log.items()): for neighbor, rate in graph.get(currency, []): if cur_log + math.log(rate) > best_log[neighbor] + eps: cycling.append(neighbor) return target in reachable_from(graph, cycling) ```

  • How would you preprocess a static exchange-rate graph to answer tens of thousands of conversion lookups quickly? Stop running a fresh graph search per query and precompute per-component or per-source multipliers once. For Part 1 with reciprocal, consistent quotes, currencies partition into connected components (isolated islands of mutually convertible currencies): run a single O(V + E) pass assigning an arbitrary root currency in each island potential = 1 and setting potential[b] = potential[a] * rate along edges, so every query (source, target, amount) answers in O(1) time via amount * potential[target] / potential[source] if comp[source] == comp[target] (or via a weighted Union-Find if quotes stream in dynamically). With directed quotes (reciprocal=False), run one traversal from each of the V sources to build a V × V multiplier table in O(V × (V + E)) time for O(1) lookups; for Part 2, one full non-stopping backtracking run per source records the best simple-path multiplier to every target simultaneously and caches that row until quotes change.

  • How can you guarantee identical decimal conversion outputs across services written in different languages? Never parse exchange rates into binary IEEE-754 floats (float / double), because values like 2.675 actually store 2.67499999999999982... and round differently across round(), toFixed(), and Math.round(x * 100) / 100. Instead, transmit rates over JSON/RPC as decimal strings ("0.7525"), compute inside exact rational types (Fraction / BigInteger numerator-denominator pairs) or fixed-scale base-10 decimals (Python Decimal, Java BigDecimal, scaled BigInt in JavaScript), and write down a strict cross-language specification fixing: (1) exact intermediate division precision for reciprocals (1 / 0.75), (2) order of operations, (3) rounding only once at the final step to the ISO-4217 minor unit of the target currency (2 decimals for CAD, 0 for JPY, 3 for KWD), and (4) the exact tie-breaking mode (such as ROUND_HALF_EVEN vs ROUND_HALF_UP), verified by a shared golden test suite.

Follow-up questions

Similar questions

More Rippling interview questions

All 106 Rippling questions →