Bernard Wong
  • Software Engineer
  • Problems
    • Lowest Common Ancestor of a Binary Tree
    • Longest Substring Without Repeating Characters
    • Longest Palindromic Substring
    • Longest Common Prefix
    • Isomorphic Strings
    • Integer to Roman
    • Frog Jump
    • Find the Difference
    • Find k closest elements to a given value
    • Longest Common Subsequence
    • Binary Search Tree from Sorted Array
    • Balanced Binary Tree
    • Sort Using Two Stacks
    • O(1) Stack
    • k-th element to last of a LinkedList
    • Dedup LinkedList
    • Check Rotated String
    • Compress String by Character Count
    • Escape HTML whitespace
    • Check String Permutation
    • Unique String
    • Container With Most Water
    • 4 Sum
    • 3 Sum Closest
    • 3 Sum
    • 2 Sum
    • Maximum Subarray
    • Nested List Weight Sum
    • Palindrome Number
    • Pow(x, n)
    • Regular Expression Matching
    • Remove Nth Node From End of List
    • Reverse Integer
    • Roman to Integer
    • Rotate Array
    • Search a 2D Matrix
    • Shortest Word Distance
    • Two Sum III - Data structure design
    • Valid Parentheses
    • ZigZag Conversion
    • Quicksort
    • Add Two Numbers
    • Best Time to Buy and Sell Stock
    • Letter Combinations of a Phone Number
  • Data Structures
    • Heap
Powered by GitBook
On this page
  1. Problems

Shortest Word Distance

PreviousSearch a 2D MatrixNextTwo Sum III - Data structure design

Last updated 6 years ago

Given a list of words and two words word1 and word2, return the shortest distance between these two words in the list.

For example, Assume that

words = ["practice", "makes", "perfect", "coding", "makes"].

Given

word1 = “coding”, word2 = “practice”, return 3.

Given

word1 = "makes", word2 = "coding", return 1.

Note: You may assume that word1 does not equal to word2, and word1 and word2 are both in the list.

The only difference is now you are given the list of words and your method will be called repeatedly many times with different parameters. How would you optimize it?

Design a class which receives a list of words in the constructor, and implements a method that takes two words word1 and word2 and return the shortest distance between these two words in the list.

The only difference is now word1 could be the same as word2.

Given a list of words and two words word1 and word2, return the shortest distance between these two words in the list.

word1 and word2 may be the same and they represent two individual words in the list.

For example, Assume that

words = ["practice", "makes", "perfect", "coding", "makes"].

Given

word1 = “makes”, word2 = “coding”, return 1.

Given

word1 = "makes", word2 = "makes", return 3.

def shortestDistance(words: Array[String], word1: String, word2: String) = {
  var minDist = Int.MaxValue
  var (word1Index, word2Index) = (-1, -1)
  for ((word, i) <- words.zipWithIndex) {
    if (word == word1) word1Index = i
    else if (word == word2) word2Index = i
    if (word1Index != -1 && word2Index != -1) minDist = minDist min math.abs(word1Index - word2Index)
  }
  minDist
}

val words = Array("practice", "makes", "perfect", "coding", "makes")
shortestDistance(words, "coding", "practice")
shortestDistance(words, "makes", "coding")

/**
  * Follow up
  * https://leetcode.com/problems/shortest-word-distance-ii/
  *
  * @param words
  */
class WordDistance(words: Array[String]) {

  val indexes: Map[String, Array[Int]] = (for {
    (word, i) <- words zipWithIndex
  } yield (word, i)).groupBy(_._1).mapValues(_.map(_._2))

  def shortest(word1: String, word2: String): Int = {
    var minDist = Int.MaxValue
    for (x <- indexes(word1); y <- indexes(word2)) {
      minDist = minDist min math.abs(x - y)
    }
    minDist
  }

}

val wd = new WordDistance(words)
wd.shortest("coding", "practice")
wd.shortest("makes", "coding")

/**
  * Follow up
  *
  * @param words
  * @param word1
  * @param word2
  * @return
  */
def shortestDistanceIII(words: Array[String], word1: String, word2: String) = {
  var minDist = Int.MaxValue
  var (word1Index, word2Index) = (-1, -1)
  val sameWord: Boolean = word1 == word2
  for ((word, i) <- words.zipWithIndex) {
    if (sameWord && word == word1) {
      word1Index = word2Index
      word2Index = i
    } else {
      if (word == word1) word1Index = i
      else if (word == word2) word2Index = i
    }
    if (word1Index != -1 && word2Index != -1) minDist = minDist min math.abs(word1Index - word2Index)
  }
  minDist
}


shortestDistanceIII(words, "makes", "coding")
shortestDistanceIII(words, "makes", "makes")

Shortest Word Distance II
Shortest Word Distance III