#3421

Find Students Who Improved

Medium
DatabaseHash MapAggregation Functions
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution leverages aggregation functions to efficiently compute the first and latest scores for each student and subject combination in a single pass, reducing unnecessary comparisons.

⚙️

Algorithm

3 steps
  1. 1Step 1: Use a GROUP BY clause to group scores by student_id and subject.
  2. 2Step 2: Use aggregation functions to find the minimum (first score) and maximum (latest score) for each group.
  3. 3Step 3: Filter results using HAVING to ensure at least two distinct exam dates and that the latest score is greater than the first score.
solution.py5 lines
1SELECT student_id, subject, MIN(score) AS first_score, MAX(score) AS latest_score
2FROM Scores
3GROUP BY student_id, subject
4HAVING COUNT(DISTINCT exam_date) >= 2 AND MAX(score) > MIN(score)
5ORDER BY student_id, subject;

Complexity note: This complexity is linear because we are processing each score once and aggregating results efficiently.

  • 1Using aggregation functions can significantly reduce the complexity of the solution.
  • 2Filtering results after aggregation helps to ensure we only return relevant data.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.