Katkat

Calculate Circular Route Query Distance

AmazonSoftware Engineer · Technical Screen

Last updated

This question evaluates a candidate's ability to reason about circular arrays, distance computations, and query-efficient algorithms, assessing concepts such as modular indexing and cumulative distances.

You are given a circular route with n stops numbered 0 to n - 1. The array distances has length n, where distances[i] is the clockwise distance from stop i to stop (i + 1) mod n.

You are also given a list of queries, where each query [start, end] asks for the shortest distance between start and end along the circular route. For each query, you may travel either clockwise or counterclockwise. Return the sum of the shortest distances over all queries.

For example, if distances = [1, 2, 3, 4], the clockwise distance from stop 0 to stop 2 is 1 + 2 = 3, while the other direction is 3 + 4 = 7, so the shortest distance is 3.

Design an efficient algorithm for many queries.

Function signature:

def total_shortest_circular_distance(distances: list[int], queries: list[list[int]]) -> int:
 pass

Constraints:

  • 2 <= n <= 100000
  • 1 <= distances[i] <= 100000
  • 1 <= len(queries) <= 100000
  • 0 <= start, end < n
  • The answer fits in a 64-bit signed integer.