Show problems as
Classic problem #2515EasyArrayString

Shortest Distance to Target String in a Circular Array

Real-world version: Nearest Stop on the Loop Line
Tracked in this browser only
Read Shortest Distance to Target String in a Circular Array on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

A tram runs a loop line. stops lists the name painted on each stop in the order the tram passes them, and the stop after the last one in the list is the first one again.

A driver standing at the stop in slot startIndex wants to reach a stop named target. One step moves to the neighbouring stop in either direction, and stepping past either end of the list carries on round the loop.

Return the fewest steps that reach a stop named target, or -1 if no stop carries that name. A step count is never negative, so -1 can only mean the name is absent.

Examples

Example 1

Input
stops = ["quay", "mill", "park", "dock", "mill"], target = "mill", startIndex = 3
Output
1

A stop named "mill" sits in slot 4, which is one step forward from slot 3. Another sits in slot 1, which is two steps back.

Example 2

Input
stops = ["zz", "yy", "xx", "ww", "vv"], target = "xx", startIndex = 4
Output
2

From slot 4 the tram reaches slot 2 in two steps backwards, passing slot 3 on the way. Going forward instead would wrap round the loop and take three steps.

Example 3

Input
stops = ["quay", "mill", "park"], target = "yard", startIndex = 1
Output
-1

No stop on the loop is named "yard", so the answer is -1.

Constraints

  • 1 <= stops.length <= 100
  • 1 <= stops[i].length <= 100
  • stops[i] and target consist of lowercase English letters only
  • 0 <= startIndex <= 99
  • startIndex < stops.length

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def nearest_stop(stops: list[str], target: str, startIndex: int) -> int:
Java
public int nearestStop(String[] stops, String target, int startIndex)