Problem
Table: Calls
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| from_id | int |
| to_id | int |
| duration | int |
+-------------+---------+
This table does not have a primary key (column with unique values), it may contain duplicates.
This table contains the duration of a phone call between from_id and to_id.
from_id != to_id
Write a solution to report the number of calls and the total call duration between each pair of distinct persons (person1, person2)
where person1 < person2
.
Return the result table in any order.
The result format is in the following example.
Examples
Example 1:
|
|
Solution
Method 1 – SQL Group By Normalized Pair
Intuition
Normalize each call pair so that (person1, person2) is always (min(from_id, to_id), max(from_id, to_id)). Group by this pair and aggregate count and sum.
Approach
- For each row, set person1 = LEAST(from_id, to_id), person2 = GREATEST(from_id, to_id).
- Group by person1, person2 and count calls, sum durations.
Code
|
|
Complexity
- ⏰ Time complexity:
O(N)
- 🧺 Space complexity:
O(N)