Calculate Circular Route Query Distance
AmazonSoftware Engineer · Technical ScreenLast 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 <= 1000001 <= distances[i] <= 1000001 <= len(queries) <= 1000000 <= start, end < n- The answer fits in a 64-bit signed integer.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.