KatInterview

Minimum Rides Across Circular Shuttle Lines

Trees & GraphsAuto-graded · 23 test cases
MediumAuto-gradedTrees & Graphsbfsgraphhash-map

Last updated

Find the fewest shuttle lines to board to get from one stop to another, using a graph search over lines and a stop-to-lines index to stay linear in total stops.

A transit system has several shuttle lines. Each line travels around a fixed circular list of stops, again and again without end. A passenger on a line can ride from any stop on it to any other stop on the same line. Passengers may get on or off only at stops that belong to the line they are using.

You begin at stop start, not aboard any shuttle, and you want to arrive at stop goal. To change lines, you get off at a stop that both lines serve and board the other one there.

Return the smallest number of shuttles you need to board to get from start to goal, or -1 if it is impossible.

lines[i] is the list of stops that line i serves, in the order the shuttle visits them. After the last stop it goes back to the first. start and goal are stop IDs.

Rules

  • Every boarding counts as one ride, including the first. Riding a single line between any two of its stops counts as one ride, no matter how many stops are passed.
  • If start == goal, the answer is 0, even if no line serves that stop.
  • Otherwise, if no sequence of boardings leads to goal, return -1. This includes the case where start or goal is not served by any line.
  • Lines can be changed only at a stop shared by both lines. Walking between different stops is not allowed.
  • The result is a single integer.

Constraints

  • 1 <= len(lines) <= 500
  • 1 <= len(lines[i]) <= 10^5
  • sum(len(l) for l in lines) <= 10^5
  • Stops within a single line are distinct; the same stop can appear on many lines.
  • 0 <= lines[i][j] < 10^6
  • 0 <= start, goal < 10^6
  • All values fit in a signed 32-bit integer.

Examples

Example 1

Input: min_shuttle_rides([[2, 4, 9], [9, 11, 5], [5, 13], [4, 5]], 4, 13)

Output: 2

Example 2

Input: min_shuttle_rides([[1, 3, 5], [2, 4], [4, 8]], 3, 8)

Output: -1

Example 3

Input: min_shuttle_rides([[7, 12]], 3, 3)

Output: 0

Hints

Hint 1

The order of stops around the loop does not matter: riding one line from any of its stops to any other costs exactly one ride. Treat each line as a set of stops.

Hint 2

Search over lines instead of stops. Two lines are neighbours if they share a stop. Starting lines (those serving start) are at distance 1, since the first boarding counts.

Hint 3

Do not build line-to-line edges pairwise. Keep a map from each stop to the lines serving it, and expand each stop only once during a breadth-first search, along with a visited flag per line.