Skip to main content

648. Replace Words


Today's post brings out the awesome question from "problem of the day" on Leetcode. This code implements a solution to replace words in a sentence with their corresponding root words based on a given dictionary of root words. Let's break down the code step by step:



Intuition - So we were provided with the list of words in dictionary and a sentence. For each word in sentence we need to find if that word is starting from any word in the given dictionary. If yes then we need to return that word from dictionary in-place of original word in sentence. 




So it can be either processed using nested loops. one loop on sentence words and inside loop over dictionary words and find out which word in dictionary in the root in word in sentence. For small inputs we can do it but who we are kidding in real life scenario we operate on thousands and sometimes millions of data entries. So check the code constraints and you will realise what i am saying.

Approach- We will optimise the search time by using Tries.

  • Class `Solution`

- `__init__(self)`: Initialises the Solution class with an empty dictionary `self.root` to store the trie structure and an empty dictionary `self.dictionaryDict` to store the dictionary words.


  • Method `createTrie(self, words)`

- `createTrie`: This method creates a trie data structure from the given words. It iterates through each character of each word in the input list `words`, adding each character to the trie. It marks the end of a word by appending `"*"` as a key in the trie.





  • Method `findPrefix(self, words)`

- `findPrefix`: This method finds the shortest prefix of the word in the trie that exists in the dictionary. It starts traversing the trie based on the characters in the input word. If it finds a `"*"` in the trie or reaches a point where the word doesn't exist in the trie, it checks if the current suffix (`suff`) exists in the dictionary. If it does, it returns the current suffix, otherwise, it returns `None`.


  • Method `replaceWords(self, dictionary, sentence)`

- `replaceWords`: This is the main method that replaces words in the given sentence with their corresponding root words from the dictionary. It first initializes an empty list `res` to store the result. Then, it iterates through each word in the dictionary, adding each word to `self.dictionaryDict` and creating a trie for each word using the `createTrie` method. Next, it splits the input sentence into a list of words using `split(' ')`. Then, for each word in the sentence, it finds the shortest prefix using the `findPrefix` method. If a prefix is found, it appends the prefix to the result list `res`, otherwise, it appends the original word. Finally, it joins the elements of `res` with spaces and returns the resulting sentence.



  • Time Complexity

- `createTrie`: Let `n` be the total number of characters in all words in the dictionary. The time complexity of creating the trie is O(n).

- `findPrefix`: Let `m` be the average length of the words in the dictionary and `l` be the length of the longest word. In the worst case, if all words have different prefixes, the time complexity is O(ml).

- `replaceWords`: Let `k` be the number of words in the dictionary and `p` be the number of words in the sentence. The time complexity is O(kml + p).


  • Space Complexity

- The space complexity is O(n + kml), where `n` is the total number of characters in all words in the dictionary, `k` is the number of words in the dictionary, `m` is the average length of the words in the dictionary, and `l` is the length of the longest word.


I hope you like my solution. Do give me an upvote.


Hi, thanks for reading my post, I hope you enjoyed it. So, if you want me to keep you updated with the tech references in coming future please do share your valuable comments with me and also do not forget to share it with your friends....:)

Comments

Popular posts from this blog

WhatsApp hidden Fonts

WhatsApp is a messaging app used by over 1 million world wide. It have been the default messaging app for the people since it was first made, Social messaging app supports Android, IOS and windows. It surely have become crucial part of our lives but some of us may not know about some of its hidden features. Whatsapp gives its user full liberty to block useless contacts, choose wisely to let other people know whether you read their messages or not (read receipts), setting privacy, secret fonts, and recent updates gave us the option to post stories too, no doubt why it is number 1 messaging app. Some of us may know the feature of hidden text and some of us may not, they are very simple. If you ever wanted to highlight the particular text or say make it bold so you can do that on whatsapp Here are some cool tricks that you can do while typing messages to your friends. Italicize the text by placing asterisks before and after the text. _techgen_ make the text appear bold by placing tidle sy...

What is a Processor?

Smartphones have been the most important part of our lives. We have seen the evolution of our  handsets. First we saw landlines which were mess of tangled wires then we saw mobile phones which is successor of landlines. They were portable devices from which you can make calls then we witnessed emergence of Smartphones which were  considered as portable computers which also allows us to make calls. What is a Processor? Underneath that touchscreen display there is a full- fledged computer that commands your apps so that they function properly. A processor executes what you want your smartphone to do or in other word you can say processor is brain of computer. there is Exynos, Snapdragon, quad-core octa-core etc. What is a core? It is an element of surprises. They are present inside processor and are responsible for reading the command and executing them. First devices came with single core processor but later on scientists invented more advanced processors such as dual core , So...

Samsung launches CFG70 curved gaming monitors in India.

Samsung electronics launched its two gaming monitors in India on Thursday, LC24FG70 (24 inch) and LC27FG70 (27 inch)-priced at ₹ 35000 and ₹ 42000 respectively. The company claims that they are first curved gaming computer with a 1 millisecond moving picture response time (MPRT). These two monitors are part of CFG70 series of curved gaming computers which were launched in IFA 2016. Apart from ther fast response time with their VA panels, the both come with Quantum dot technologyand a 144 Hz refresh rate that is optimised for AMD's FreeSynch technology. Both the monitors support a full HD resolution, and company is touting a contrast ratio of 3000:1.Samsung is also boasting of a UX that's specially designed for gamers, with an "intuitive settings dashboard" as well as hotkeys on the front and back of the display to quickly adjust settings between presets. The company also says each monitor undergoes rigorous pre-shipment factory calibration for compatibility with vario...