Remove duplicated from sorted DLL

Linked-List FAQS (DLL) Hard

Given the head of a doubly linked list with its values sorted in non-decreasing order. Remove all duplicate occurrences of any value in the list so that only distinct values are present in the list.


Return the head of the modified linked list.

Examples:

Input: head -> 1 <-> 1 <-> 3 <-> 3 <-> 4 <-> 5

Output: head -> 1 <-> 3 <-> 4 <-> 5

Explanation: head -> 1 <-> 1 <-> 3 <-> 3 <-> 4 <-> 5

The underlined nodes were deleted to get the desired result.

Input: head -> 1 <-> 1 <-> 1 <-> 1 <-> 1 <-> 2

Output: head -> 1 <-> 2

Explanation: head -> 1 <-> 1 <-> 1 <-> 1 <-> 1 <-> 2

The underlined nodes were deleted to get the desired result.

Input: head -> 1 <-> 2 <-> 3

Constraints

  • 1 <= number of nodes in the linked list <= 105
  • -104 <= ListNode.val <= 104
  • Values of nodes are sorted in non-decreasing order.

Hints

  • A brute-force approach would involve: Using a HashMap (O(n) space) to track occurrences. Reconstructing the DLL without duplicates.
  • Since the list is already sorted, duplicates will always be adjacent. Traverse the list (O(n)), removing all occurrences of duplicate values in one pass. Use a dummy node (O(1) space) to handle head modifications cleanly.

Company Tags

Deloitte ARM KPMG Reddit Splunk Seagate Technology Stripe McKinsey & Company Roche Ubisoft Rakuten Salesforce Rockstar Games Texas Instruments Bain & Company Qualcomm HashiCorp Pinterest Intel Epic Games Micron Technology Morgan Stanley Byju's GE Healthcare MongoDB Google Microsoft Amazon Meta Apple Netflix Adobe