algoadvance

Leetcode 2469. Convert the Temperature

Problem Statement

You are given a temperature in Celsius. You need to convert it to both Kelvin and Fahrenheit and return it in an array where:

Given a floating-point number celsius representing the temperature in Celsius, you need to implement a function that returns the resulting temperatures in a list of two floating point numbers.

Conversion Formulas

Clarifying Questions

  1. Input Constraints:
    • Are there any specific bounds on the value of the temperature in Celsius?
      • The problem statement does not specify any bounds, but we will assume it is a valid floating-point number.
  2. Output Format:
    • Should the conversion retain a certain number of decimal places, or is any floating-point precision acceptable?
      • We will assume that any reasonable floating-point precision is acceptable unless otherwise specified.

Strategy

  1. Read the input temperature in Celsius.
  2. Convert the temperature to Kelvin using the formula ( K = C + 273.15 ).
  3. Convert the temperature to Fahrenheit using the formula ( F = C \times \frac{9}{5} + 32 ).
  4. Return the results in the specified array format [Kelvin, Fahrenheit].

Code

#include <vector>

class Solution {
public:
    std::vector<double> convertTemperature(double celsius) {
        double kelvin = celsius + 273.15;
        double fahrenheit = celsius * 9.0 / 5.0 + 32.0;
        return {kelvin, fahrenheit};
    }
};

Time Complexity

The time complexity for this solution is ( O(1) ), which is constant time. The reason is that only a fixed number of arithmetic operations are performed, irrespective of the input size.

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI