Users With a Qualifying Login Session in an Unordered Event Log
Arrays & HashingAuto-graded · 16 test casesLast updated
Pair sign-in and sign-out events per user from an unsorted log using chronological order and FIFO matching, and report users with a session within a time limit.
Quick Sessions in an Activity Log
A service records user activity as text lines. Each line has the form:
"<user> <action> <time>"
<user>is a non-empty identifier with no spaces.<action>is eithersigninorsignout.<time>is an integer number of seconds.
The lines are not guaranteed to be in chronological order.
You are also given an integer max_time.
Building sessions
Handle each user independently. Process that user's events in chronological order (ascending time). If two events have the same time, the one that appears earlier in the input list is processed first.
- A
signinevent becomes open and waits for a matching signout. - A
signoutevent is matched with the oldest still-opensigninof the same user. The two together form one session, and that signin is no longer open. - If a
signoutarrives when the user has no open signin, the signout is ignored. - Any
signinthat is still open after all events are processed forms no session.
A session that starts at t_in and ends at t_out is quick if t_out - t_in <= max_time.
Task
Return every user who has at least one quick session. The result must be a list of distinct user IDs sorted in ascending (lexicographic) order. If no user qualifies, return an empty list.
Constraints
0 <= len(logs) <= 10^5- Every entry in
logsis well formed: exactly three space-separated fields, withactionequal tosigninorsignoutandtimea valid integer. max_timeis an integer (it may be zero or negative).- Different users never influence each other's sessions.
Examples
Example 1
Input: users_with_quick_session(['u1 signin 1', 'u2 signin 2', 'u1 signout 5', 'u2 signout 20', 'u1 signin 30', 'u1 signout 35'], 10)
Output: ['u1']
Hints
Hint 1
Parse each line into (time, original position, user, action) and sort so events are in chronological order, using the original position to break ties.
Hint 2
Keep a separate queue of open signin times for each user, for example a dictionary that maps each user to a deque.
Hint 3
When a signout arrives, take the oldest open signin from the front of that user's queue, if there is one, and compare the difference to max_time. Add the user to a set when a session is quick, then return the sorted set.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is an event-matching problem, and each user can be handled on their own once the events are in chronological order.
- Parse and sort. Split each line into user, action and time. Sort all events by
(time, original index). The original index makes ties deterministic: among events with equal times, the one listed earlier is processed first. - Keep a queue per user. Each user has a FIFO queue of open signin times.
- Sweep through the sorted events.
- On
signin, append the time to that user's queue. - On
signout, if the user's queue is empty, ignore the event. Otherwise pop the oldest open signin. The pair is a session. Iftime - signin_time <= max_time, add the user to the result set.
- On
- Signins left in queues at the end form no session and are ignored.
- Return the result set as a sorted list.
Why it is correct
- Each signin claims the first signout after it that no earlier signin has claimed. In a chronological sweep, when a signout arrives, every open signin for that user is older than it and unclaimed. The oldest of them would find this signout first, so the signout belongs to the front of the queue. That is exactly FIFO matching.
- An orphan signout finds an empty queue and is skipped, so it never consumes a later signin.
- Users are stored separately, so one user's events never affect another's.
- Using a set means a user is reported once, however many quick sessions they have. Sorting the set gives a deterministic output.
- The tie-break by original index fixes the processing order of equal-time events, so the result is fully determined by the input.
Complexity
- Time: O(n log n) for the sort. The sweep is O(n), since each signin is pushed once and popped at most once.
- Space: O(n) for the parsed events, the queues and the result set.
Reference solution
from collections import defaultdict, deque
from typing import List
def users_with_quick_session(logs: List[str], max_time: int) -> List[str]:
events = []
for index, entry in enumerate(logs):
user, action, timestamp = entry.split()
events.append((int(timestamp), index, user, action))
events.sort(key=lambda event: (event[0], event[1]))
pending = defaultdict(deque)
quick_users = set()
for timestamp, _, user, action in events:
if action == "signin":
pending[user].append(timestamp)
elif pending[user]:
signin_time = pending[user].popleft()
if timestamp - signin_time <= max_time:
quick_users.add(user)
return sorted(quick_users)