Find users with at least one valid session
Company: Oracle
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
You are given:
- A list of log entries `logs`, where each entry is a string in the format:
```
"userId action timestamp"
```
- `userId` is a non-empty string without spaces (e.g., `"u1"`).
- `action` is either `"signin"` or `"signout"`.
- `timestamp` is an integer representing time in seconds.
- An integer `maxTime`.
A **session** for a user is defined as a pair of actions:
- A `"signin"` log for that user at time `t_in`, and
- The **next** `"signout"` log for the same user at time `t_out` such that `t_out > t_in`,
- And that `signout` has not already been paired with a previous `signin` for that user.
A session is **valid** if:
```text
(t_out - t_in) <= maxTime
```
Your task is to:
> Return the set (or list) of all `userId`s that have **at least one** valid session.
Additional details and assumptions:
- The `logs` list may **not** be sorted by time; you should handle that.
- Each log belongs to exactly one user, determined by `userId`.
- If there is a `signout` without any earlier unmatched `signin` for that user, ignore that `signout`.
- If there is a `signin` without any later `signout`, it does not form a session.
- A single user may have multiple sessions; if **any one** of them is valid, that user should be included in the output.
- The output can be in any order.
**Example**
```text
logs = [
"u1 signin 1",
"u2 signin 2",
"u1 signout 5",
"u2 signout 20",
"u1 signin 30",
"u1 signout 35"
]
maxTime = 10
```
- For `u1`:
- Session 1: signin at 1, signout at 5 → duration 4 (valid)
- Session 2: signin at 30, signout at 35 → duration 5 (valid)
- For `u2`:
- Session 1: signin at 2, signout at 20 → duration 18 (invalid if `maxTime = 10`)
So the output should include `"u1"` (has valid sessions) and exclude `"u2"`.
Implement a function that, given `logs` and `maxTime`, returns all such `userId`s.
Quick Answer: This question evaluates the ability to parse and process event logs, pair signin/signout events per user, and handle unordered timestamps and per-user state with time-window constraints.
Return sorted user IDs that have at least one signin/signout session whose duration is <= maxTime.
Examples
Input: (['u1 signin 1', 'u2 signin 2', 'u1 signout 5', 'u2 signout 20', 'u1 signin 30', 'u1 signout 35'], 10)
Expected Output: ['u1']
Explanation: Prompt example.
Input: (['u signout 1', 'u signin 2'], 5)
Expected Output: []
Explanation: Unmatched signout ignored.
Input: (['b signout 5', 'b signin 1', 'a signin 1', 'a signout 3'], 3)
Expected Output: ['a']
Explanation: Unsorted logs.
Hints
- Sort by timestamp and pair each signout with the earliest unmatched prior signin for that user.