#1141

User Activity for the Past 30 Days I

Easy
DatabaseHash MapAggregation
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)

Instead of checking each day against all activities, we can use a single pass through the activity table to build a count of distinct users for each day. This reduces the number of operations significantly.

⚙️

Algorithm

3 steps
  1. 1Step 1: Use a HashMap to store the count of distinct users for each activity date.
  2. 2Step 2: Iterate through the activity table and for each activity, update the count in the HashMap.
  3. 3Step 3: Extract the results from the HashMap for the 30-day period.
solution.py4 lines
1SELECT activity_date, COUNT(DISTINCT user_id) AS active_users
2FROM Activity
3WHERE activity_date BETWEEN DATE('2019-06-28') AND DATE('2019-07-27')
4GROUP BY activity_date;

Complexity note: This complexity is due to a single pass through the activities (O(n)) and storing the results in a HashMap (O(n)) for distinct user counts.

  • 1Using a HashMap can significantly reduce the time complexity of counting distinct elements.
  • 2Understanding the problem requirements helps in choosing the right data structure.

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