Losing head/tail while rewiring
Wrong move: Pointer updates overwrite references before they are saved.
Usually fails on: List becomes disconnected mid-operation.
Fix: Store next pointers first and use a dummy head for safer joins.
Move from brute-force thinking to an efficient approach using linked list strategy.
Given the head of a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. Return the linked list sorted as well.
Example 1:
Input: head = [1,2,3,3,4,4,5] Output: [1,2,5]
Example 2:
Input: head = [1,1,1,2,3] Output: [2,3]
Constraints:
[0, 300].-100 <= Node.val <= 100Problem summary: Given the head of a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. Return the linked list sorted as well.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Linked List · Two Pointers
[1,2,3,3,4,4,5]
[1,1,1,2,3]
remove-duplicates-from-sorted-list)remove-duplicates-from-an-unsorted-linked-list)/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode deleteDuplicates(ListNode head) {
ListNode dummy = new ListNode(0, head);
ListNode prev = dummy;
while (head != null) {
if (head.next != null && head.val == head.next.val) {
int duplicateVal = head.val;
while (head != null && head.val == duplicateVal) head = head.next;
prev.next = head;
} else {
prev = prev.next;
head = head.next;
}
}
return dummy.next;
}
}
/**
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func deleteDuplicates(head *ListNode) *ListNode {
dummy := &ListNode{Val: 0, Next: head}
prev := dummy
for head != nil {
if head.Next != nil && head.Val == head.Next.Val {
dup := head.Val
for head != nil && head.Val == dup {
head = head.Next
}
prev.Next = head
} else {
prev = prev.Next
head = head.Next
}
}
return dummy.Next
}
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:
dummy = ListNode(0, head)
prev = dummy
while head:
if head.next and head.val == head.next.val:
dup = head.val
while head and head.val == dup:
head = head.next
prev.next = head
else:
prev = prev.next
head = head.next
return dummy.next
/**
* Definition for singly-linked list.
* #[derive(PartialEq, Eq, Clone, Debug)]
* pub struct ListNode {
* pub val: i32,
* pub next: Option<Box<ListNode>>
* }
* impl ListNode {
* #[inline]
* fn new(val: i32) -> Self {
* ListNode { next: None, val }
* }
* }
*/
impl Solution {
pub fn delete_duplicates(head: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
let mut vals = Vec::new();
let mut cur = head;
while let Some(mut node) = cur {
vals.push(node.val);
cur = node.next.take();
}
let mut kept = Vec::new();
let mut i = 0usize;
while i < vals.len() {
let mut j = i + 1;
while j < vals.len() && vals[j] == vals[i] {
j += 1;
}
if j == i + 1 {
kept.push(vals[i]);
}
i = j;
}
let mut out: Option<Box<ListNode>> = None;
for &v in kept.iter().rev() {
out = Some(Box::new(ListNode { val: v, next: out }));
}
out
}
}
/**
* Definition for singly-linked list.
* class ListNode {
* val: number
* next: ListNode | null
* constructor(val?: number, next?: ListNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
* }
*/
function deleteDuplicates(head: ListNode | null): ListNode | null {
const dummy = new ListNode(0, head);
let prev: ListNode = dummy;
while (head) {
if (head.next && head.val === head.next.val) {
const dup = head.val;
while (head && head.val === dup) head = head.next;
prev.next = head;
} else {
prev = prev.next!;
head = head.next;
}
}
return dummy.next;
}
Use this to step through a reusable interview workflow for this problem.
Copy all n nodes into an array (O(n) time and space), then use array indexing for random access. Operations like reversal or middle-finding become trivial with indices, but the O(n) extra space defeats the purpose of using a linked list.
Most linked list operations traverse the list once (O(n)) and re-wire pointers in-place (O(1) extra space). The brute force often copies nodes to an array to enable random access, costing O(n) space. In-place pointer manipulation eliminates that.
Review these before coding to avoid predictable interview regressions.
Wrong move: Pointer updates overwrite references before they are saved.
Usually fails on: List becomes disconnected mid-operation.
Fix: Store next pointers first and use a dummy head for safer joins.
Wrong move: Advancing both pointers shrinks the search space too aggressively and skips candidates.
Usually fails on: A valid pair can be skipped when only one side should move.
Fix: Move exactly one pointer per decision branch based on invariant.