Skip to content
Related Articles

Related Articles

Python program to remove words that are common in two Strings

View Discussion
Improve Article
Save Article
  • Difficulty Level : Medium
  • Last Updated : 31 Mar, 2021
View Discussion
Improve Article
Save Article

Given two strings S1 and S2, representing sentences, the task is to print both sentences after removing all words which are present in both sentences.

Input: S1 = “sky is blue in color”, S2 =”Raj likes sky blue color “
Output: is in
             Raj likes 
Explanation: The common words are [ sky, blue, color ]. Removing these words from the two sentences modifies the sentences to the specified output.

Input: S1 = learn data structures and algorithms in GeeksforGeeks“, S2 = GeeksforGeeks is the computer science portal for Geeks
Output: learn data structures and algorithms in
              is the computer science portal for.

Approach using Hashing: The problem can be solved using Counter() function. Follow the steps below to solve the problem:

  • As all the words in a sentence are separated by spaces, split the words by spaces using split() and store them in a List.
  • Initialize two lists, say sentence1 and sentence2, to store the words of the two given sentences.
  • Count frequencies of the words of both sentences using the Counter() function and store it in dictionaries frequency1 and frequency2.
  • Traverse the list sentence1 and remove the words which are present in the dictionary frequency2.
  • Traverse the list sentence2 and remove the words which are present in the dictionary frequency1.
  • Print both the lists.

Below is the implementation of the above approach:

Python3




# Python program for the above approach
from collections import Counter
  
# Function to remove common
# words from two strings
def removeCommonWords(sent1, sent2):
    
    # Store the words present
    # in both the sentences
    sentence1 = list(sent1.split())
    sentence2 = list(sent2.split())
      
    # Calculate frequency of words
    # using Counter() function
    frequency1 = Counter(sentence1)
    frequency2 = Counter(sentence2)
  
  
    word = 0
      
    # Iterate the list consisting
    # of words in the first sentence 
    for i in range(len(sentence1)):
        
        # If word is present
        # in both the strings
        if sentence1[word] in frequency2.keys():
            
              # Remove the word
            sentence1.pop(word)
              
            # Decrease the frequency of the word
            word = word-1
        word += 1
          
    word = 0
      
    # Iterate the list consisting of
    # words in the second sentence 
    for i in range(len(sentence2)):
        
        # If word is present
        # in both the strings
        if sentence2[word] in frequency1.keys():
            
              # Remove the word
            sentence2.pop(word)
              
            # Decrease the removed word
            word = word-1
              
        word += 1
          
    # Print the remaining
    # words in the two sentences
    print(*sentence1)
    print(*sentence2)
  
  
# Driver Code
  
sentence1 = "sky is blue in color"
sentence2 = "raj likes sky blue color"
  
removeCommonWords(sentence1, sentence2)

Output:

is in
raj likes


Time Complexity: O((max(N, M))2)
Auxiliary Space: O(max(N, M))

Approach using Sets and Lists: Follow the steps below to solve the problem:

  • As all the words in a sentence are separated by spaces, split the words by spaces using split() and store them in a List.
  • Initialize two lists, say sentence1 and sentence2, to store the words of the two given sentences.
  • Convert the two Lists into Sets, say sen1 and sen2.
  • Now, find the set intersection of two sets, to store words that are common in both the sentences, say common.
  • Traverse the List sentence1 and pop all the words which are present in the set intersection of two sentences.
  • Repeat the same for the second sentence.
  • Finally, print the remaining words in the two Lists.

Below is the implementation of the above approach:

Python3




# Python program to implement
# the above approach
  
# Function to return the words which
# are common in both the sentences
def commonWords(sent1, sent2):
    
    # Splitting the words in a set
    sen1 = set(sent1)
    sen2 = set(sent2)
      
    # Stores the list of common words
    common = list(sen1.intersection(sen2))
      
    # Return the list
    return common
  
# Function to remove all the words
# that are common in both the strings
def removeCommonWords(sent1, sent2):
    
    # Stores the words of the
    # sentences in separate lists
    sentence1 = list(sent1.split())
    sentence2 = list(sent2.split())
      
    # Find the words that are
    # common in both the sentences
    commonlist = commonWords(sentence1, 
                             sentence2)
  
    word = 0
      
    # Iterate the list of words
    # of the first sentence
    for i in range(len(sentence1)):
        
        # If word is common in both lists
        if sentence1[word] in commonlist:
            
              # Remove the word
            sentence1.pop(word)
              
            # Decrease the removed word
            word = word - 1
        word += 1
  
    word = 0
      
    # Iterate the list of words
    # of the second sentence
    for i in range(len(sentence2)):
        
        # If word is common in both lists
        if sentence2[word] in commonlist:
            
              # Remove the word
            sentence2.pop(word)
              
            # Decrease the removed word
            word = word-1
        word += 1
          
    # Print the remaining words
    # in both the sentences
    print(*sentence1)
    print(*sentence2)
  
  
# Driver Code
  
S1 = "sky is blue in color"
S2 = "Raj likes sky blue color"
  
removeCommonWords(S1, S2)

Output:

is in
Raj likes


Time Complexity: O(max(N, M))
Auxiliary Space: O(max(N, M))


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!