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): Whenreciprocal=True(the default), a quote(a, b, r)can be traversed forward asa -> bwith multiplierrand in reverse asb -> awith multiplier1 / r. Whenreciprocal=False, only the forward edgea -> bexists. - Rate validation: Every quote rate must be strictly positive (
rate > 0, rejecting0, negatives, andNaNwithValueErroreven ifqueriesis empty). - Zero-hop identity: Whenever
source == target, returnamountunchanged, even if that currency code does not appear inquotes. - Unreachable destinations: Return
NO_ROUTE(-1) when no valid path connectssourcetotarget. - Numeric generality: Rates and amounts may be passed as
floator exactfractions.Fractionobjects, so stick to standard arithmetic (*,/,>) without forcing conversions tofloat.
The two parts differ in their path assumptions:
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 inqueries, return the converted amount intarget(or-1if unreachable).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 fromsourcetotarget—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
convertruns inO(E + Q * (V + E))time acrossQqueries onVcurrencies andEquotes. - In
max_amount, keep visitation path-local (backtracking) rather than global, and never recurse pasttargetsince simple paths cannot visittargettwice. - Preserve all parallel quotes when constructing the graph: even when one quote has a lower forward rate
r, its reciprocal1 / ris higher in the reverse direction.
Step-by-step walkthrough
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 -> batratealso allowb -> aat1 / 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(elseValueError); parallel quotes kept1 / 0crashes; negative rates flip min/max; parallel quotes compete in Part 2.What if source == target?Return amountunchanged (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>, soFractionis exact andfloatroundsBinary 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, andCAD -> 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 SGDIn Part 1, rates are consistent (for instance,
CAD -> SGDwould be1.20), so any route gives the exact same answer. In Part 2, routes disagree and we must compare all valid simple routes to pick100 SGD.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_graphprevent subtle bugs:- Reject non-positive and
NaNrates withnot rate > 0: In IEEE-754 floating point,NaN <= 0isFalseANDNaN > 0isFalse! Writingif not rate > 0:catches0, negatives, andNaNin one test. - Keep parallel quotes instead of overwriting: If two liquidity providers quote
CAD -> CHFat0.75and0.80,0.80wins goingCAD -> CHF, whereas1 / 0.75 ≈ 1.333beats1 / 0.80 = 1.25goingCHF -> 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- Reject non-positive and
Part 1: Find any valid route with iterative DFS
When rates are path-consistent, every route from
sourcetotargetproduces 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, returnamountimmediately (0 conversions). - Maintain a
seenset 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
listas our stack avoids hitting Python's1,000-frame recursion limit on deep chains of currencies. - Return
NO_ROUTE(-1) only afterstackbecomes completely empty, provingtargetis 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- If
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 integernumerator / denominatorpairs, so even reciprocals like1 / Fraction(3, 4) == Fraction(4, 3)lose zero precision. Because our functions only use*,/, and>, passingFractionrates 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 like1 / Decimal("0.75")or1 / 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 forCAD, 0 forJPY).
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
seenset gives wrong answers in Part 2! Trace converting10.0units fromCADtoSGDon 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
CHFtoSGD" keyed only onCHFfails for the exact same reason: when reached viaCAD -> AUD -> CHF,AUDis already used soCHFgoes straight toSGD(x1), whereas when reached viaCAD -> CHF,AUDis still available as a candidate branch!Instead, we need backtracking: keep a path-local set
on_pathcontaining only the currencies on the currently active chain fromsource. Addneighbortoon_pathbefore exploring out of it, and removeneighborfromon_pathas soon as that recursive call returns.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:- Start
best = None(usingNonerather than-1keeps "no route found" cleanly separated from a valid0.0starting amount). - Loop over every
(neighbor, rate)edge fromcurrency, skipping anyneighboralready inon_path. - If
neighbor == target, recordcandidate = value * ratewithout recursing further — because a simple route cannot pass throughtargetand later arrive attargeta second time! - Otherwise add
neighbortoon_path, recurse to find the best completion, and removeneighboron 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 bestHow many routes does backtracking explore? In a complete graph of
Vcurrencies (after keeping the best parallel quote per directed pair), choosingkintermediate currencies (0 <= k <= V - 2) in order givessum over k = 0..V-2 of (V - 2)! / (V - 2 - k)!simple routes: just5routes forV = 4,1,957forV = 8, and9,864,101forV = 12. If memoization is ever wanted for moderateV, the cache key must include the full subset(currency, frozenset(on_path)), bounding work byO(2^V × V^2)(~590,000operations atV = 12).- Start
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
> 1is reachable fromsourceAND can reachtarget, walking around that loopktimes multiplies your money byproduct^k, growing without bound! The API must report an unbounded result explicitly (for example, returningmath.infor raisingUnboundedConversionError— 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) withreciprocal=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- If a cycle with product
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:
- Build the graph: Adding reverse edges (
1 / rate) givesSGD -> CHF = 5/8,CHF -> CAD = 4/3, andSGD -> CAD = 4/5. - Route 1 (
SGD -> CHF -> CAD): Start atSGD(on_path = {"SGD"}), step toCHFwith90 × 5/8 = 225/4(on_path = {"SGD", "CHF"}), then hitCADwith(225/4) × 4/3 = 75. Backtrack by removing"CHF"fromon_path. - Route 2 (
SGD -> CAD): Step directly fromSGDtoCADwith90 × 4/5 = 72. - Pick the winner:
75beats72, somax_amountreturns75.
Complexity
- Time:
- Graph construction (
build_graph):O(E), whereEis the number of quotes, because we scan the quote list once and append one (or two, whenreciprocal=True) tuple to a dictionary list per quote. - Part 1 (
convert):O(E + Q × (V + E))acrossQqueries onVcurrencies andEedges. We build the graph once inO(E), and for each queryseenlets 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, wherePis the number of simple paths starting atsource(without passing throughtarget) andDis the maximum outgoing degree of a currency. In the worst case (a complete graph onVcurrencies),Pgrows factorially up toO((V - 2)!)(for example,5routes atV = 4,1,957atV = 8, and9,864,101atV = 12).
- Graph construction (
- Space:
O(V + E)to store the adjacency list, plusO(V)auxiliary memory per search for the iterative DFSstackandseenset in Part 1, or the recursion call stack andon_pathset of depth at mostVin Part 2.
Edge cases
- Same source and target (
source == target): Returnsamountunchanged via the 0-hop empty route, even if that currency code never appeared inquotes(confirm this convention with the interviewer, since returning-1for unlisted currencies is an equally reasonable alternative). - Disconnected components or unknown currencies: Returns
-1(NO_ROUTE) only after exhausting every reachable currency fromsource. - Starting amount of
0:best_fromtracksOptional[float](Nonefor unreachable) rather than-1, so a reachable route withamount = 0properly returns0while an unreachable route returns-1. - Directed vs reciprocal quotes (
reciprocal=False):CAD -> CHFallows convertingCADintoCHF, whileCHF -> CADreturns-1unless 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 quoterautomatically supplies the larger reverse rate1 / r! - Zero, negative, or
NaNrates: Rejected immediately withValueErrorduringbuild_graphviaif 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 / rateis only valid if the problem specifies mid-market reciprocal quotes. - Using a global
visitedset 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
currencyalone: The best remaining multiplier fromcurrencytotargetdepends on which currencies are already forbidden inon_path; memoization is only valid if keyed on(currency, frozenset(on_path)). - Continuing recursion past
targetin Part 2: A simple path cannot leavetargetand return totargetlater without visitingtargettwice, soneighbor == targetmust terminate that branch. - Returning
-1when a profitable cycle makes the answer infinite:-1already means "no route exists"; overloading it for "unbounded profit" makes the two opposite extremes indistinguishable. - Testing float products with exact
> 1.0for arbitrage: Binary float rounding on consistent decimal quotes (0.51 × 0.89 == 0.4539) can produce1.0000000000000002; useFractionor a small epsilon tolerance.
Alternative approaches
- Breadth-first search (BFS) for Part 1: Replacing the LIFO stack with
collections.dequevisits routes in order of hop count (1conversion, then2, then3) in the sameO(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 atO(2^V × V^2), which beats rawO(V!)backtracking on dense graphs aroundV = 10..18. - Bellman-Ford in log space when repeated currencies ARE allowed: Because
log(a × b) = log(a) + log(b)andlogis strictly increasing, maximizing a product of rates equals maximizing a sum oflog(rate)(or minimizing-log(rate)), turning the problem into standard shortest/longest paths inO(V × E)time whenever no reachable profitable cycle can reachtarget.
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
rateinto additive weightmath.log(rate)(so multiplying rates becomes summing logs without overflowing huge products toinfor underflowing tiny ones to0.0), then run the Bellman-Ford algorithm — a dynamic-programming path algorithm that relaxes all edgesV - 1times so every simple path settles to its best value. On one extraV-th pass, any edge(u -> v)reachable fromsourcewhose 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 suchvchecks inO(V × E)total time whethertargetcan 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 islandpotential = 1and settingpotential[b] = potential[a] * ratealong edges, so every query(source, target, amount)answers inO(1)time viaamount * potential[target] / potential[source]ifcomp[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 theVsources to build aV × Vmultiplier table inO(V × (V + E))time forO(1)lookups; for Part 2, one full non-stopping backtracking run persourcerecords 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 like2.675actually store2.67499999999999982...and round differently acrossround(),toFixed(), andMath.round(x * 100) / 100. Instead, transmit rates over JSON/RPC as decimal strings ("0.7525"), compute inside exact rational types (Fraction/BigIntegernumerator-denominator pairs) or fixed-scale base-10 decimals (Python Decimal,Java BigDecimal, scaledBigIntin 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 (2decimals forCAD,0forJPY,3forKWD), and (4) the exact tie-breaking mode (such asROUND_HALF_EVENvsROUND_HALF_UP), verified by a shared golden test suite.
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?
- How would you preprocess a static exchange-rate graph to answer tens of thousands of conversion lookups quickly?
- How can you guarantee identical decimal conversion outputs across services written in different languages?
Similar questions
- Historical Rate Ledger for E-Bike Rentals
- Shared Ancestors in a Directed Graph
- In-Memory Courier Wage Ledger with Cutoff Payouts
- Numeric Five-Card Hand Evaluator and Partial-Hand Completions
- JSON Policy Engine for Expense Claims
- Thread-Safe Logger with Isolated Handlers and Backpressure
More Rippling interview questions
- Logarithmic Median of Two Sorted Arrays Medium
- Ranking Five-Digit Card Hands with Pluggable Rules Medium
- User Article Vote History Tracker Easy Pro
- In-Memory Courier Wage Ledger with Cutoff Payouts Medium Pro
- Numeric Five-Card Hand Evaluator and Partial-Hand Completions Medium Pro
- Hourly Payroll Service for Delivery Couriers Medium Pro
- Pluggable Broadcast Logger and Inverted-Index Keyword Search Easy Pro
- Global News Aggregation Platform Medium Pro
- In-Memory Delivery Cost Tracker Medium Pro
- Explicit-Preference News Feed Aggregator Medium Pro