Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Currency Conversion from Logs

MediumPython00:00
Practice interviewer
In session
5 left
00:00

Your question is Currency Conversion from Logs. Start with the requirements on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

Amazon Pay receives currency conversion rates as directed exchange relationships. Given a log of known rates, implement a function that converts an amount from any source currency to a target currency, possibly through intermediate currencies.

Formal Specification

Implement convert_currency(rates, source, target, amount), where rates is a list of records [from_currency, to_currency, rate]. Each rate means one unit of from_currency equals rate units of to_currency. The function must return the converted amount as a floating-point number. Every rate is positive. You may use the reciprocal rate to convert in the opposite direction. Return -1.0 if no conversion path exists. Converting a currency to itself returns the original amount.

Use graph traversal to find a path and multiply the rates along that path. You may assume that a valid path, when one exists, does not require revisiting a currency.

Constraints

  • 1 <= len(rates) <= 10^4
  • Currency codes are non-empty uppercase strings of length at most 5
  • 0 < rate <= 10^6
  • 0 <= amount <= 10^12
  • The graph may contain disconnected components
  • A valid path does not require revisiting a currency

Function Signature

def convert_currency(rates, source, target, amount):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output