Fix getOrCreate in a session registry
Your task
Your Java service keeps one session per user in a ConcurrentHashMap. The first getOrCreate called get, then put when it found nothing, so two threads could each create a session for the same user. Session ids come from a counter, so they also show how many sessions were ever created.
An assistant wrote assign_session_ids(calls), which replays registry calls with each map operation done in one atomic step. It is in the editor. It has a bug. Find it and fix it.
Input and output:
calls: the calls in order.useris getOrCreate for that user.user|endcloses that user's session.- Return one number per call.
Rules the tests check:
- Split a call on
|. The user is the first part. Return 0 if the user is empty, there are more than 2 parts, or there are 2 parts and the second is notend. - getOrCreate for a user with a live session returns that session's id.
- getOrCreate for a user with no live session creates one and returns its id. Ids start at 1, and each new session gets the next one.
endfor a user with a live session returns its id and removes it. A later getOrCreate for that user creates a new session.endfor a user with no live session returns 0.
Examples
assign_session_ids(calls: list[str]) -> list[int]Example 1
Input
assign_session_ids(["u1", "u1", "u2"])Output
[1, 1, 2]Example 2
Input
assign_session_ids(["u1", "u1|end", "u1"])Output
[1, 1, 2]