Shortest Distance to Target String in a Circular Array — LeetCode 2515 Python Solution

EasyArrayString
Problem
#2515
Pattern
Hash Map
Reading time
2 min

The problem

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.

Example

Input
words = ["hello","i","am","leetcode","hello"], target = "hello", startIndex = 1
Output
1
Explanation
We start from index 1 and can reach "hello" by

Python solution

Python
class Solution:
    def closetTarget(self, words: List[str], target: str, startIndex: int) -> int:
        n = len(words)
        ans = n
        for i, w in enumerate(words):
            if w == target:
                t = abs(i - startIndex)
                ans = min(ans, t, n - t)
        return -1 if ans == n else ans

Complexity

MeasureComplexity
TimeO(n)
SpaceO(1) to O(n) auxiliary

Pattern: Hash Map

Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 2515. Shortest Distance to Target String in a Circular Array is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.

The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2515. Shortest Distance to Target String in a Circular Array?
LeetCode 2515. Shortest Distance to Target String in a Circular Array is rated Easy on LeetCode.
What topics does LeetCode 2515. Shortest Distance to Target String in a Circular Array cover?
LeetCode 2515. Shortest Distance to Target String in a Circular Array is tagged Array and String on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview