#C258. Group Logs by User and Sort by Timestamp
Group Logs by User and Sort by Timestamp
Group Logs by User and Sort by Timestamp
You are given a list of log entries. Each log entry contains three fields: a positive integer user_id
, a non-negative integer timestamp
(representing the Unix timestamp), and a non-empty string action
describing the user action.
Your task is to group the logs by user_id
and, for each user, sort the corresponding actions in ascending order of their timestamp
. Then, print the results in ascending order of the user IDs. The output for each user must be on a separate line in the following format:
user_id: action1 action2 ... actionK
It is guaranteed that the input data follows the constraints.
Note: If there are no log entries, the program should produce no output.
Mathematical formulation:
Let \(L = [l_1, l_2, \ldots, l_n]\) be a list of logs where each log \(l_i\) is a tuple \((u_i, t_i, a_i)\). For each unique user id \(u\), output the sorted list of actions \(A(u) = [a_{i_1}, a_{i_2}, \ldots, a_{i_k}]\) such that \(t_{i_1} \le t_{i_2} \le \ldots \le t_{i_k}\).
inputFormat
The input is read from standard input (stdin
) and is formatted as follows:
- The first line contains a single integer
n
representing the number of log entries. - The next
n
lines each contain a log entry in the format:user_id timestamp action
Constraints:
user_id
is a positive integer.timestamp
is a non-negative integer.action
is a non-empty string (it will not contain whitespace).
outputFormat
For each distinct user_id, output a line containing the user_id followed by a colon and the list of actions (sorted in ascending order by timestamp) separated by a space. The users should be printed in ascending order of their user_id. If there are no logs, output nothing.
## sample5
1 1622476800 login
2 1622476860 view_page
1 1622476900 logout
1 1622476805 click_button
2 1622476890 logout
1: login click_button logout
2: view_page logout
</p>