Shortest Distance to Target String in a Circular Array - Problem
You are given a 0-indexed circular string array words and a string target. A circular array means that the array's end connects to the array's beginning.
Formally, the next element of words[i] is words[(i + 1) % n] and the previous element of words[i] is words[(i - 1 + n) % n], where n is the length of words.
Starting from startIndex, you can move to either the next word or the previous word with 1 step at a time.
Return the shortest distance needed to reach the string target. If the string target does not exist in words, return -1.
Input & Output
Example 1 — Basic Case
$
Input:
words = ["happy","sad","corner","leetcode","pass","around"], target = "leetcode", startIndex = 1
›
Output:
2
💡 Note:
From index 1 ("sad"), we can reach "leetcode" at index 3 by moving 2 steps clockwise (1→2→3) or 4 steps counterclockwise (1→0→5→4→3). The minimum is 2.
Example 2 — Target at Start
$
Input:
words = ["a","b","c"], target = "a", startIndex = 0
›
Output:
0
💡 Note:
The target "a" is already at the starting position (index 0), so the distance is 0.
Example 3 — Target Not Found
$
Input:
words = ["i","eat","code"], target = "day", startIndex = 1
›
Output:
-1
💡 Note:
The target "day" does not exist in the 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
Input
Circular array with words, target string, and start index
2
Process
Search both clockwise and counterclockwise directions
3
Output
Return minimum steps needed, or -1 if not found
Key Takeaway
🎯 Key Insight: In a circular array, always check both directions and choose the shorter path
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code