Table: Followers
+-------------+------+ | Column Name | Type | +-------------+------+ | user_id | int | | follower_id | int | +-------------+------+ (user_id, follower_id) is the primary key (combination of columns with unique values) for this table. This table contains the IDs of a user and a follower in a social media app where the follower follows the user.
Write a solution that will, for each user, return the number of followers.
Return the result table ordered by user_id in ascending order.
The result format is in the following example.
Example 1:
Input:
Followers table:
+---------+-------------+
| user_id | follower_id |
+---------+-------------+
| 0 | 1 |
| 1 | 0 |
| 2 | 0 |
| 2 | 1 |
+---------+-------------+
Output:
+---------+----------------+
| user_id | followers_count|
+---------+----------------+
| 0 | 1 |
| 1 | 1 |
| 2 | 2 |
+---------+----------------+
Explanation:
The followers of 0 are {1}
The followers of 1 are {0}
The followers of 2 are {0,1}
This approach involves using an SQL-like query to count the number of followers for each user by grouping the records by user_id. This can be achieved using a GROUP BY clause and the COUNT function.
This Python solution uses a defaultdict to count the followers for each user. We iterate over the input list of tuples, updating the count of followers for each user_id. Finally, we return the result sorted by user_id.
JavaScript
Time Complexity: O(n), where n is the number of records in the table because each record is processed once.
Space Complexity: O(u), where u is the number of distinct user_ids because we're storing results for each user.
This approach relies on using hash maps or dictionaries to keep track of the follower counts for each user. It directly translates the SQL GROUP BY method into a coding solution using dictionary data structures available in multiple languages.
This C++ solution utilizes an unordered_map to count followers for each user_id. It iterates over the input vector, updating the map. Finally, it extracts the counts into a vector of pairs and sorts it, mimicking a GROUP BY query in SQL.
C#
Time Complexity: O(n log u), where n is the number of records and u is the number of unique user_ids, because of the sort operation.
Space Complexity: O(u) for storing follower counts.
| Approach | Complexity |
|---|---|
| Use SQL-like Aggregation | Time Complexity: O(n), where n is the number of records in the table because each record is processed once. |
| Use Hash Maps or Dictionaries | Time Complexity: O(n log u), where n is the number of records and u is the number of unique |
Find Followers Count | Leetcode 1729 | Crack SQL Interviews in 50 Qs #mysql #leetcode • Learn With Chirag • 2,247 views views
Watch 9 more video solutions →Practice Find Followers Count with our built-in code editor and test cases.
Practice on FleetCode