⚡Flashcard Drill➔
NeetCode #174LC-2534HardArrays & Hashing
← Back to All Problems

#174 · #2534 · Time Taken to Cross the Door(通过门的时间)

📌 Problem Statement & Constraints

There are n people who want to cross a door. arrival[i] is the arrival time and state[i] is 0 for entering, 1 for exiting. Each person takes 1 second to cross, one at a time. Priority rule: if people are waiting on both sides, the side that used the door most recently goes next (exiting has priority if nobody has used the door yet). Return the time each person crosses. Constraints: 1 <= n <= 10^5; arrival is non-decreasing.

💡 Core Algorithmic Approaches

  1. Simulate second by second with two queues, one per direction.
  2. At each second, admit everyone whose arrival time is at most the current second into their respective queue.
  3. If both queues are non-empty, the last flag (1 for exit, 0 for enter, initialised to 1) decides who goes.
  4. If only one queue is non-empty, that side goes and the last flag is updated. If nobody is waiting, jump the clock to the next arrival -- this jump is essential for performance.

💻 Benchmark Python3 Implementation

class Solution:
    def timeTaken(self, arrival: List[int], state: List[int]) -> List[int]:
        from collections import deque
        n = len(arrival)
        enter, exit_ = deque(), deque()
        res = [0] * n
        i = 0
        t = 0
        last = 1                           # nobody used the door -> exit priority
        while i < n or enter or exit_:
            while i < n and arrival[i] <= t:
                (exit_ if state[i] == 1 else enter).append(i)
                i += 1
            if not enter and not exit_:
                t = arrival[i]             # jump to the next arrival
                continue
            if enter and exit_:
                if last == 1:
                    res[exit_.popleft()] = t
                else:
                    res[enter.popleft()] = t
                    last = 0
            elif exit_:
                res[exit_.popleft()] = t
                last = 1
            else:
                res[enter.popleft()] = t
                last = 0
            t += 1
        return res

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(n + max time): each person is enqueued and dequeued once, and the clock jump keeps the idle iterations to O(n).
💾 Space Complexity
O(n) for the two queues and the result.

⚠️ Interview Pitfalls & Follow-ups

  • Forgetting to update last in the both-queues case when the exit side goes: it stays 1, which is correct, but the enter branch must set it to 0.
  • Initialising last to 0: nobody has used the door yet, so the rule gives exit priority, i.e. last = 1.
  • Not jumping the clock: when nobody is waiting, incrementing t by one each iteration would be O(max arrival) which can be 10^9.
  • Admitting arrivals with arrival[i] < t instead of <= t: someone arriving exactly at the current second can still cross now.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related Arrays & Hashing Problems

中文速览与面试要点

通过门的时间

n 个人排成一队准备通过一扇门。给你两个下标从 0 开始的数组 arrival 和 state: arrival[i] 是第 i 个人到达门口的时间; state[i] 为 0 表示他想 出去 ,为 1 表示他想 进来 。规则:门每秒只能通过一个人;若门在上一秒被使用过,则优先让 与上一秒方向相同 的人通过;若门在上一秒 未被使用 ,则优先让想 出去 的人通过。返回每个人通过门的时刻数组。约束:n == arrival.length == state.length;1 ≤ n ≤ 10^5;0 ≤ arrival[i] ≤ 10^9;state[i] 为 0 或 1。

核心要点

  • 双队列模拟 + 方向状态机(标准解) :用两个队列分别保存等待「出」和「进」的人的下标。
  • 时间推进 :维护当前时刻 t。每秒先把所有 arrival[i] &lt;= t 的人加入对应队列。
  • 方向决策 :① 若两个队列都非空:若上一秒有使用方向且该方向队列非空,则沿用;否则切换到另一方向(首秒无历史时优先「出」)。② 若只有一个队列非空,则用该方向。③ 若都空,把 t 跳到下一个到达时间。
  • 为什么用 deque :需要 O(1) 的队首弹出,list 的 pop(0) 是 O(n)。
  • 为什么用 −1 表示「上一秒未使用」 :这样首秒能自然地让「出」优先,与题目规则一致。

常见陷阱

  • 方向决策时把「沿用上一秒」写成「总是切换」 :题目规则是「若上一秒被使用过,优先同方向」。写反会导致方向每秒翻转,结果错误。
  • 用 last = 1 作为首秒初值 :那会让首秒优先「进」,而题目要求首秒(门未被使用)优先「出」。必须用 −1 作哨兵。
  • 无人等待时不跳时间 :若队列为空但还有未到达的人,直接 t += 1 会空转大量时间(arrival 可达 10^9)。必须 t = arrival[i] 跳跃。
  • 用 list 的 pop(0) :O(n) 会让总复杂度退化到 O(n²)。必须用 deque。
  • while i &lt; n and arrival[i] &lt;= t 写成 == t :到达时间可能重复,且跳到 arrival[i] 后可能有多个同刻到达,必须用 &lt;= 。

参考实现

from collections import deque

class Solution:
    def timeTaken(self, arrival: list[int], state: list[int]) -> list[int]:
        n = len(arrival)
        res = [0] * n
        q = [deque(), deque()]      # q[0] 待出,q[1] 待进
        i = 0                       # 下一个尚未到达的人
        t = 0
        last = -1                   # 上一秒使用的方向;-1 表示未使用

        while i < n or q[0] or q[1]:
            # 把 t 时刻及之前到达的人入队
            while i < n and arrival[i] <= t:
                q[state[i]].append(i)
                i += 1

            if q[0] and q[1]:
                # 两方向都有人:优先沿用上一秒的方向;首秒(last == -1)出优先
                if last == -1:
                    direction = 0
                elif q[last]:
                    direction = last
                else:
                    direction = 1 - last
            elif q[0]:
                direction = 0
            elif q[1]:
                direction = 1
            else:
                t = arrival[i]      # 无人等待,时间跳到下一个到达
                continue

            person = q[direction].popleft()
            res[person] = t
            last = direction
            t += 1

        return res