DEV Community

Sharmila devi
Sharmila devi

Posted on

# 🧩 Remove Duplicates from Sorted Linked List (Java)

🚀 Problem Statement

You are given the head of a sorted singly linked list.
Your task is to:

  • Remove all duplicate nodes
  • Keep only one occurrence of each value
  • Do it in-place (no extra space)

💡 Key Idea

Since the list is already sorted, duplicates will always be adjacent.

👉 So we just:

  • Traverse the list
  • Compare current node with next node
  • If equal → skip the next node

🧠 Approach

  1. Start from the head
  2. While current node and next node exist:
  • If current.data == current.next.data

    • Remove next node → current.next = current.next.next
  • Else move forward

    1. Return the head

🛠️ Java Implementation (GFG Style)

```java id="r8p4kx"
class Solution {
// Function to remove duplicates from sorted linked list
Node removeDuplicates(Node head) {
// Base case
if (head == null) return null;

    Node current = head;

    while (current != null && current.next != null) {
        if (current.data == current.next.data) {
            // Skip duplicate node
            current.next = current.next.next;
        } else {
            current = current.next;
        }
    }

    return head;
}
Enter fullscreen mode Exit fullscreen mode

}




---

## 🔍 Example



```text id="o4w6f3"
Input:
1 -> 1 -> 2 -> 3 -> 3

Output:
1 -> 2 -> 3
Enter fullscreen mode Exit fullscreen mode

⏱️ Complexity Analysis

Type Complexity
Time O(n)
Space O(1)
  • We traverse the list once
  • No extra memory used

⚠️ Common Mistakes

❌ Moving pointer after deleting (can skip nodes)
❌ Using extra data structures (not needed here)
❌ Forgetting null checks


📌 Key Takeaways

  • Sorted property makes the problem easy
  • Just compare adjacent nodes
  • Modify links instead of creating new nodes

🎯 Final Thoughts

This is a simple but important linked list problem. It teaches:

  • Pointer manipulation
  • In-place operations
  • Efficient traversal

Top comments (0)