Remove Duplicates from Sorted Linked List - The Coding Shala

Home >> Interview Prep >> Remove Duplicates from Sorted Linked List

 In this post, we will learn how to Remove Duplicates from Sorted Linked List in Java.

Remove Duplicates from Sorted Linked List Problem

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 1:
Input: head = [1,1,2]
Output: [1,2]

Example 2:
Input: head = [1,1,2,3,3]
Output: [1,2,3]

Remove Duplicates from Sorted Linked List Java Solution

Approach 1

Iterative method.

Time Complexity: O(n)
Space Complexity: O(1)

Java Program: 

 * 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; = next; }
 * }
class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        if(head == null) return head;
        ListNode current = head;
        while( != null) {
            //check for duplicates
            if(current.val == {
                //if duplicate then skip next
            } else {
                current =;
        return head;

Other Posts You May Like
Please leave a comment below if you like this post or found some errors, it will help me to improve my content.


Popular Posts from this Blog

LeetCode - Crawler Log Folder Solution - The Coding Shala

Richest Customer Wealth LeetCode Solution - The Coding Shala

First Unique Character in a String Java - The Coding Shala

Shell Script to find sum, product and average of given numbers - The Coding Shala

Add two numbers in Scala - The Coding Shala