Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python program to find uncommon words from two Strings
In this article, we will learn how to find uncommon words from two strings. Uncommon words are words that appear exactly once across both strings combined.
Problem statement ? We are given two strings, we need to get the uncommon words from the given strings.
Understanding Uncommon Words
A word is considered uncommon if it appears exactly once when we combine both strings. For example:
- String 1: "hello world"
- String 2: "world python"
- Uncommon words: "hello", "python" (each appears once)
- "world" appears twice, so it's not uncommon
Using Dictionary to Count Word Frequency
The most efficient approach is to count the frequency of each word and return words that appear exactly once ?
def find_uncommon_words(string1, string2):
# Dictionary to count word frequencies
word_count = {}
# Count words from first string
for word in string1.split():
word_count[word] = word_count.get(word, 0) + 1
# Count words from second string
for word in string2.split():
word_count[word] = word_count.get(word, 0) + 1
# Return words that appear exactly once
return [word for word in word_count if word_count[word] == 1]
# Example usage
string1 = "Tutorials point"
string2 = "Python on Tutorials point"
result = find_uncommon_words(string1, string2)
print("The uncommon words are:", result)
The uncommon words are: ['Python', 'on']
Using Counter from collections Module
Python's Counter class provides a more concise solution ?
from collections import Counter
def find_uncommon_words_counter(string1, string2):
# Combine both strings and count word frequencies
all_words = string1.split() + string2.split()
word_count = Counter(all_words)
# Return words with frequency 1
return [word for word, count in word_count.items() if count == 1]
# Example usage
string1 = "hello world python"
string2 = "world java programming"
result = find_uncommon_words_counter(string1, string2)
print("Uncommon words:", result)
Uncommon words: ['hello', 'python', 'java', 'programming']
How It Works
The algorithm follows these steps:
- Split strings: Convert both strings into lists of words
- Count frequencies: Use a dictionary to track how many times each word appears
- Filter uncommon words: Return words that have a frequency of exactly 1
Comparison of Methods
| Method | Time Complexity | Space Complexity | Readability |
|---|---|---|---|
| Dictionary with get() | O(n + m) | O(k) | Good |
| Counter class | O(n + m) | O(k) | Excellent |
n, m = lengths of strings; k = unique words
Conclusion
Use dictionary counting to find uncommon words by tracking word frequencies and filtering words that appear exactly once. The Counter class provides a more readable solution for the same approach.
