83. Remove Duplicates from Sorted List LeetCode Solution

In this guide, you will get 83. Remove Duplicates from Sorted List LeetCode Solution with the best time and space complexity. The solution to Remove Duplicates from Sorted List problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Remove Duplicates from Sorted List solution in C++
  4. Remove Duplicates from Sorted List solution in Java
  5. Remove Duplicates from Sorted List solution in Python
  6. Additional Resources
83. Remove Duplicates from Sorted List LeetCode Solution image

Problem Statement of Remove Duplicates from Sorted List

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]

Constraints:

The number of nodes in the list is in the range [0, 300].
-100 <= Node.val <= 100
The list is guaranteed to be sorted in ascending order.

Complexity Analysis

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

83. Remove Duplicates from Sorted List LeetCode Solution in C++

class Solution {
 public:
  ListNode* deleteDuplicates(ListNode* head) {
    ListNode* curr = head;

    while (curr != nullptr) {
      while (curr->next && curr->val == curr->next->val)
        curr->next = curr->next->next;
      curr = curr->next;
    }

    return head;
  }
};
/* code provided by PROGIEZ */

83. Remove Duplicates from Sorted List LeetCode Solution in Java

class Solution {
  public ListNode deleteDuplicates(ListNode head) {
    ListNode curr = head;

    while (curr != null) {
      while (curr.next != null && curr.val == curr.next.val)
        curr.next = curr.next.next;
      curr = curr.next;
    }

    return head;
  }
}
// code provided by PROGIEZ

83. Remove Duplicates from Sorted List LeetCode Solution in Python

class Solution:
  def deleteDuplicates(self, head: ListNode) -> ListNode:
    curr = head

    while curr:
      while curr.next and curr.val == curr.next.val:
        curr.next = curr.next.next
      curr = curr.next

    return head
# code by PROGIEZ

Additional Resources

See also  419. Battleships in a Board LeetCode Solution

Happy Coding! Keep following PROGIEZ for more updates and solutions.