#602
Friend Requests II: Who Has the Most Friends
MediumDatabaseHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal 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 count friends for each user using a hash map. This is efficient as it allows us to process the data in linear time.
⚙️
Algorithm
5 steps- 1Step 1: Create a hash map to count friends for each user.
- 2Step 2: Iterate through each row in the RequestAccepted table.
- 3Step 3: For each requester_id and accepter_id, increment the friend count for both users in the hash map.
- 4Step 4: After processing all requests, find the user with the maximum friend count in a single pass.
- 5Step 5: Return the user ID and the maximum friend count.
solution.py18 lines
1# Full working Python code
2import sqlite3
3
4def most_friends():
5 conn = sqlite3.connect(':memory:')
6 cursor = conn.cursor()
7 cursor.execute('''CREATE TABLE RequestAccepted (requester_id INT, accepter_id INT, accept_date DATE)''')
8 cursor.executemany('INSERT INTO RequestAccepted VALUES (?, ?, ?)', [(1, 2, '2016-06-03'), (1, 3, '2016-06-08'), (2, 3, '2016-06-08'), (3, 4, '2016-06-09')])
9
10 friend_count = {}
11 for requester, accepter, _ in cursor.execute('SELECT requester_id, accepter_id FROM RequestAccepted'):
12 friend_count[requester] = friend_count.get(requester, 0) + 1
13 friend_count[accepter] = friend_count.get(accepter, 0) + 1
14
15 user_id, max_friends = max(friend_count.items(), key=lambda x: x[1])
16 return [(user_id, max_friends)]
17
18print(most_friends())ℹ
Complexity note: The time complexity is O(n) because we only pass through the data once to count friends. The space complexity is O(n) for storing the friend counts in a hash map.
- 1Friendship is bidirectional, meaning both users count each other as friends.
- 2Using a hash map allows for efficient counting and retrieval.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.