Remove duplicates from a singly linked list
Company: Salesforce
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: HR Screen
Quick Answer: This question evaluates understanding of singly linked list data structures and in-place node manipulation to remove repeated values while preserving relative order, testing competencies in pointer management and duplicate-detection.
Constraints
- 0 <= number of nodes <= 10^5
- -10^9 <= node value (data) <= 10^9
- The relative order of the remaining nodes must be preserved
- Keep only the first occurrence of each value
Examples
Input: [3, 4, 3, 6]
Expected Output: [3, 4, 6]
Explanation: The second 3 is a duplicate of the earlier 3, so it is removed; 4 and 6 are unique.
Input: [3, 4, 3, 2, 6, 1, 2, 6]
Expected Output: [3, 4, 2, 6, 1]
Explanation: The second 3, the second 2, and the second 6 are all later duplicates and get removed, leaving the first occurrence of each value in order.
Input: []
Expected Output: []
Explanation: An empty list (null head) stays empty.
Input: [7]
Expected Output: [7]
Explanation: A single node has no duplicates.
Input: [5, 5, 5, 5]
Expected Output: [5]
Explanation: All nodes share the same value, so only the first 5 survives.
Input: [-1, -2, -1, -3, -2]
Expected Output: [-1, -2, -3]
Explanation: Negative values work the same way; the repeated -1 and -2 are removed.
Input: [1, 2, 3, 4, 5]
Expected Output: [1, 2, 3, 4, 5]
Explanation: No duplicates means the list is unchanged.
Input: [0, 0, 1, 0, 1, 2]
Expected Output: [0, 1, 2]
Explanation: 0 first appears at index 0 and 1 first appears at index 2; later 0s and the later 1 are removed.
Hints
- Walk the list once from head to tail, tracking which values you have already seen in a hash set.
- Keep a node only the first time you encounter its value; skip (unlink) any node whose value is already in the set.
- A single pass with a set gives O(n) time and O(n) extra space — no need to compare every pair of nodes.