Delete all occurrences of a key in DLL

Linked-List FAQS (DLL) Hard
  • One real-world application of this problem can be seen in web browsers
  • Each tab in a web browser can be thought of as a node in a doubly linked list, with the previous and next tabs being the 'previous' and 'next' nodes
  • When a user closes a tab (equivalent to deleting a node), the browser re-links the adjacent tabs (similar to updating the 'previous' and 'next' pointers in the node deletion operation)
  • This scenario underscores the importance of algorithms for maintaining and manipulating doubly linked lists in software applications

Given the head of a doubly linked list and an integer target. Delete all nodes in the linked list with the value target and return the head of the modified linked list.

Examples:

Input: head -> 1 <-> 2 <-> 3 <-> 1 <-> 4, target = 1

Output: head -> 2 <-> 3 <-> 4

Explanation: All nodes with the value 1 were removed.

Input: head -> 2 <-> 3 <-> -1 <-> 4 <-> 2, target = 2

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

Explanation: All nodes with the value 2 were removed.

Note that the value of head is changed.

Input: head -> 7 <-> 7 <-> 7 <-> 7, target = 7

Constraints

  • 1 <= number of nodes in the linked list <= 105
  • -104 <= ListNode.val <= 104
  • -104 <= target <= 104

Hints

  • A brute-force approach would involve: Creating a new list while copying only non-target nodes. Reconstructing the DLL (O(n) space).
  • Traverse the list (O(n)), deleting nodes in-place. Handle three cases efficiently: Head node contains target → Update head. Middle nodes contain target → Update prev.next and next.prev. Tail node contains target → Update prev.next = NULL.

Company Tags

Salesforce ARM Shopify Seagate Technology Uber JPMorgan Chase Reddit Western Digital Mastercard DoorDash Twilio Wayfair MongoDB eBay HCL Technologies Zoho Robinhood Medtronic Zomato Swiggy Texas Instruments Databricks McKinsey & Company PwC Cerner Google Microsoft Amazon Meta Apple Netflix Adobe