Skip to content

Instantly share code, notes, and snippets.

@dautermann
Created April 24, 2017 14:01
Show Gist options
  • Save dautermann/7879a684ef52fd875fb795aed2674c23 to your computer and use it in GitHub Desktop.
Save dautermann/7879a684ef52fd875fb795aed2674c23 to your computer and use it in GitHub Desktop.
Given a list of words, provide a method that takes two words and returns the shortest distance (in words) between those two words in the provided text.
/* The following was a coding question given during an interview for LinkedIn in March, 2017 */
/* This class will be given a list of words (such as might be tokenized
* from a paragraph of text), and will provide a method that takes two
* words and returns the shortest distance (in words) between those two
* words in the provided text.
* Example:
* WordDistanceFinder finder = new WordDistanceFinder(Arrays.asList("the", "quick", "brown", "fox", "quick"));
* assert(finder.distance("fox", "the") == 3);
* assert(finder.distance("quick", "fox") == 1);
*
* "quick" appears twice in the input. There are two possible distance values for "quick" and "fox":
* (3 - 1) = 2 and (4 - 3) = 1.
* Since we have to return the shortest distance between the two words we return 1.
*/
/* And now my answer in Swift 3 */
import Foundation
class WordDistanceFinder
{
var words : [String]?
init(array : [String])
{
words = array
}
func distance(_ word1: String, _ word2: String) -> Int
{
var distance = 99999
// dereference optional
if let words = words
{
// find indexes for word1 matches in the word array
let arrayA = words.enumerated().filter {
$0.element.contains(word1)
}.map{$0.offset}
// and word2, too
let arrayB = words.enumerated().filter {
$0.element.contains(word2)
}.map{$0.offset}
// now use binary search to find element with closest value in the index arrays
var i = 0
var j = 0
var finished = false
repeat {
if arrayA[i] == arrayB[j]
{
return 0
}
let diff = abs(arrayA[i] - arrayB[j])
distance = min(distance, diff)
if arrayA[i] > arrayB[j]
{
j = j+1
} else {
i = i+1
}
if(j >= arrayB.count)
{
finished = true
}
if(i >= arrayA.count)
{
finished = true
}
} while (finished == false)
}
return distance;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment