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
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!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code