Rising Temperature LeetCode Solution

This Leetcode problem Rising Temperature LeetCode Solution is done in SQL.

List of all LeetCode Solution

Rising Temperature LeetCode Solution

Rising Temperature LeetCode Solution

Problem Statement

Column NameType
idint
recordDate date
temperature int
Table: Weather

id is the column with unique values for this table. There are no different rows with the same recordDate. This table contains information about the temperature on a certain day.

Write a solution to find all dates’ Id with higher temperatures compared to its previous dates (yesterday).

Return the result table in any order.

The result format is in the following example.

Example 1:
Input:

id recordDatetemperature
12015-01-0110
22015-01-0225
32015-01-0320
42015-01-0430
Weather table:

Output:

id
2
4

Explanation: In 2015-01-02, the temperature was higher than the previous day (10 -> 25). In 2015-01-04, the temperature was higher than the previous day (20 -> 30).

Rising Temperature LeetCode Solution MySQL

select 
  w1.Id 
from 
  Weather as w1, 
  Weather as w2 
where 
  datediff(w1.RecordDate, w2.RecordDate) = 1 
  and w1.Temperature > w2.Temperature;
Code language: SQL (Structured Query Language) (sql)

Rising Temperature LeetCode Solution Pandas

import pandas as pd

def rising_temperature(weather: pd.DataFrame) -> pd.DataFrame:
    # Ensure the 'recordDate' column is a datetime type
    weather['recordDate'] = pd.to_datetime(weather['recordDate'])
    
    # Create a copy of the weather DataFrame with a 1 day shift 
    weather_shifted = weather.copy()
    weather_shifted['recordDate'] = weather_shifted['recordDate'] + pd.to_timedelta(1, unit='D')
    
    # Merging the DataFrames on the 'recordDate' column to find consecutive dates
    merged_df = pd.merge(weather, weather_shifted, on='recordDate', suffixes=('_today', '_yesterday'))
    
    # Finding rows where the temperature is greater on the current day compared to the previous day
    result = merged_df[merged_df['temperature_today'] > merged_df['temperature_yesterday']][['id_today']].rename(columns={'id_today': 'Id'})
    
    return resultCode language: SQL (Structured Query Language) (sql)
Scroll to Top