Shortest Distance to Target String in a Circular Array — LeetCode 2515 Python Solution
- Problem
- #2515
- Pattern
- Hash Map
- Reading time
- 2 min
- Source
- leetcode.com
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
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(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.