1169. Ants on a Ring

Hard7.5 points estimatedBrainteaserSimulationSortingMaths

n ants stand on distinct integer positions of a circular track with circumference length. Ant i starts at positions[i] and walks clockwise (increasing position, modulo length) when dirs[i] = 1 or counterclockwise when dirs[i] = 0, one unit per second. Whenever two ants meet they instantly reverse direction.

Return the position of every ant, by input index and in [0, length), after t seconds. Two ants can end on the same position. Here 1 <= n <= 10^5, n <= length <= 10^9, positions are distinct and lie in [0, length), and 0 <= t <= 10^9.

Think of ants passing through each other as ghosts; the ants keep their cyclic order, rotated by the net number of wraps. This gives O(n log n) time and O(n) space.

Example 1

Input:
length = 10positions = [1,4,8]dirs = [1,1,0]t = 3
Output:
[4,5,7]
Explanation:

The ghost ants end at 4, 7 and 5; sorted they read 4, 5, 7, and since the ants keep their left-to-right order the answer is [4, 5, 7].

Example 2

Input:
length = 5positions = [0,1]dirs = [1,0]t = 1
Output:
[0,1]
Explanation:

The two ants meet halfway, bounce, and return to their starting cells.

Example 3

Input:
length = 8positions = [2,5]dirs = [1,0]t = 0
Output:
[2,5]
Explanation:

With t = 0 nobody moves.

Constraints

1 ≤ n ≤ 105

n ≤ length ≤ 109; positions distinct in [0, length)

dirs[i] is 0 or 1

0 ≤ t ≤ 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)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…