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

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

Single Number 3 LeetCode Solution - The Coding Shala

LeetCode - Number of Good Pairs Solution - The Coding Shala

Shell Script to Create a Simple Calculator - The Coding Shala

Java Method Overloading - The Coding Shala