Katkat

Compute Total Manual Distance

CoinbaseSoftware Engineer · Onsite

Last updated

This problem tests your ability to simulate a state-based movement process and calculate cumulative distance based on a non-monotonic set of instructions.

Problem Statement

You are given a list of actions, where each action is a tuple (direction, steps). The direction is either 1 (representing clockwise/forward) or -1 (representing counter-clockwise/backward) along a circular track of size M.

Starting at position 0, you must process the list of actions sequentially. Your task is to calculate the total distance traveled across the track. The distance is defined as the absolute number of steps moved, regardless of the direction. However, if the movement causes the position to wrap around the track, you must account for the specific track boundaries.

Given the track size M (an integer) and an array of actions (a list of pairs), return the total units moved.

Function Signature

def calculate_total_distance(M: int, actions: List[Tuple[int, int]]) -> int:

Constraints

  • M >= 1
  • actions length = 0

Examples

Example 1:

  • Input: M = 10, actions = [(1, 3), (-1, 2), (1, 6)]
  • Output: 11
  • Explanation: Start at 0. Move +3 (pos 3), move -2 (pos 1), move +6 (pos 7). Total distance: 3 + 2 + 6 = 11.

Example 2:

  • Input: M = 5, actions = [(1, 7)]
  • Output: 7
  • Explanation: Moving 7 steps on a track of size 5 results in a net position change, but the total distance moved remains 7.

Edge Cases

  • What happens if M=1?
  • What happens if the steps are 0?
  • What happens if the total steps move multiple full circles?

Hints

Hint 1

Note that the problem asks for the total distance traveled, not the final displacement from the starting point.

Hint 2

Since the movement is additive and cumulative, you do not need to track the current position using modulo arithmetic to find the total distance.

Hint 3

The total distance is simply the sum of all absolute 'steps' provided in the input actions array.

Follow-up questions

  • How would your approach change if you were asked to return the final position on the track instead of the total distance?
  • If the track had 'forbidden segments' that couldn't be crossed, how would you modify the simulation?
  • How would you optimize the solution if the input `actions` list was provided as a stream of data?