VOOZH about

URL: https://www.geeksforgeeks.org/dsa/remove-duplicaterepeated-words-string/

⇱ Remove Duplicate/Repeated words from String - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Remove Duplicate/Repeated words from String

Last Updated : 11 Jul, 2025

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 

Remove Duplicate/Repeated words from String using Hashing:

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.

  • Split the input string into individual words.
  • Keep track of visited words using an unordered set.
  • Print each word only if it hasn't been encountered before, effectively removing duplicates from the output.

Below is the implementation of the above approach:


Output
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.

Comment
Article Tags:
Article Tags: