#2515

Shortest Distance to Target String in a Circular Array

Easy
ArrayStringCircular ArrayTwo Pointers
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal solution involves a single pass through the array to find all occurrences of the target string. By calculating the distances in both directions (clockwise and counterclockwise) simultaneously, we can determine the shortest distance efficiently.

⚙️

Algorithm

5 steps
  1. 1Step 1: Initialize a variable to store the minimum distance as infinity.
  2. 2Step 2: Create a loop to iterate through the circular array and find all occurrences of the target string.
  3. 3Step 3: For each occurrence, calculate the distance to the startIndex in both directions.
  4. 4Step 4: Update the minimum distance if the calculated distance is smaller.
  5. 5Step 5: Return the minimum distance or -1 if the target is not found.
solution.py10 lines
1# Full working Python code
2
3def shortestDistance(words, target, startIndex):
4    min_distance = float('inf')
5    n = len(words)
6    for i in range(n):
7        if words[i] == target:
8            distance = min((i - startIndex) % n, (startIndex - i) % n)
9            min_distance = min(min_distance, distance)
10    return min_distance if min_distance != float('inf') else -1

Complexity note: The time complexity is O(n) because we make a single pass through the array to find the target and calculate distances, which is efficient for this problem.

  • 1The circular nature of the array allows for two potential paths to the target.
  • 2Calculating distances in both directions is crucial for finding the shortest path.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.