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
Shortest Distance to Target in Circular Array INPUT happy [0] sad START[1] corner [2] leetcode TARGET[3] pass [4] around [5] target = "leetcode" startIndex = 1 n = 6 (array length) ALGORITHM STEPS 1 Find Target Positions Scan array for "leetcode" Found at index 3 2 Calculate Clockwise From 1 to 3: steps = 2 |3 - 1| = 2 3 Calculate Counter-CW Go the other way around 6 - 2 = 4 steps 4 Return Minimum min(clockwise, counter-cw) min(2, 4) = 2 Distance Formula Clockwise: 1 --> 2 --> 3 = 2 steps Counter-CW: 1 --> 0 --> 5 --> 4 --> 3 = 4 FINAL RESULT [0] [1] START [2] [3] TARGET [4] [5] Step 1 Step 2 Output 2 Minimum distance found! Key Insight: In a circular array, the shortest path is either clockwise or counter-clockwise. Formula: min(|target_idx - start_idx|, n - |target_idx - start_idx|) where n is array length. TutorialsPoint - Shortest Distance to Target String in a Circular Array | Single Pass with Distance Calculation
Asked in
Google 15 Amazon 12 Microsoft 8
25.0K Views
Medium Frequency
~15 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