Remove Duplicate Words

Remove duplicate words from string.

Logic BuildingIntermediate
Logic Building
# Take string input
s = input("Enter a string: ")

# Remove duplicate words
words = s.split()
unique_words = []
seen = set()
for word in words:
    if word not in seen:
        unique_words.append(word)
        seen.add(word)

result = " ".join(unique_words)
print(f"Without duplicates: {result}")

Output

Enter a string: hello world hello programming
Without duplicates: hello world programming

Keep only first occurrence of each word.

Key Concepts:

  • Use set to track seen words
  • Add to result if not seen
  • Preserves order