
Sponsored
Sponsored
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.
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.
1function findFollowersCount(followers) {
2 const followersCount = {};
3
4 followers.forEach(([userId, followerId]) => {
5 if (!followersCount[userId]) {
6 followersCount[userId] = 0;
7 }
8 followersCount[userId]++;
9 });
10
11 return Object.entries(followersCount)
12 .map(([userId, count]) => ({ user_id: Number(userId), followers_count: count }))
13 .sort((a, b) => a.user_id - b.user_id);
14}
15
16// Example usage
17const followers = [ [0, 1], [1, 0], [2, 0], [2, 1] ];
18console.log(findFollowersCount(followers));In JavaScript, we use an object to keep track of follower counts by user_id. We iterate over the follower pairs, updating the counts. The result is then transformed into an array of objects and sorted by user_id.
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.
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.
1#include <iostream>
2#include <vector>
3#include <unordered_map>
4#include <algorithm>
5
using namespace std;
vector<pair<int, int>> findFollowersCount(vector<pair<int, int>>& followers) {
unordered_map<int, int> followersCount;
for (const auto& p : followers) {
followersCount[p.first]++;
}
vector<pair<int, int>> result;
for (const auto& entry : followersCount) {
result.push_back(entry);
}
sort(result.begin(), result.end());
return result;
}
// Example usage
int main() {
vector<pair<int, int>> followers = { {0, 1}, {1, 0}, {2, 0}, {2, 1} };
auto result = findFollowersCount(followers);
for (const auto& p : result) {
cout << "User ID: " << p.first << ", Followers Count: " << p.second << endl;
}
return 0;
}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.