All problems
0831EasyArrayString

Nearest Stop on the Loop Line

Tracked in this browser only
Write code

Trains the technique from

LeetCode 2515Shortest Distance to Target String in a Circular Array

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.

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 is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

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