Ctrl K

Turnstile Queue

Hard
An office entrance has a single turnstile. n people numbered 0 to n − 1 come to it; person i arrives at second arrival[i] (the array is non-decreasing) and wants to pass once: to go in if direction[i] = 0, or to go out if direction[i] = 1. Passing takes exactly one second, and at most one person passes per second. Anyone who has arrived may wait as long as needed. When several people want to pass at the same second, the order is decided like this: - if nobody used the turnstile in the previous second, someone going out passes first; - if someone went in during the previous second, someone going in passes first; - if someone went out during the previous second, someone going out passes first; - among people heading the same way, the one with the smaller number goes first. Before second 0 the turnstile counts as idle. Return an array whose i-th element is the second at which person i passes.
Example 1
arrival=[0, 0, 1, 3], direction=[0, 1, 0, 0] → [1, 0, 2, 3]

At second 0 the turnstile was idle before, so person 1 goes out first. At second 1 nobody is leaving and person 0 goes in, person 2 follows at second 2 and person 3 at second 3.

Example 2
arrival=[0, 1, 1], direction=[0, 1, 0] → [0, 2, 1]

Person 0 goes in at second 0. At second 1 person 1 wants out and person 2 wants in; the previous second was an entry, so person 2 goes. Person 1 leaves at second 2.

Example 3
arrival=[0, 2, 2], direction=[0, 0, 1] → [0, 3, 2]

The turnstile is idle at second 1, so at second 2 exits have priority: person 2 leaves first and person 1 enters at second 3.

Constraints
  • 1 ≤ n ≤ 10⁵
  • len(arrival) = len(direction) = n
  • 0 ≤ arrival[i] ≤ n, and arrival is non-decreasing
  • direction[i] is 0 or 1
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsA Deck That Reveals in Order MediumA Picky Line at the Counter EasyLast One in the Circle MediumWaiting in the Ticket Line EasyJustify the Lines Hard
loading Python…
Input
arrival=[0, 0, 1, 3], direction=[0, 1, 0, 0]
Expected
[1, 0, 2, 3]

Run checks the first 3 tests in your browser. Submit checks all 89 tests on the server, hidden ones included.