↓Skip to main content
  1. LeetCode/

LeetCode 197: Rising Temperature

·1 min· ·
LeetCode Easy Database
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2021-10-10

  • Submissions: Runtime Error → Accepted

Approach
#

Join each day to the previous day (SQL Template 3) with DATEDIFF(w.recordDate, y.recordDate) = 1 and filter w.temperature > y.temperature. Adjacent ids do not mean adjacent dates: ids need not follow date order, and dates may be missing.

My Attempts
#

Attempt 1 mistyped the join as JOIN weather,w, with a stray comma (RE); removing it passed.

Solution
#

SELECT w.id
FROM Weather w
JOIN Weather y ON DATEDIFF(w.recordDate, y.recordDate) = 1
WHERE w.temperature > y.temperature;

Complexity
#

A self join, near O(n) with a date index.

Mistakes to Avoid
#

  • Determine the previous day by date, not by id.
  • DATEDIFF is MySQL-specific; other databases differ (for example date - interval).

Interview Explanation
#

I self-join Weather where the dates differ by exactly one day and keep ids warmer than the previous day; the previous day must be found by date, since id order need not follow dates.

Related

LeetCode 595: Big Countries
·1 min
LeetCode Easy Database
LeetCode 595 note: filter with WHERE and OR for an area of at least 3 million or a population of at least 25 million
LeetCode 596: Classes With at Least 5 Students
·1 min
LeetCode Easy Database
LeetCode 596 note: group by class with HAVING COUNT(DISTINCT student) >= 5; older test data had duplicate rows, so count distinct students
LeetCode 620: Not Boring Movies
·1 min
LeetCode Easy Database
LeetCode 620 note: odd id and description not ‘boring’, ordered by rating from high to low
LeetCode 175: Combine Two Tables
·1 min
LeetCode Easy Database
LeetCode 175 note: people without an address must still appear, so LEFT JOIN, leaving city and state NULL when unmatched
LeetCode 181: Employees Earning More Than Their Managers
·1 min
LeetCode Easy Database
LeetCode 181 note: self-join Employee on managerId = id to pair employees with managers, then compare salaries
LeetCode 182: Duplicate Emails
·1 min
LeetCode Easy Database
LeetCode 182 note: group by email and keep groups with HAVING COUNT(*) > 1