KatInterview

Currency Conversion Rates via Graph Traversal

Trees & GraphsModel answer
MediumModel answerTrees & Graphsgraph-traversalshortest-pathbellman-ford

Last updated

Build a weighted graph from currency pairs and answer conversion queries, then extend to directional rates and arbitrage detection.

You are given a list of currency pairs such as [('USD','CAD'), ('CAD','EUR'), ...] together with a parallel list of rates [1.1, 1.2, ...]. A rate r attached to a pair (A, B) means that 1 unit of A buys r units of B.

Part 1 (base). Assume the market is coherent: quotes are reciprocal (the rate for B → A is exactly 1/r) and consistent (every route between two currencies multiplies out to the same answer). Implement rate(src, dst) returning the conversion factor from src to dst, or -1 if no chain of exchanges connects them. State your data structures, the traversal you use, and the time/space cost of building the structure versus answering one query.

Part 2 (many queries). Queries arrive constantly and the pair list changes rarely. How does your design change?

Part 3 (follow-up). Now quotes are directional and not reciprocal: only A → B at rate r exists, and different routes give different answers. Compute the best rate from src to dst. Explain the graph model, which shortest-path algorithm is valid, how cycles correspond to arbitrage, and how floating-point error affects your comparisons.

Hints

Hint 1

Each currency is a node and each rate is the weight of a directed edge; the rate along a route is the product of its edge weights, not the sum.

Hint 2

In Part 1 every route is equally good, so any traversal that carries the running product works — but you still need a visited set, otherwise a cycle makes the search loop forever.

Hint 3

Maximizing a product is the same as minimizing a sum of negative logs; check whether those log weights are actually non-negative before you reach for Dijkstra.

Hint 4

A cycle whose product exceeds 1 is an arbitrage loop. In -log space it is a negative cycle, and it makes the answer unbounded rather than merely large.