244. Shortest Word Distance II

244 is for huge data size, 243 is for small data size

Solution1:

compare two lists, one by one => time: O(n^2)

Solution2:

use two pointer => O(n + m)

because the map<String, List<Integer>>, the list adds by order and not repeated,

the shortest distance happened at two list's closest index

ex:

i

j

[ 1(a3), 2(a4), 3(a4), 6(a3), 8(a4) ]

when a[i] < a[j] we should i++ .=> to find next min . (not move j, that's will increase the distance , right?)

i

j

[ 1(a3), 2(a4), 3(a4), 6(a3), 8(a4) ]

until ending

time: O(n), n is the wordsDict's length

space: O(n)

Solution 3:

in two lists, for loop and use binary search

time: O(m * logn)

space: O(n)

Last updated

Was this helpful?