algoadvance

Leetcode 2469. Convert the Temperature

Problem Statement

You are given a temperature in Celsius. You need to convert this temperature to Kelvin and Fahrenheit using the following formulas:

Implement a function that takes a temperature in Celsius and returns an array containing the temperature in Kelvin and the temperature in Fahrenheit.

Clarifying Questions

  1. Input Type:
    • Is the temperature input always a floating-point number?
    • Will the input always be valid (i.e., no null or invalid inputs)?
  2. Output Format:
    • Should the output be in a specific order, i.e., Kelvin first, then Fahrenheit?
    • Should the output be formatted to any specific number of decimal places?

Code

public class Solution {
    public double[] convertTemperature(double celsius) {
        // Convert Celsius to Kelvin
        double kelvin = celsius + 273.15;
        
        // Convert Celsius to Fahrenheit
        double fahrenheit = celsius * 1.80 + 32.00;
        
        // Return the resultant temperatures in an array
        return new double[] {kelvin, fahrenheit};
    }

    public static void main(String[] args) {
        Solution sol = new Solution();

        // Test cases
        double[] result1 = sol.convertTemperature(25.0);
        System.out.println("Kelvin: " + result1[0] + ", Fahrenheit: " + result1[1]);  // Expected: Kelvin: 298.15, Fahrenheit: 77.00

        double[] result2 = sol.convertTemperature(-273.15);
        System.out.println("Kelvin: " + result2[0] + ", Fahrenheit: " + result2[1]);  // Expected: Kelvin: 0.00, Fahrenheit: -459.67
    }
}

Strategy

  1. Definition and Assignment:
    • Define the function convertTemperature which takes a double representing the temperature in Celsius.
    • Use the given formulas to compute the temperature in Kelvin and Fahrenheit.
  2. Conversion:
    • Convert Celsius to Kelvin by adding 273.15 to the Celsius temperature.
    • Convert Celsius to Fahrenheit using the formula ( C \times 1.80 + 32.00 ).
  3. Returning the Result:
    • Return the converted temperatures as an array of doubles where the first element is the Kelvin temperature and the second is the Fahrenheit temperature.
  4. Testing:
    • Test the function with a few sample values to ensure its correctness.

Time Complexity

The time complexity for this problem is O(1) (constant time) since the computations involved (addition and multiplication) take a consistent amount of time regardless of the input size. The space complexity is also O(1) since we are using a fixed amount of additional space to store the results.

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