◻️924. Shortest Word Distance (easy)

[Lintcode] Problem Link: https://www.lintcode.com/problem/924/descriptionarrow-up-right

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

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

Example 1:

Input:["practice", "makes", "perfect", "coding", "makes"],"coding","practice"
Output:3
Explanation:index("coding") - index("practice") = 3

Example 2:

Input:["practice", "makes", "perfect", "coding", "makes"],"makes","coding"
Output:1
Explanation:index("makes") - index("coding")

Solutions

Optimised

Runtime 222ms Memory 3.64MB

class Solution {
public:
    /**
     * @param words: a list of words
     * @param word1: a string
     * @param word2: a string
     * @return: the shortest distance between word1 and word2 in the list
     */
    int shortestDistance(vector<string> &words, string &word1, string &word2) {
        int ans = INT_MAX;
        for (int k = 0, i = -1, j = -1; k < words.size(); ++k) {
            if (words[k] == word1) {
                i = k;
            }
            if (words[k] == word2) {
                j = k;
            }
            if (i != -1 && j != -1) {
                ans = min(ans, abs(i - j));
            }
        }
        return ans;
    }
};

Last updated