Shortest Distance to Target String in a Circular Array

As a Systems Engineer at Tata Consultancy Services, I deliver exceptional software products for mobile and web platforms, using agile methodologies and robust quality maintenance. I am experienced in performance testing, automation testing, API testing, and manual testing, with various tools and technologies such as Jmeter, Azure LoadTest, Selenium, Java, OOPS, Maven, TestNG, and Postman.
I have successfully developed and executed detailed test plans, test cases, and scripts for Android and web applications, ensuring high-quality standards and user satisfaction. I have also demonstrated my proficiency in manual REST API testing with Postman, as well as in end-to-end performance and automation testing using Jmeter and selenium with Java, TestNG and Maven. Additionally, I have utilized Azure DevOps for bug tracking and issue management.
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]iswords[(i + 1) % n]and the previous element ofwords[i]iswords[(i - 1 + n) % n], wherenis the length ofwords.
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.
LeetCode Problem - 2515
class Solution {
public int closetTarget(String[] words, String target, int startIndex) {
int n = words.length; // Get the length of the words array
// Loop to search for the target in both directions (clockwise and counter-clockwise)
for (int count = 0; count < n; count++) {
// Check the word in the clockwise direction
// The index is calculated using (startIndex + count) % n to ensure it wraps around the array
if (words[(startIndex + count) % n].equals(target)) {
return count; // Return the number of steps taken in the clockwise direction
}
// Check the word in the counter-clockwise direction
// The index is calculated using (startIndex - count + n) % n to ensure it wraps around correctly
if (words[(startIndex - count + n) % n].equals(target)) {
return count; // Return the number of steps taken in the counter-clockwise direction
}
}
// If the target is not found, return -1
return -1;
}
}




