490. Time Taken to Cross the Door
There is a door and n people with numbers ranging from 0 to n-1. Every individual has one second to enter or exit through the door.
A non-decreasing integer array of size n is sent to you, with arrival[i] representing the ith person's arrival time at the door. Additionally, you are provided an array state of size n, where state[i] is 1 if the person wants to leave through the door or 0 if they want to enter.
If two or more persons want to use the door at the same time, they follow the following rules:
- If the door was not used in the previous second, then the person who wants to exit goes first.
- If the door was used in the previous second for entering, the person who wants to enter goes first.
- If the door was used in the previous second for exiting, the person who wants to exit goes first.
- If multiple persons want to go in the same direction, the person with the smallest index goes first.
Return an array answer of size n where answer[i] is the second at which the ith person crosses the door.
Example 1:
Input : arrival = [0, 1, 1, 1, 3], state = [1, 0, 1, 1, 0]
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 exit, so they just exit through the door.
- At t = 1: Person 1 wants to enter, and person 2 and person 3 wants to exit. Since the door was used the previous second for exit, person 2 exits as it has smallest index.
- At t = 2: Person 1 still wants to enter, and person 3 wants to exit. Since the door was used the previous second for exit, person 3 exit.
- At t = 3: Person 1 and Person 4 wants to enter the door. Person 1 being with smallest index enters first.
- At t = 4: Person 4 is the only one who wants to enter now, so they just enter through the door.
Example 2:
Example 2:
Input : arrival = [0,0,0], state = [1,0,1]
Output : [0,2,1]
Explanation : At each second we have the following:
- At t = 0: Person 1 wants to enter while persons 0 and 2 want to exit. Since the door was not used in the previous second, the persons who want to exit get to go first. Since person 0 has a smaller index, they exit first.
- At t = 1: Person 1 wants to enter, and person 2 wants to exit. Since the door was used in the previous second for exiting, person 2 exits.
- At t = 2: Person 1 is the only one who wants to enter, so they just enter through the door.
Now Your Turn!
Pick the correct output for the given inputInput : arrival = [0, 1, 2, 2, 3, 3, 4] , state = [0, 1, 0, 1, 0, 1, 0]
Still unsure what the problem is asking ?
Let’s go through a few more examples, step by step, to make it clearer.
Constraints:
- n == arrival.length == state.length
- 1 <= n <= 105
- 0 <= arrival[i] <= n
- arrival is sorted in non-decreasing order.
- state[i] is either 0 or 1.