KatInterview

Determine Pass Times for Single-Lane Security Gate

Stacks & QueuesAuto-graded · 22 test cases
HardAuto-gradedStacks & Queuesstacks-queuessimulationarrays

Last updated

Simulate the scheduling of access requests through a shared resource using state tracking and queues under conflict-resolution rules.

A single-lane security gate processes individuals moving in two possible directions: entering (0) or leaving (1). Exactly one person can traverse the gate per second.

The gate applies the following arbitration logic to resolve conflicts when multiple people are queued:

  1. If the gate was operated during the previous second (t - 1), it gives priority to people traveling in the same direction as that previous operation.
  2. If the gate was idle during the previous second (t - 1), or if people are waiting in only one direction, preference is given to the leaving direction (1).
  3. If multiple people waiting in the same direction arrived at different times, the person who arrived earlier goes first. If they arrived at the exact same time, the person with the smaller initial index goes first.

You are given two arrays of equal length, times and direction:

  • times[i] specifies the timestamp (in seconds) when person i reaches the gate area.
  • direction[i] indicates whether person i wants to enter (0) or leave (1).

Return an array results of length $N$, where results[i] is the timestamp at which person i completes their passage through the gate.

Constraints

  • $1 \le N \le 10^5$, where $N$ is the number of people.
  • times is sorted in non-decreasing order (times[i] <= times[i+1]).
  • $0 \le \text{times}[i] \le 10^9$.
  • direction[i] is either 0 or 1.
  • len(times) == len(direction).

Examples

Example 1

Input: get_turnstile_times([0, 0, 1, 5], [0, 1, 1, 0])

Output: [2, 0, 1, 5]

Example 2

Input: get_turnstile_times([0, 1, 1, 3, 3], [0, 1, 0, 0, 1])

Output: [0, 2, 1, 4, 3]

Hints

Hint 1

Use two separate double-ended queues (deques) to track waiting individuals for each direction (0 for entering, 1 for leaving).

Hint 2

Instead of incrementing time second-by-second up to 10^9, jump directly to the next person's arrival time whenever both waiting queues are empty.

Hint 3

Maintain two state variables: the direction used during the previous passage and a boolean flag indicating whether the gate was used in the immediately preceding second.