In what scenarios might a LinkedHashSet outperform a TreeSet, and vice versa?

LinkedHashSet and TreeSet are both implementations of the Set interface, but they are optimized for different use cases. LinkedHashSet maintains insertion order and provides faster lookup and insertion operations, while TreeSet automatically keeps elements sorted according to their natural ordering or a custom Comparator.

Key Points: • LinkedHashSet preserves insertion order and typically provides O(1) performance for add(), remove(), and contains() operations. • TreeSet maintains elements in sorted order but performs operations in O(log n) time because it is internally based on a Red-Black Tree. • Choose LinkedHashSet when ordering by insertion sequence and performance are important; choose TreeSet when automatic sorting and range-based operations are required.

Example: In a web application that stores recently visited pages, LinkedHashSet is ideal because it preserves the order in which pages were visited. In contrast, a leaderboard that must always display scores in sorted order would benefit from TreeSet.

Code Example:

import java.util.LinkedHashSet;
import java.util.TreeSet;

public class Main {

    public static void main(String[] args) {

        LinkedHashSet<Integer> linkedHashSet =
                new LinkedHashSet<>();

        linkedHashSet.add(30);
        linkedHashSet.add(10);
        linkedHashSet.add(20);

        System.out.println(
                "LinkedHashSet: "
                + linkedHashSet);

        TreeSet<Integer> treeSet =
                new TreeSet<>();

        treeSet.add(30);
        treeSet.add(10);
        treeSet.add(20);

        System.out.println(
                "TreeSet: "
                + treeSet);
    }
}

Interview Tip: A concise interview answer is: LinkedHashSet outperforms TreeSet when fast insertion, lookup, and insertion-order preservation are required because it offers O(1) average performance. TreeSet is preferable when elements must remain automatically sorted, even though its operations take O(log n) time due to its tree-based implementation.