Skip to main content

Command Palette

Search for a command to run...

Shortest Distance to Target String in a Circular Array

Published
2 min read
Shortest Distance to Target String in a Circular Array
G

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] 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.

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;
    }
}

More from this blog

S

Software and Performance Testing Insights

462 posts

Results-Driven Agile QA Specialist | Expert in Mobile & Web Testing | Proficient in Test Planning, Execution, and Root Cause Analysis.