Shortest Distance to Target String in a Circular Array
|
|
The Python function closetTarget
is designed to find the minimum distance to a target word in a circular list of words. The list is circular in the sense that after the last word, the first word follows.
Here’s how the function works:
It starts by checking whether the target word exists in the list. If it doesn’t exist, the function returns -1.
It initializes two variables,
forward_distance
andbackward_distance
, to store the distances to the target word when moving forward and backward in the list, respectively.It then iterates over the list in the forward direction starting from
startIndex
, incrementingforward_distance
until it finds the target word. The operationi % n
ensures that the index wraps around to the beginning of the list after reaching the end.It does the same in the backward direction, decrementing the index from
startIndex
and incrementingbackward_distance
until it finds the target word.Finally, it returns the minimum of
forward_distance
andbackward_distance
, which is the minimum distance to the target word in the circular list.
The function effectively uses the property of modulo operation to handle circular lists and calculates distances in two directions in a single pass, resulting in a time complexity of O(n), where n is the number of words in the list. The space complexity is O(1) as no extra space is used apart from the input list.
One Pass
|
|
The Python function closetTarget
is designed to find the minimum distance to a target word in a circular list of words. The list is circular in that after the last word, the first word follows.
Here’s how the function works:
It starts by initializing the result
res
to positive infinity. This acts as a placeholder for the minimum distance, which will be updated as we find instances of the target word.It then iterates over the list of words. For each word, if it is equal to the target, it calculates the distance
d
from the current index tostartIndex
(the absolute difference between the two indices).In a circular list, a word can be reached either by moving forward from
startIndex
or by moving backward. So, it also calculatesn - d
, which is the distance when moving in the opposite direction.It updates
res
to be the minimum of its current value,d
, andn - d
. This ensures thatres
always holds the smallest possible distance to the target word.Finally, if
res
is still positive infinity (meaning the target word was not found), it returns -1. Otherwise, it returnsres
.
This function effectively uses the property of circular lists to calculate distances in both directions in a single pass, resulting in a time complexity of O(n), where n is the number of words in the list. The space complexity is O(1) as no extra space is used apart from the input list.