1167. Hot Potato by Numbers
People numbered 1..n sit clockwise in a circle and person i holds the number steps[i-1]. A pointer starts on person 1 and the counter k starts as steps[0]. Repeatedly, the person k - 1 places clockwise after the pointer among those still seated (the pointer person counts as 1) is eliminated, k becomes the eliminated person's number, and the pointer moves to the next seated person clockwise.
Return the people in the order they are eliminated, until nobody is left. Every choice is forced by the rule, so there is no tie to break. Here 1 <= n <= 10^5 and 1 <= steps[i] <= 10^9.
Find each victim as the ((pos + k - 1) mod remaining)-th survivor with a Fenwick tree, for O(n log n) time and O(n) space.
Example 1
- Input:
- steps = [1,1,1]
- Output:
- [1,2,3]
- Explanation:
Each person holds 1, so the victim is always the pointer person and the order is 1, 2, 3.
Example 2
- Input:
- steps = [3,1,2]
- Output:
- [3,2,1]
- Explanation:
Person 1 holds 3, so person 3 leaves first; person 3 holds 2, so from person 1 the second survivor, person 2, leaves; person 1 is last.
Example 3
- Input:
- steps = [2,4,1,3,5]
- Output:
- [2,1,4,5,3]
- Explanation:
Person 2 leaves first (k = 2) and hands over k = 4; the pointer sits on person 3, so person 1 leaves next, and then persons 4, 5 and 3 follow.
Constraints
1 ≤ n ≤ 105
1 ≤ steps[i] ≤ 109
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 4,000 msC++ 1,000 msJava 2,000 msJavaScript 2,000 msTypeScript 2,000 ms
Expected complexity
- Time
- O(n log n)
- Space
- O(n)