Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #2534: Time Taken to Cross the Door

In this guide, we solve Leetcode #2534 Time Taken to Cross the Door in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

Problem Statement

There are n persons numbered from 0 to n - 1 and a door. Each person can enter or exit through the door once, taking one second.

Quick Facts

  • Difficulty: Hard
  • Premium: Yes
  • Tags: Queue, Array, Simulation

Intuition

We need level-order exploration or shortest-step expansion, which maps directly to a queue.

BFS guarantees the first time you reach a node is the shortest in unweighted graphs.

Approach

Initialize the queue with starting nodes and expand outward layer by layer.

Track visited nodes to avoid cycles and redundant work.

Steps:

  • Initialize a queue with start nodes.
  • Pop, process, and enqueue neighbors.
  • Track visited nodes.

Example

Input: arrival = [0,1,1,2,4], state = [0,1,0,0,1] Output: [0,3,1,2,4] Explanation: At each second we have the following: - At t = 0: Person 0 is the only one who wants to enter, so they just enter through the door. - At t = 1: Person 1 wants to exit, and person 2 wants to enter. Since the door was used the previous second for entering, person 2 enters. - At t = 2: Person 1 still wants to exit, and person 3 wants to enter. Since the door was used the previous second for entering, person 3 enters. - At t = 3: Person 1 is the only one who wants to exit, so they just exit through the door. - At t = 4: Person 4 is the only one who wants to exit, so they just exit through the door.

Python Solution

class Solution: def timeTaken(self, arrival: List[int], state: List[int]) -> List[int]: q = [deque(), deque()] n = len(arrival) t = i = 0 st = 1 ans = [0] * n while i < n or q[0] or q[1]: while i < n and arrival[i] <= t: q[state[i]].append(i) i += 1 if q[0] and q[1]: ans[q[st].popleft()] = t elif q[0] or q[1]: st = 0 if q[0] else 1 ans[q[st].popleft()] = t else: st = 1 t += 1 return ans

Complexity

The time complexity is O(n)O(n)O(n), and the space complexity is O(n)O(n)O(n). The space complexity is O(n)O(n)O(n).

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy