#1633

Percentage of Users Attended a Contest

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

In the optimal approach, we will use a single pass to gather the necessary counts, which allows us to efficiently compute the required percentages without redundant calculations.

⚙️

Algorithm

5 steps
  1. 1Step 1: Count the total number of unique users from the Users table.
  2. 2Step 2: Use a GROUP BY query on the Register table to count the number of unique users for each contest.
  3. 3Step 3: Calculate the percentage for each contest using the total user count.
  4. 4Step 4: Round the percentage to two decimal places.
  5. 5Step 5: Order the results by percentage in descending order and contest_id in ascending order.
solution.py7 lines
1# Full working Python code
2SELECT r.contest_id,
3       ROUND(COUNT(DISTINCT r.user_id) * 100.0 / total_users.total, 2) AS percentage
4FROM Register r
5JOIN (SELECT COUNT(DISTINCT user_id) AS total FROM Users) AS total_users ON 1=1
6GROUP BY r.contest_id
7ORDER BY percentage DESC, r.contest_id ASC;

Complexity note: This complexity is due to the need to count unique users in both tables, but it is done in a single pass for the Register table and a single pass for the Users table.

  • 1Using JOINs can significantly reduce the number of queries and improve performance.
  • 2Understanding how to use GROUP BY effectively is crucial for aggregating data.

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