![]() |
VOOZH | about |
Given a sentence, the task is to remove all duplicate words while keeping only the first occurrence of each word. For example:
Input: "Geeks for Geeks"
Output: "Geeks for"
Let's explore different methods to remove duplicate words efficiently in Python.
This method uses a dictionary, which automatically removes duplicates while maintaining the order of words.
Geeks for
Explanation:
This method uses a set to track seen words and list comprehension to build the final list. It keeps the order and removes duplicates efficiently.
Geeks for
Explanation:
A set in Python is a collection that automatically removes duplicate values. This method is the simplest and fastest. However, set does not maintain order hence, it's not ideal for situations where maintaining order is intended.
Geeks for
Explanation:
This method is the most basic way of removing duplicates but it can be slower for longer sentences. It loops through each word checks if it's already been added to a result list and adds it only if it hasn't appeared before.
Geeks for
Explanation: