#1729

Find Followers Count

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)

The optimal approach leverages SQL's GROUP BY and COUNT functions to efficiently aggregate the follower counts in a single query, which is much faster than the brute force method.

⚙️

Algorithm

4 steps
  1. 1Step 1: Use the SQL SELECT statement to choose user_id and count the number of follower_id for each user.
  2. 2Step 2: Use GROUP BY to group results by user_id to aggregate follower counts.
  3. 3Step 3: Order the results by user_id in ascending order.
  4. 4Step 4: Return the aggregated results.
solution.py5 lines
1# Full working Python code
2SELECT user_id, COUNT(follower_id) AS followers_count
3FROM Followers
4GROUP BY user_id
5ORDER BY user_id;

Complexity note: The time complexity is O(n) because we are scanning through the table once to count followers. Space complexity is O(n) due to the storage of results.

  • 1Using GROUP BY and COUNT is much more efficient than manual counting.
  • 2Understanding how to leverage SQL functions can significantly reduce complexity.

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