Shortest Distance to Target String in a Circular Array
Real-world version: Nearest Stop on the Loop LineThe 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.
def nearest_stop(stops: list[str], target: str, startIndex: int) -> int:public int nearestStop(String[] stops, String target, int startIndex)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 11 test cases: 11 passed
- Passed: 3 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's
More on the same topics
- Longest Common PrefixReal-world version: Shared Crate CodeEasy
- Shortest Word DistanceReal-world version: Closest Station Calls in the Announcement LogEasy
- Verifying an Alien DictionaryReal-world version: Catalogue Order Under a Custom Glyph SequenceEasy
- Find Common CharactersReal-world version: Tiles Every Rack Can SupplyEasy