Remove Duplicates from Sorted List II

Data Structures
Medium
Amazon
83.4K views

Given the head of a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

Why Interviewers Ask This

Amazon interviewers ask this to evaluate a candidate's mastery of pointer manipulation and edge case handling in linked lists. Unlike simple duplicate removal, this variant requires deleting all instances of duplicates, testing the ability to manage complex node connections without losing the list structure. It specifically assesses attention to detail, as missing boundary conditions like head or tail nodes often leads to subtle bugs that Amazon values engineers must avoid.

How to Answer This Question

1. Clarify Requirements: Confirm if the list is sorted and what happens to nodes with multiple occurrences. Explicitly state you will remove ALL nodes containing duplicates, not just extra copies. 2. Choose Strategy: Propose a dummy node approach to simplify head deletion logic, which is crucial for Amazon's focus on clean, maintainable code. 3. Define Pointers: Initialize a 'prev' pointer pointing to the dummy and a 'current' pointer at the head to traverse the list. 4. Implement Logic: Iterate through the list; if current node value matches the next, skip all subsequent nodes with that same value until a different value or null is found. 5. Link and Advance: If no duplicates are found for the current node, move both pointers forward; otherwise, link prev directly to the new unique node. 6. Edge Cases: Verify logic handles empty lists, single nodes, and cases where all nodes are duplicates.

Key Points to Cover

  • Using a dummy node to eliminate special-case logic for the head
  • Correctly identifying and skipping all instances of a duplicate value block
  • Maintaining O(n) time complexity by traversing the list only once
  • Handling edge cases like an entirely duplicate list or empty input
  • Ensuring proper pointer reassignment to prevent memory leaks or broken chains

Sample Answer

To solve the Remove Duplicates from Sorted List II problem, I would first clarify that we need to delete every node that has a duplicate value, leaving only numbers that appear exactly once. Since the input is sorted, id…

Common Mistakes to Avoid

  • Removing only extra copies instead of all instances of the duplicate number
  • Failing to use a dummy node, leading to complex conditional checks for the head
  • Incorrectly advancing the 'prev' pointer when duplicates are detected
  • Missing the case where the last few nodes in the list are all duplicates

Sound confident on this question in 5 minutes

Answer once and get a 30-second AI critique of your structure, content, and delivery. First attempt is free — no signup needed.

Try it free

Related Interview Questions

Browse all 166 Data Structures questionsBrowse all 184 Amazon questions