Shortest Distance to Target String in a Circular Array - Problem

Imagine you're standing at a train station on a circular subway line where trains go in both directions and eventually loop back. You're given an array of station names words and need to find the shortest path to reach your target station.

In this circular array, the last element connects back to the first element, creating an endless loop. From any starting position startIndex, you can move either:

  • Forward: to the next station words[(i + 1) % n]
  • Backward: to the previous station words[(i - 1 + n) % n]

Each move costs exactly 1 step. Your goal is to find the minimum number of steps needed to reach the target station from your starting position.

Return the shortest distance to reach the target string, or -1 if the target doesn't exist in the array.

Input & Output

example_1.py โ€” Basic Case
$ Input: words = ["hello", "i", "am", "leetcode", "hello"], target = "hello", startIndex = 1
โ€บ Output: 1
๐Ÿ’ก Note: Starting from index 1, we can reach "hello" at index 0 by moving 1 step counterclockwise, or reach "hello" at index 4 by moving 3 steps clockwise. The minimum is 1.
example_2.py โ€” Target Not Found
$ Input: words = ["a", "b", "leetcode"], target = "leetcode", startIndex = 0
โ€บ Output: 1
๐Ÿ’ก Note: Starting from index 0, we can reach "leetcode" at index 2 by moving 2 steps clockwise or 1 step counterclockwise. The minimum is 1.
example_3.py โ€” Target Not Exists
$ Input: words = ["i", "eat", "leetcode"], target = "ate", startIndex = 0
โ€บ Output: -1
๐Ÿ’ก Note: The target "ate" does not exist in the words array, so we return -1.

Constraints

  • 1 โ‰ค words.length โ‰ค 100
  • 1 โ‰ค words[i].length โ‰ค 100
  • words[i] and target consist of only lowercase English letters
  • 0 โ‰ค startIndex < words.length

Visualization

Tap to expand
TargetSTARTOtherOtherClockwise: 3 stepsCounter: 1 stepCircular Array NavigationShortest Distance: 1 step (counterclockwise)
Understanding the Visualization
1
Identify the Problem
We have a circular array where the end connects to the beginning
2
Calculate Clockwise
Distance going forward: (target_index - start_index + n) % n
3
Calculate Counterclockwise
Distance going backward: (start_index - target_index + n) % n
4
Choose Minimum
The shortest path is the minimum of both distances
Key Takeaway
๐ŸŽฏ Key Insight: In a circular array, always calculate both clockwise and counterclockwise distances, then choose the minimum!
Asked in
Google 15 Amazon 12 Meta 8 Microsoft 6
28.5K Views
Medium Frequency
~12 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen