What is a set and how is it different from a list?

Answer

A set is an unordered collection of unique elements — it stores no duplicates. A list (array) is an ordered collection that can contain duplicates. Key differences: Uniqueness: sets enforce uniqueness; lists allow duplicates; Order: lists maintain insertion order (indices); sets typically have no defined order (hash sets) though some maintain insertion order (LinkedHashSet) or sorted order (TreeSet); Lookup: checking if an element exists in a hash set is O(1) avg; in a list O(n); Access by index: lists support O(1) index access; sets don't (no index concept). Implementations: HashSet/unordered_set — backed by hash table, O(1) avg operations; TreeSet/set — backed by BST (Red-Black tree), O(log n) operations, sorted order; LinkedHashSet — hash table + linked list, O(1) operations, insertion order. Operations: add(e), remove(e), contains(e), size(), iterate. Set operations: union, intersection, difference. Applications: (1) Finding unique elements; (2) Detecting duplicates; (3) Membership testing; (4) Graph visited nodes; (5) Set operations on data. Example: given an array, find all duplicate elements → add each to a set, check if add returns false (already present).