Intern
# Given a string consisting of the letters 'X', 'Y', and 'O'. # Find the shortest distance between the letters 'X' and 'Y', # or output 0 if 'X' or 'Y' are missing. # "YY" -> 0 # "XX" -> 0 # "XY" -> 1 # "YOX" -> 2 # "OOOXOOYOXO" -> 2 # "OOOXXOY" -> 2 def distance(string: str) -> int:
sobes.tech AI
Answer from AI
python def distance(string: str) -> int: # Check for presence of 'X' and 'Y' in the string if 'X' not in string or 'Y' not in string: return 0
positions_x = [i for i, ch in enumerate(string) if ch == 'X']
positions_y = [i for i, ch in enumerate(string) if ch == 'Y']
min_dist = float('inf')
i, j = 0, 0
# Use two pointers to find the minimum distance
while i < len(positions_x) and j < len(positions_y):
dist = abs(positions_x[i] - positions_y[j])
if dist < min_dist:
min_dist = dist
# Move the pointer to find a smaller distance
if positions_x[i] < positions_y[j]:
i += 1
else:
j += 1
return min_dist