FastPrepShortest Currency Conversion with Three-Decimal Rate

Shortest Currency Conversion with Three-Decimal Rate

Maven Clinic logoMaven Clinic● MediumFULLTIMEPHONE SCREEN
Learn

Problem statement

Each string in rates has the form from,to,rate and represents one directed conversion edge. Find a path from source to target that uses the fewest edges.

When several shortest paths exist, choose the lexicographically smallest complete currency sequence. Return the currencies on that path followed by the cumulative conversion factor formatted with exactly three digits after the decimal point. Return an empty array when the target is unreachable.

Function

shortestConversion(rates: String[], source: String, target: String) → String[]

Examples

Example 1

rates = ["CAD,USD,0.88","USD,JPY,2000"]source = "CAD"target = "JPY"return = ["CAD","USD","JPY","1760.000"]

The unique two-edge path multiplies 0.88 by 2000.

Example 2

rates = ["USD,JPY,2000","USD,EUR,0.90","EUR,JPY,1600"]source = "USD"target = "JPY"return = ["USD","JPY","2000.000"]

The direct conversion uses fewer edges than the route through EUR.

Example 3

rates = ["USD,CAD,1.25"]source = "USD"target = "USD"return = ["USD","1.000"]

A currency converts to itself without traversing an edge.

Constraints

  • 0 <= rates.length <= 100000.
  • Currency names are nonempty ASCII strings without commas.
  • Each rate is finite and strictly positive.
  • The same ordered currency pair appears at most once.

More Maven Clinic problems

See Maven Clinic hiring insights
public String[] shortestConversion(String[] rates, String source, String target) {
    // Write your code here.
}
rates["CAD,USD,0.88","USD,JPY,2000"]
source"CAD"
target"JPY"
expected["CAD", "USD", "JPY", "1760.000"]
Checking account…