Shortest Distance to Target String in a Circular Array

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.

Example 1
Inputwords = ["hello","i","am","leetcode","hello"], target = "hello", startIndex = 1
Output1
The shortest way from index 1 to an occurrence of "hello" is moving 1 step left to index 0.
Example 2
Inputwords = ["a","b","leetcode"], target = "leetcode", startIndex = 0
Output1
The shortest way from index 0 to "leetcode" is moving 1 step left to index 2.

Constraints

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

Asked at 4 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate