Bridge · From syntax to engineering · 25 MIN
Remove duplicates while preserving order
Use one structure for membership and another for output order.
A set gives efficient membership checks, but it is not the output contract when first-seen order matters. Traverse the values, append a value only on its first occurrence, and then record it in the set. Here the inputs are strings and are hashable. If the input were dictionaries, you would first choose a stable identity field. Avoid sorting merely to remove duplicates: sorting changes the original order and costs more work.
Write a small contract first, then test how the implementation behaves at its boundaries.
Read the example
seen = {"api"}
print("api" in seen)Check the expected output
True
Your challenge
Input is a list of strings. Return each distinct string once, preserving first-seen order. Do not modify the input list.
Solution cost: Expected O(n), with string hashing dependent on string length. time · O(u) for distinct values. space
Common trap
list(set(values)) does not preserve the required first-seen order.
Further reading: Python sets
Next lesson: Find a shortest path through an unweighted graph →