Convert amounts between multiple currencies
RipplingSoftware Engineer · Technical ScreenLast updated
This question evaluates understanding of graph modeling and path-optimization in directed weighted graphs, specifically reasoning about chained conversions and maximizing multiplicative path weights.
You are given a set of direct currency exchange rates and a list of queries. Each exchange rate gives you how to convert from one currency to another.
- You can assume there are up to (10^4) distinct currencies.
- You are given
ndirect exchange rates, each described as:from_currency,to_currency,rate, meaning: - 1 unit of
from_currencycan be exchanged forrateunits ofto_currency. - Exchange rates are directed: if you know
A -> Bat rater, you cannot assume you knowB -> Aunless an explicit rate is given. - You can chain exchanges: if you know
A -> BandB -> C, then you can exchange fromAtoCviaB. - You may assume that if a chain exists, the effective rate is the product of rates along the path.
You are also given q queries. Each query is of the form:
source_currency,target_currency,amount.
For each query, compute the maximum amount of target_currency you can obtain by converting the given amount units of source_currency, using zero or more intermediate currencies and the available direct exchange rates.
- If no conversion path exists from
source_currencytotarget_currency, return-1for that query. - You may assume there are no arbitrage cycles that increase money unboundedly (i.e., no cycles whose product of rates is greater than 1).
Input format (conceptual):
- Integer
n— number of direct exchange rates. - Next
nlines:from_currency to_currency rate(e.g.,USD EUR 0.9). - Integer
q— number of queries. - Next
qlines:source_currency target_currency amount.
Output:
- For each query, output a real number representing the maximum amount of
target_currencyyou can obtain, or-1if it is impossible.
Task: Describe an efficient algorithm to answer all queries.
- Clearly specify the data structures you will use.
- State the time and space complexity in terms of
nandq.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.