Currency Exchange Rate (graph traversal with best rate calculation)

Difficulty: MEDIUMCategory: LLDFrequency: 1Asked On 2022-06-13

Problem Statement

Design a system that maintains currency exchange rates between multiple currencies and allows users to query the best possible exchange rate between two given currencies.


The system should treat exchange rates as a graph problem:


•Each currency is a node.
•Each exchange rate (e.g., USD → EUR = 0.9) is a directed weighted edge.
•Finding the best exchange rate path between two currencies may involve traversing multiple intermediate currencies (e.g., USD → GBP → EUR if that gives a better effective rate).


Functional Requirements


1.Data Model
•Store currencies as graph nodes.
•Store exchange rates as directed weighted edges.
•Rates can change dynamically (updates should be supported).
2.Queries
•getBestRate(fromCurrency, toCurrency) → return the maximum possible rate achievable using available paths.
•Handle direct and indirect conversions.
•If no path exists, return an error/-1.
3.Updates
•updateRate(from, to, rate) → updates or inserts a conversion edge.
•Ensure consistency in graph after updates.


Non-Functional Requirements


•Performance: Querying best rates should be efficient even with thousands of currencies and edges.
•Correctness: Handle cycles (e.g., arbitrage opportunities like USD → EUR → GBP → USD).
•Scalability: Support both frequent updates and frequent queries.
•Extensibility: Allow plugging in APIs that provide live forex data.


Algorithmic Considerations


•Represent graph as Map<String, Map<String, Double>>.
•Use graph traversal (DFS/BFS with multiplication of weights) to find the best rate.
•Since we need the maximum product path, transform the problem:
•Use -log(rate) as edge weights.
•Apply Dijkstra’s Algorithm or Bellman-Ford (to detect arbitrage cycles).


Example


Input Rates:

1 2USD → EUR = 0.9 3EUR → GBP = 0.8 4USD → GBP = 0.7


Query: getBestRate(USD, GBP)


•Path 1: Direct → 0.7
•Path 2: USD → EUR → GBP → 0.9 * 0.8 = 0.72 (better)


Output: 0.72


Class Design (Sketch in Java-like Pseudocode)

1 2class CurrencyExchange { 3 Map<String, Map<String, Double>> graph; 4 5 CurrencyExchange() { 6 graph = new HashMap<>(); 7 } 8 9 void updateRate(String from, String to, double rate) { 10 graph.putIfAbsent(from, new HashMap<>()); 11 graph.get(from).put(to, rate); 12 } 13 14 double getBestRate(String from, String to) { 15 if (!graph.containsKey(from) || !graph.containsKey(to)) return -1; 16 return bfsBestRate(from, to); // or Dijkstra with log transform 17 } 18 19 private double bfsBestRate(String from, String to) { 20 Queue<Pair<String, Double>> q = new LinkedList<>(); 21 q.add(new Pair<>(from, 1.0)); 22 double bestRate = -1.0; 23 Set<String> visited = new HashSet<>(); 24 25 while (!q.isEmpty()) { 26 Pair<String, Double> curr = q.poll(); 27 String currCurrency = curr.getKey(); 28 double rateSoFar = curr.getValue(); 29 30 if (currCurrency.equals(to)) { 31 bestRate = Math.max(bestRate, rateSoFar); 32 } 33 34 if (visited.contains(currCurrency)) continue; 35 visited.add(currCurrency); 36 37 for (Map.Entry<String, Double> entry : graph.getOrDefault(currCurrency, new HashMap<>()).entrySet()) { 38 q.add(new Pair<>(entry.getKey(), rateSoFar * entry.getValue())); 39 } 40 } 41 return bestRate; 42 } 43}


Key Discussion Points in LLD Round


•Graph modeling choice (Adjacency List vs Adjacency Matrix).
•Trade-offs between precision vs performance (floating-point errors in multiplications).
•Handling updates efficiently (batch updates vs streaming updates).
•Detecting and preventing arbitrage loops (negative cycles).
•Extensibility to real-world forex APIs (latency, consistency trade-offs).


Solution

Comments