![]() |
VOOZH | about |
Given a string S, the task is to remove all duplicate/repeated words from the given string.
Examples:
Input: S = "Geeks for Geeks A Computer Science portal for Geeks"
Output: Geeks for A Computer Science portal
Explanation: here 'Geeks' and 'for' are duplicate so these words are removed from the string
Input: S = "Publish your own articles on GeeksforGeeks and share your knowledge with the world"
Output: Publish your own articles on GeeksforGeeks and share knowledge with the world
Explanation: here 'your' is the duplicate word so that word is removed from string
Create an empty hash table. Then split given string around spaces. For every word, first check if it is in hash table or not. If not found in hash table, print it and store in the hash table.
Below is the implementation of the above approach:
Geeks for A Computer Science portal
Time Complexity: O(n), where n is the number of words in the input string
Auxiliary Space: O(n), because the set 'hsh' set can potentially store all the unique words in the input string.