KatInterview

Users With a Qualifying Login Session in an Unordered Event Log

Arrays & HashingAuto-graded · 16 test cases
MediumAuto-gradedArrays & Hashinghash-mapsortingqueue

Last 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 either signin or signout.
  • <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 signin event becomes open and waits for a matching signout.
  • A signout event is matched with the oldest still-open signin of the same user. The two together form one session, and that signin is no longer open.
  • If a signout arrives when the user has no open signin, the signout is ignored.
  • Any signin that 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 logs is well formed: exactly three space-separated fields, with action equal to signin or signout and time a valid integer.
  • max_time is 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.