Problem Description (warm-up)
Implement the methods of the class:
class EnglishSpanishTranslator {
public:
// adds a bi-directional mapping between these words to the knowledge base
void addTranslation(string englishWord, string spanishWord);
// gets english for a spanish word else raise an exception
void getEnglish(string spanishWord);
// gets spanish for an english word else raise an exception
void getSpanish(string englishWord);
};Straightfoward Solution
Use two hashmaps (unordered_map) to keep the relations and return the translations.
Problem description (core)
Implement a generic translator class where you can add translations from any language to any other languge to the knowledge base and can query the same way. It should allow multi-level translations.
Multi-level translations: If there's a word translation in the knowledgebase for English <-> Spanish and Spanish <-> Hindi, when queried for Hindi -> English for the same word, function should still be able to return it if there's an indirect relation.
Solution
- Instead of maintaining two hashmaps, maintain a graph
- define each node having a
wordand it'slanguage - edges represent relation between these words
- define each node having a
- Maintain a mapping to fetch the node having
word-languagecombination in constant time- define key as
word:languageand value as node pointers
- define key as
- Run a DFS from starting node (node with the right word/lang combination) to find out the resultant node and return the translation
Interview Experience Post: https://leetcode.com/discuss/interview-question/2199510/Google-or-L4-or-India-or-June-2022-or-Accepted


