mediumLinked ListsPattern: Recursive Approach

Remove Duplicate Nodes from Linked List Solution

Problem Statement

Implement a function to remove duplicate nodes from a given linked list, preserving the original order of nodes.

Examples

Example 1:
Input:1 -> 2 -> 2 -> 1 -> 3
Output:1 -> 2 -> 3
Explanation: The function removes duplicate nodes (2, 1) from the linked list, preserving the original order.
Example 2:
Input:1 -> 1 -> 2 -> 2 -> 2
Output:1 -> 2
Explanation: The function removes all duplicate nodes (1, 2) from the linked list, preserving the original order.
Example 3:
Input:1 -> 2 -> 3 -> 4 -> 5
Output:1 -> 2 -> 3 -> 4 -> 5
Explanation: The function does not remove any nodes from the linked list since all nodes are unique.

Constraints

  • The linked list nodes may contain integers or strings.
  • The linked list may be empty or contain only one node.
  • The function should preserve the original order of nodes.
Time: O(n) Space: O(n)
A more optimized approach involves using a recursive function to traverse the linked list, keeping track of visited nodes to remove duplicates, with a time complexity of O(n) and space complexity of O(n).

Run, Test & Submit Code

Ready to practice this challenge? Launch our interactive compilation environment with compiler validation.

Solve on Interactive Workspace

Tested Solutions

No solution code is currently loaded.
Complete this code in the workspace editor.