Both of the code snippets you've provided are solutions to the problem of removing duplicates from a sorted singly-linked list. Despite their differences in structure and minor implementation details, they both correctly achieve the same goal. Let's dissect each code, understand how they work, and see why both produce the correct result even though they are written differently.
Understanding the Problem
Problem Statement: Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well.
Example:
Input: 1 -> 1 -> 2 -> 3 -> 3
Output: 1 -> 2 -> 3
Typescript Code Analysis
function deleteDuplicates(head: ListNode | null): ListNode | null {
let currentHead = head;
while (currentHead && currentHead.next) {
if (currentHead.val === currentHead.next.val) {
currentHead.next = currentHead.next.next;
} else {
currentHead = currentHead.next;
}
}
return head;
}
Explanation:
-
Initialization: We start with a pointer currentHead pointing to the head of the list.
-
While Loop Condition: while (currentHead && currentHead.next)
- We loop as long as
currentHead and currentHead.next are not null.
- This ensures that we have at least two nodes to compare.
-
Comparing Current and Next Node Values:
- If
currentHead.val === currentHead.next.val:
- We found a duplicate.
- Remove Duplicate: We set
currentHead.next = currentHead.next.next, effectively skipping over the duplicate node.
- Else:
- No duplicate at this position.
- Move Forward: We advance
currentHead to the next node.
-
Returning the Result: After traversing and modifying the list, we return the original head.
Python Code Analysis
class Solution:
def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:
cur = head
while cur:
while cur.next and cur.next.val == cur.val:
cur.next = cur.next.next
cur = cur.next
return head
Explanation:
-
Initialization: We start with a pointer cur pointing to the head of the list.
-
Outer While Loop Condition: while cur:
- We loop as long as
cur is not None.
- This ensures we traverse every node in the list.
-
Inner While Loop:
- Condition:
while cur.next and cur.next.val == cur.val
- Checks if the next node exists and if it is a duplicate.
- Removing Duplicates:
- Action:
cur.next = cur.next.next
- We bypass the duplicate node(s) by pointing
cur.next to the node after the duplicate.
-
Advancing the Pointer:
- After removing duplicates for the current node, we move
cur to the next node (cur = cur.next).
-
Returning the Result: After processing, we return the modified list starting from head.
Comparing the Two Approaches
Common Ground:
- Both codes traverse the linked list using a pointer (
currentHead in Typescript and cur in Python).
- They compare the current node's value with the next node's value.
- If duplicates are found, they modify the
next pointers to skip over duplicate nodes.
- Both return the head of the modified list.
Differences:
-
Loop Structure:
- Typescript Code:
- Uses a single
while loop with an if-else inside.
- Only advances the
currentHead pointer when no duplicate is found.
- Python Code:
- Uses nested
while loops.
- The inner loop removes all consecutive duplicates of the current value before advancing.
- Advances the
cur pointer after all duplicates are removed.
-
Advancement of Pointer:
- Typescript Code:
- Moves to the next node only when the current node and the next node have different values.
- If duplicates are found consecutively, it repeatedly removes them without moving
currentHead.
- Python Code:
- Removes all duplicates of the current value in the inner loop.
- Then moves
cur to the next node.
-
Handling of Duplicates:
- Typescript Code:
- Handles duplicates one at a time.
- The
if condition checks for a duplicate and removes it, then the loop repeats.
- Python Code:
- Collectively removes all duplicates of the current value in one go using the inner loop.
Why Both Codes Work
-
Data Structure Nature: Since the linked list is sorted, all duplicates will be adjacent. This property allows us to remove duplicates by comparing each node with its next node.
-
Effectiveness of Both Methods:
-
Sequential Removal (Typescript): By checking and removing duplicates one at a time, the Typescript code eventually removes all duplicates even if there are multiple in a row.
-
Batch Removal (Python): By using a nested loop to remove all duplicates of the current value before moving on, the Python code efficiently handles multiple duplicates in a row.
-
End Result: Both methods ensure that for each unique value in the list, only one node remains in the final linked list.
Step-by-Step Example
Let's consider the linked list: 1 -> 1 -> 2 -> 3 -> 3
Typescript Code Flow:
-
currentHead = Node(1)
currentHead.val (1) == currentHead.next.val (1) => Duplicate found.
- Remove duplicate:
currentHead.next = currentHead.next.next (skip the next node).
- List is now:
1 -> 2 -> 3 -> 3
-
currentHead = Node(1)
currentHead.val (1) != currentHead.next.val (2) => No duplicate.
- Move to next node:
currentHead = currentHead.next (Node 2)
-
currentHead = Node(2)
currentHead.val (2) != currentHead.next.val (3) => No duplicate.
- Move to next node:
currentHead = currentHead.next (Node 3)
-
currentHead = Node(3)
currentHead.val (3) == currentHead.next.val (3) => Duplicate found.
- Remove duplicate:
currentHead.next = currentHead.next.next (skip the next node).
- List is now:
1 -> 2 -> 3
-
currentHead = Node(3)
currentHead.next is null. Exit loop.
Python Code Flow:
-
cur = Node(1)
- Inner Loop:
cur.next.val (1) == cur.val (1) => Duplicate found.
- Remove duplicate:
cur.next = cur.next.next (skip the next node).
- List is now:
1 -> 2 -> 3 -> 3
cur.next.val (2) != cur.val (1). Exit inner loop.
- Move to next node:
cur = cur.next (Node 2)
-
cur = Node(2)
- Inner Loop:
cur.next.val (3) != cur.val (2). Exit inner loop.
- Move to next node:
cur = cur.next (Node 3)
-
cur = Node(3)
- Inner Loop:
cur.next.val (3) == cur.val (3) => Duplicate found.
- Remove duplicate:
cur.next = cur.next.next (skip the next node).
- List is now:
1 -> 2 -> 3
cur.next is null. Exit inner loop.
- Move to next node:
cur = cur.next (null). Exit outer loop.
Conclusion
Both solutions are valid and effective in removing duplicates from a sorted linked list. The difference in structure does not affect the correctness because:
- They both rely on the property that duplicates are adjacent in a sorted list.
- They both modify the
next pointers to skip over duplicate nodes.
- They both traverse the entire list, ensuring no duplicates are left unprocessed.
Choice of Implementation:
- The Typescript code is straightforward with a single loop and conditional logic inside.
- The Python code uses nested loops to consolidate the removal of all duplicates for the current node before moving on.
Both styles are acceptable, and choosing one over the other may depend on personal or language-specific preferences. The key takeaway is that despite differences in implementation details, both codes correctly perform the required operation by leveraging the sorted property of the linked list to identify and remove duplicates.
In Summary:
- Different Structures: The codes have different loop structures (single loop vs. nested loops).
- Same Outcome: Both effectively remove duplicates from the list.
- Reason for Correctness: They both correctly identify duplicates and adjust the
next pointers to exclude duplicate nodes, ensuring the final list contains only unique elements.