Time Taken to Cross the Door — LeetCode 2534 Python Solution
HardLeetCode PremiumQueueArraySimulation
- Problem
- #2534
- Pattern
- Stack
- Reading time
- 4 min
- Source
- leetcode.com
The problem
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.
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:
Python solution
Python
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) auxiliary |
Pattern: Stack
When the most recent unresolved thing is the one that matters, use a stack. LeetCode 2534. Time Taken to Cross the Door is filed here because LeetCode tags it Queue, which is the vocabulary this hub collects.
The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2534. Time Taken to Cross the Door?
- LeetCode 2534. Time Taken to Cross the Door is rated Hard on LeetCode.
- What is the time complexity of LeetCode 2534. Time Taken to Cross the Door?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 2534. Time Taken to Cross the Door?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 2534. Time Taken to Cross the Door cover?
- LeetCode 2534. Time Taken to Cross the Door is tagged Queue, Array and Simulation on LeetCode.
- Is LeetCode 2534. Time Taken to Cross the Door a premium problem?
- Yes. LeetCode 2534. Time Taken to Cross the Door is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.