1127. Bouncing Shuttle

Easy1.5 points estimatedMathsSimulationBrainteaser

A shuttle runs on a straight track whose stations are numbered 0 to length. It begins at station start moving toward station length, advances exactly one station per step, and the instant it reaches either end it turns around without losing a step.

Return the station where the shuttle stands after steps steps. Walking step by step is far too slow for the largest inputs, so unfold the bouncing track into a line that repeats every 2*length steps.

Constraints: 1 <= length <= 10^9, 0 <= start <= length and 0 <= steps <= 10^15. Use 64-bit arithmetic for start + steps. The intended solution needs O(1) time and O(1) space.

Example 1

Input:
length = 5, start = 2, steps = 4
Output:
4
Explanation:

The shuttle goes 2 to 5 in three steps and bounces back one step to 4.

Example 2

Input:
length = 3, start = 0, steps = 7
Output:
1
Explanation:

From 0 the shuttle runs 0 to 3 and back to 0 in six steps, then one more step puts it at 1.

Constraints

1 ≤ length ≤ 109

0 ≤ start ≤ length

0 ≤ steps ≤ 1015

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O(1)
Space
O(1)

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…