Leetcode 2515: Shortest Distance to Target String in a Circular Array

grid47
grid47
Exploring patterns and algorithms
Feb 29, 2024 5 min read

You are given a 0-indexed circular array of strings words and a target string target. A circular array means that the last element connects to the first one. For any index i, the next element is words[(i + 1) % n] and the previous element is words[(i - 1 + n) % n], where n is the length of the array. Starting at startIndex, you can move to either the next or previous word with one step at a time. Your goal is to find the minimum distance needed to reach the target string from the starting index. If target does not exist in the array, return -1.
Problem
Approach
Steps
Complexity
Input: You are given a circular string array `words` and a string `target`.
Example: words = ["good", "morning", "world", "good"], target = "good", startIndex = 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
Output: Return the minimum distance to reach the target string, or -1 if the target is not found in the array.
Example: Output: 1
Constraints:
• If the target does not exist in words, return -1.
Goal: We need to compute the shortest possible distance to the target string in the circular array starting from the given index.
Steps:
• Iterate over the words array to find all indices where the target exists.
• Calculate the distance from the startIndex to each of these indices.
• Compute the shortest circular distance by considering both left and right movements.
• Return the minimum distance, or -1 if the target is not found.
Goal: The problem constraints are provided in the input and output specification sections.
Steps:
• The array length and string length are within manageable limits.
• The target is guaranteed to be a lowercase English string.
Assumptions:
• The words array is non-empty and the target is always a lowercase string.
• The input startIndex is always a valid index.
Input: words = ["good", "morning", "world", "good"], target = "good", startIndex = 2
Explanation: Starting from index 2, the closest 'good' can be found at index 3 by moving 1 step to the left, or at index 0 by moving 3 steps to the right. The shortest distance is 1.

Input: words = ["apple", "banana", "cherry"], target = "banana", startIndex = 0
Explanation: The target 'banana' is directly at index 1, so the shortest distance is 1.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus