Rising Temperature - Problem

You're given a Weather table that tracks daily temperature readings. Your task is to identify all days where the temperature was higher than the previous day.

Column NameType
idint
recordDatedate
temperatureint

Key Points:

  • Each row has a unique id
  • No duplicate dates exist in the table
  • Return the id values for days with rising temperatures
  • Results can be returned in any order

Think of this as finding "warming trends" - days that got warmer compared to the day before!

Input & Output

example_1.sql — Basic Rising Temperature
$ Input: Weather table: | id | recordDate | temperature | |----|------------|-------------| | 1 | 2015-01-01 | 10 | | 2 | 2015-01-02 | 25 | | 3 | 2015-01-03 | 20 | | 4 | 2015-01-04 | 30 |
Output: | id | |----| | 2 | | 4 |
💡 Note: On 2015-01-02, temperature was 25°C which is higher than previous day's 10°C. On 2015-01-04, temperature was 30°C which is higher than previous day's 20°C.
example_2.sql — No Rising Temperature
$ Input: Weather table: | id | recordDate | temperature | |----|------------|-------------| | 1 | 2015-01-01 | 30 | | 2 | 2015-01-02 | 25 | | 3 | 2015-01-03 | 20 |
Output: Empty result set | id | |----|
💡 Note: No day had a higher temperature than the previous day - temperatures consistently decreased.
example_3.sql — Single Day Edge Case
$ Input: Weather table: | id | recordDate | temperature | |----|------------|-------------| | 1 | 2015-01-01 | 15 |
Output: Empty result set | id | |----|
💡 Note: With only one day of data, there's no previous day to compare against, so no rising temperature can be detected.

Visualization

Tap to expand
Rising Temperature Detection ProcessDay 120°CNo PreviousDay 225°C✓ Rising!Day 322°C✗ FallingDay 430°C✓ Rising!25 > 2022 < 2530 > 22ResultRising Temperature IDs: 2, 4
Understanding the Visualization
1
Sort by Date
Arrange weather records in chronological order
2
Look Back
For each day, check the previous day's temperature using LAG function
3
Compare
Identify days where temperature increased from the previous day
4
Report
Return the IDs of all days with rising temperatures
Key Takeaway
🎯 Key Insight: Use LAG window function to efficiently compare each day's temperature with the previous day in a single pass, avoiding the need for complex self-joins.

Time & Space Complexity

Time Complexity
⏱️
O(n)

Single pass through the sorted data using window function

n
2n
Linear Growth
Space Complexity
O(1)

Window function uses constant additional space

n
2n
Linear Space

Constraints

  • 1 ≤ Weather table rows ≤ 100
  • 1980-01-01 ≤ recordDate ≤ 2000-12-31
  • -100 ≤ temperature ≤ 100
  • All recordDate values are unique
Asked in
Amazon 15 Google 12 Microsoft 8 Meta 6
28.4K Views
Medium Frequency
~15 min Avg. Time
875 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