-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path243.shortest-word-distance.py
More file actions
65 lines (56 loc) · 1.35 KB
/
243.shortest-word-distance.py
File metadata and controls
65 lines (56 loc) · 1.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
from string import *
from re import *
from datetime import *
from collections import *
from heapq import *
from bisect import *
from copy import *
from math import *
from random import *
from statistics import *
from itertools import *
from functools import *
from operator import *
from io import *
from sys import *
from json import *
from builtins import *
import string
import re
import datetime
import collections
import heapq
import bisect
import copy
import math
import random
import statistics
import itertools
import functools
import operator
import io
import sys
import json
from typing import *
# @leet start
class Solution:
def shortestDistance(self, wordsDict: List[str], word1: str, word2: str) -> int:
word_indices = {}
for i, word in enumerate(wordsDict):
word_indices.setdefault(word, []).append(i)
pos1 = word_indices[word1]
pos2 = word_indices[word2]
# Two-pointer traversal
i, j = 0, 0
min_distance = float("inf")
while i < len(pos1) and j < len(pos2):
index1 = pos1[i]
index2 = pos2[j]
min_distance = min(min_distance, abs(index1 - index2))
# Move the pointer pointing to the smaller index
if index1 < index2:
i += 1
else:
j += 1
return min_distance
# @leet end