Compute Turnstile Crossing Times
Company: Google
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: hard
Interview Round: Technical Screen
Quick Answer: This question evaluates proficiency in queue simulation, event-driven scheduling, and handling priority and tie-breaking rules while achieving linear time complexity.
Constraints
- 0 <= n == len(time) == len(direction) <= 2 * 10^5
- 0 <= time[i] <= 10^9
- direction[i] is either 0 or 1
- time is sorted in nondecreasing order
Examples
Input: ([0,0,1,5], [0,1,1,0])
Expected Output: [2,0,1,5]
Explanation: At t=0 the turnstile was idle, so exiting person 1 goes first. At t=1 person 2 also wants to exit and keeps priority. Person 0 enters at t=2, and after an idle gap person 3 enters at t=5.
Input: ([0,0,0], [0,1,0])
Expected Output: [1,0,2]
Explanation: All arrive at t=0. Because the turnstile was idle, exiting person 1 goes first at t=0. Then persons 0 and 2 enter in increasing index order.
Input: ([2,2,10], [1,0,1])
Expected Output: [2,3,10]
Explanation: At t=2 person 0 exits first, then person 1 enters at t=3. No one waits after that, so time jumps directly to t=10 and person 2 exits.
Input: ([1,1,3,3], [0,1,0,1])
Expected Output: [2,1,3,4]
Explanation: Person 1 exits at t=1. Then person 0 enters at t=2. At t=3 both person 2 (enter) and person 3 (exit) are waiting, and enter has priority because the previous use was also enter.
Input: ([0,1,1,1,2], [1,0,1,0,0])
Expected Output: [0,2,1,3,4]
Explanation: Person 0 exits at t=0, person 2 exits at t=1, then only entering people remain. Among entering people, smaller indices go first: person 1, then 3, then 4.
Input: ([0], [0])
Expected Output: [0]
Explanation: Only one person is present, so they use the turnstile immediately at t=0.
Input: ([], [])
Expected Output: []
Explanation: No people are waiting, so the result is an empty list.
Hints
- Maintain two queues of waiting people: one for enter and one for exit. Because indices increase naturally, queue order also handles the smaller-index tie break.
- When both queues are empty, jump the current time directly to the next person's arrival time and treat the previous second as unused.