LeetCode 2534, Hard. Topics: Queue, Array, Simulation. View on LeetCode.
Generate this problem as a practice environment: tested reference solution, 24 parametrized pytest cases, and a playground notebook:
Problem
There are <code>n</code> persons numbered from <code>0</code> to <code>n - 1</code> and a door. Each person can enter or exit through the door once, taking one second.</p>
<p>You are given a <strong>non-decreasing</strong> integer array <code>arrival</code> of size <code>n</code>, where <code>arrival[i]</code> is the arrival time of the <code>i<sup>th</sup></code> person at the door. You are also given an array <code>state</code> of size <code>n</code>, where <code>state[i]</code> is <code>0</code> if person <code>i</code> wants to enter through the door or <code>1</code> if they want to exit through the door.</p>
<p>If two or more persons want to use the door at the <strong>same</strong> time, they follow the following rules:</p>
<ul>
<li>If the door was <strong>not</strong> used in the previous second, then the person who wants to <strong>exit</strong> goes first.</li>
<li>If the door was used in the previous second for <strong>entering</strong>, the person who wants to enter goes first.</li>
<li>If the door was used in the previous second for <strong>exiting</strong>, the person who wants to <strong>exit</strong> goes first.</li>
<li>If multiple persons want to go in the same direction, the person with the <strong>smallest</strong> index goes first.</li>
</ul>
<p>Return <em>an array </em><code>answer</code><em> of size </em><code>n</code><em> where </em><code>answer[i]</code><em> is the second at which the <code>i<sup>th</sup></code> person crosses the door</em>.</p>
<p><strong>Note</strong> that:</p>
<ul>
<li>Only one person can cross the door at each second.</li>
<li>A person may arrive at the door and wait without entering or exiting to follow the mentioned rules.</li>
</ul>
Examples
Constraints
- n == arrival.length == state.length
- 1 <= n <= 10^5
- 0 <= arrival[i] <= n
- arrival is sorted in non-decreasing order.
- state[i] is either 0 or 1.
Solution
Reference implementation from solution.py on GitHub, full suite in test_solution.py:
Complexity
NeetCode All. Last modified on September 7, 2026