Calculate Circular Route Query Distance
Company: Amazon
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: 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.
Constraints
- 2 <= len(distances) <= 100000
- 1 <= distances[i] <= 100000
- 1 <= len(queries) <= 100000
- 0 <= start, end < len(distances)
- The final answer fits in a 64-bit signed integer
Examples
Input: ([1,2,3,4], [[0,2],[2,0],[1,1],[3,1]])
Expected Output: 11
Explanation: Shortest distances are 3 for 0->2, 3 for 2->0, 0 for 1->1, and 5 for 3->1. Their sum is 11.
Input: ([10,1,1,1], [[0,1],[1,3],[2,0]])
Expected Output: 7
Explanation: For 0->1, clockwise is 10 and counterclockwise is 3, so choose 3. For 1->3, the shortest distance is 2. For 2->0, the shortest distance is 2. Total = 3 + 2 + 2 = 7.
Input: ([5,8], [[0,1],[1,0],[0,0]])
Expected Output: 10
Explanation: With two stops, 0->1 has shortest distance 5, 1->0 also has shortest distance 5, and 0->0 is 0. Total = 10.
Input: ([2,2,2,2,2], [[4,2],[0,3],[1,4]])
Expected Output: 12
Explanation: Each query has clockwise distance 6 and counterclockwise distance 4, so each contributes 4. Total = 12.
Hints
- Precompute the clockwise distance from stop 0 to every stop using a prefix sum array.
- For a query (start, end), compute the clockwise distance in O(1), then compare it with total_route_length - clockwise_distance.