People Leaving Queries
There are n people standing in a line, occupying positions from 1 to n. Initially, every position has exactly one person.
Design a system that supports these operations:
- leave(x): The person at position x leaves, so that position becomes empty.
- findNearest(x): Return the smallest position y such that: y >= x, and there is still a person standing at position y. If no such position exists, return -1.
A simpler way to understand findNearest(x): start from position x and move to the right until you find a position that is still occupied. Return that position. If none exists, return -1.
NOTE: Only the results of findNearest(x) calls are included in the output.
Example 1:
Input:
calls = ["PeopleLeaving", "findNearest", "leave", "findNearest", "leave", "findNearest", "findNearest", "leave", "findNearest", "leave", "findNearest"]
params = [[5], [1], [3], [3], [2], [1], [2], [4], [3], [5], [3]]
Output: [1, 4, 1, 4, 5, -1]
Explanation:
- PeopleLeaving(5) → creates the system for positions 1 to 5
- findNearest(1) → person at position 1 is still present, so answer is 1
- leave(3) → person at position 3 leaves
- findNearest(3) → nearest standing person at or to the right of 3 is at position 4
- leave(2) → person at position 2 leaves
- findNearest(1) → person at position 1 is still present, so answer is 1
- findNearest(2) → position 2 is empty, next standing person is at position 4
- leave(4) → person at position 4 leaves
- findNearest(3) → next standing person is at position 5
- leave(5) → person at position 5 leaves
- findNearest(3) → no standing person exists at or to the right of 3, so answer is -1
Example 2:
Input:
calls = ["PeopleLeaving", "leave", "findNearest", "leave", "findNearest", "findNearest", "leave"]
params = [[3], [2], [1], [1], [1], [3], [3]]
Output: [1, 3, 3]
Explanation:
- PeopleLeaving(3) → creates the system for positions 1 to 3
- leave(2) → person at position 2 leaves
- findNearest(1) → person at position 1 is still standing, so answer is 1
- leave(1) → person at position 1 leaves
- findNearest(1) → nearest standing person at or to the right of 1 is 3
- findNearest(3) → person at position 3 is still standing, so answer is 3
- leave(3) → person at position 3 leaves
Now Your Turn!
Pick the correct output for the given inputInput:
calls = ["PeopleLeaving", "leave", "findNearest", "leave", "findNearest"]
params = [[2], [1], [1], [2], [1]]
Still unsure what the problem is asking ?
Let’s go through a few more examples, step by step, to make it clearer.
Constraints:
- 1 <= n, m <= 106
- 1 <= x <= n
- Each call is either: leave(x), findNearest(x)
- All positions passed to leave(x) are distinct
- For each findNearest(x), return the nearest standing position y such that y >= x
- If no such position exists, return -1