Problem

Table: Views

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| article_id    | int     |
| author_id     | int     |
| viewer_id     | int     |
| view_date     | date    |
+---------------+---------+
This table may have duplicate rows.
Each row of this table indicates that some viewer viewed an article (written by some author) on some date. 
Note that equal author_id and viewer_id indicate the same person.

Write a solution to find all the people who viewed more than one article on the same date.

Return the result table sorted by id in ascending order.

The result format is in the following example.

Examples

Example 1:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
Input: 
Views table:
+------------+-----------+-----------+------------+
| article_id | author_id | viewer_id | view_date  |
+------------+-----------+-----------+------------+
| 1          | 3         | 5         | 2019-08-01 |
| 3          | 4         | 5         | 2019-08-01 |
| 1          | 3         | 6         | 2019-08-02 |
| 2          | 7         | 7         | 2019-08-01 |
| 2          | 7         | 6         | 2019-08-02 |
| 4          | 7         | 1         | 2019-07-22 |
| 3          | 4         | 4         | 2019-07-21 |
| 3          | 4         | 4         | 2019-07-21 |
+------------+-----------+-----------+------------+
Output: 
+------+
| id   |
+------+
| 5    |
| 6    |
+------+

Solution

Method 1 – Group By and Having

Intuition

To find viewers who viewed more than one article on the same date, we group the data by viewer_id and view_date and count distinct article_id. If the count is greater than 1, that viewer saw multiple articles on that date.

Approach

  1. Group the Views table by viewer_id and view_date.
  2. Count the number of distinct article_id for each group.
  3. Select groups where the count is greater than 1.
  4. Return the unique viewer_id as id, sorted in ascending order.
MySQL
1
2
3
4
5
SELECT DISTINCT viewer_id AS id
FROM Views
GROUP BY viewer_id, view_date
HAVING COUNT(DISTINCT article_id) > 1
ORDER BY id ASC;

Complexity

  • ⏰ Time complexity: O(N), where N is the number of rows in the Views table (for grouping and counting).
  • 🧺 Space complexity: O(N) for storing intermediate groups.