#197
Rising Temperature
EasyDatabaseSelf-JoinDate Manipulation
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses a self-join to efficiently compare each day's temperature with the previous day's temperature, reducing the number of comparisons needed.
⚙️
Algorithm
3 steps- 1Step 1: Use a self-join on the Weather table to connect each record with its previous day's record.
- 2Step 2: Filter the results where the current day's temperature is greater than the previous day's temperature.
- 3Step 3: Select the id of the records that meet the criteria.
solution.py1 lines
1SELECT w1.id FROM Weather w1 JOIN Weather w2 ON DATE_ADD(w2.recordDate, INTERVAL 1 DAY) = w1.recordDate WHERE w1.temperature > w2.temperature;ℹ
Complexity note: This complexity is linear because each record is processed a constant number of times, and we only store results for qualifying records.
- 1Understanding how to use self-joins can significantly optimize queries involving comparisons.
- 2Recognizing patterns in data (like daily temperatures) can help in structuring queries effectively.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.