All problems
0782EasyArray

Shortest Run Round The Monorail Loop

Tracked in this browser only
Write code

Trains the technique from

LeetCode 1184Distance Between Bus Stops

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

An airport monorail serves terminals numbered 0 to n - 1 set out on a closed loop. hop[i] is the length of track joining terminal i to terminal i + 1 for every i < n - 1, and the last entry hop[n - 1] is the length of track joining terminal n - 1 back to terminal 0, which closes the loop.

A shuttle may set off either way round the loop and must stay in that direction until it arrives. Given the terminal a passenger boards at and the terminal they get off at, return the smallest total track length the shuttle can cover to carry them there.

Boarding and alighting at the same terminal covers no track at all.

Examples

Example 1

Input
hop = [4,7,2,9,5], boarding = 1, alighting = 4
Output
9

Running from terminal 1 down through terminal 0 covers hop[0] = 4 and then hop[4] = 5, so that direction totals 9. Running the other way covers hop[1] = 7, hop[2] = 2 and hop[3] = 9, a total of 18.

Example 2

Input
hop = [1,20,20,20], boarding = 1, alighting = 0
Output
1

Terminals 0 and 1 are joined directly by hop[0] = 1, and the way round through terminals 2 and 3 covers 20 + 20 + 20 = 60.

Example 3

Input
hop = [6,6,6,6], boarding = 3, alighting = 3
Output
0

The passenger gets off where they got on, so the shuttle covers no track.

Constraints

  • 1 <= hop.length <= 10^4
  • 0 <= hop[i] <= 10^4
  • 0 <= boarding <= 10^4 - 1
  • 0 <= alighting <= 10^4 - 1
  • boarding and alighting are terminal numbers, so both are below hop.length.

The signature

The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def shortest_loop_run(hop: list[int], boarding: int, alighting: int) -> int:
Java
public int shortestLoopRun(int[] hop, int boarding, int alighting)
September 7
Apply