Currency Conversion Optimization (Graph traversal for best exchange rate)
Difficulty: MEDIUMCategory: LLDFrequency: 1Asked On 2020-11-04
Problem Statement
Designing a Currency Conversion Engine that determines the best possible exchange rate when converting from one currency to another. The system should support direct and indirect conversions using multiple available exchange rates, and optimize for the highest rate.
Functional Requirements
1.Exchange Rate Representation
•Maintain a set of currency pairs with conversion rates.
•Example: USD → EUR = 0.9, EUR → JPY = 140, etc.
2.Conversion Queries
•Given a sourceCurrency, targetCurrency, return the best conversion rate.
•If no valid path exists, return -1 or an error.
3.Optimization
•Handle multi-step conversions (e.g., USD → EUR → JPY).
•Always return the path with the maximum product of rates.
•Detect cycles and avoid infinite loops.
4.Updates
•Support updating exchange rates dynamically.
•Support adding/removing currencies.
Non-Functional Requirements
•Efficiency → Optimize queries since rates can be large in number.
•Extensibility → Should allow plugging in real-time rates from APIs.
•Correctness → Ensure floating-point precision is handled carefully.
•Thread Safety (optional) → Multiple queries/updates may come concurrently.
Design Hints for Interview
•Represent currencies as graph nodes; exchange rates as directed weighted edges.
•Conversion rate optimization = maximum product path problem (log transform → shortest path OR DFS/BFS with max heap).
•Core classes:
•CurrencyGraph → maintains adjacency list of rates.
•ExchangeRate → encapsulates rate between two currencies.
•ConversionEngine → handles queries and optimizations.
Example Scenario
•Input Rates:
•USD → EUR = 0.9
•EUR → JPY = 140
•USD → JPY = 120
•Query: USD → JPY
•Path1: Direct = 120
•Path2: Via EUR = 0.9 * 140 = 126
•Best = 126
✅ The challenge is both LLD (class design, clean API) and algorithmic (graph traversal, optimization, cycle handling, floating-point precision).