Leetcode Problem 2515. Shortest Distance to Target String in a Circular Array

2515. Shortest Distance to Target String in a Circular Array

Leetcode Solutions

Iterative Search in Both Directions

  1. Check if the word at startIndex is the target. If yes, return 0.
  2. Initialize two counters, rightSteps and leftSteps, to 0.
  3. Iterate to the right from startIndex, incrementing rightSteps until the target is found or we return to startIndex.
  4. Similarly, iterate to the left from startIndex, incrementing leftSteps until the target is found or we return to startIndex.
  5. If the target is found in either direction, return the minimum of rightSteps and leftSteps.
  6. If the target is not found after a full iteration in both directions, return -1.
UML Thumbnail

Single Pass Search with Distance Calculation

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...