Metric Converter Library - Problem

Create a comprehensive metric conversion library that provides functions to convert between commonly used units. Your library should handle conversions between the following unit pairs:

  • Distance: kilometers ↔ miles
  • Weight: kilograms ↔ pounds
  • Temperature: Celsius ↔ Fahrenheit
  • Volume: liters ↔ gallons (US)

Implement a function that takes a value, from_unit, and to_unit as parameters and returns the converted value. The function should handle all conversions accurately using the standard conversion formulas.

Conversion Formulas:

  • 1 kilometer = 0.621371 miles
  • 1 kilogram = 2.20462 pounds
  • °F = (°C × 9/5) + 32
  • 1 liter = 0.264172 gallons

Input & Output

Example 1 — Distance Conversion
$ Input: value = 100, from_unit = "km", to_unit = "miles"
Output: 62.1371
💡 Note: Converting 100 kilometers to miles: 100 × 0.621371 = 62.1371 miles
Example 2 — Temperature Conversion
$ Input: value = 0, from_unit = "celsius", to_unit = "fahrenheit"
Output: 32.0
💡 Note: Converting 0°C to Fahrenheit: (0 × 9/5) + 32 = 32°F (freezing point of water)
Example 3 — Weight Conversion
$ Input: value = 70, from_unit = "kg", to_unit = "lbs"
Output: 154.3234
💡 Note: Converting 70 kilograms to pounds: 70 × 2.20462 = 154.3234 lbs

Constraints

  • value is a positive number
  • from_unit and to_unit are valid unit strings
  • Supported units: km, miles, kg, lbs, celsius, fahrenheit, liters, gallons

Visualization

Tap to expand
INPUTALGORITHMRESULT100valuekmfrom_unitmilesto_unit1Identify conversion type2Look up conversion factor3Apply mathematical formulakm → milesfactor: 0.621371100 × 0.62137162.1371milesConverted resultKey Insight:Using conversion factor maps provides O(1) lookup time and makes addingnew unit types much easier than hardcoding every possible conversion pair.TutorialsPoint - Metric Converter Library | Map-Based Approach
Asked in
Google 15 Amazon 12 Microsoft 10
25.0K Views
Medium Frequency
~15 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen