Skip to content
prdlk
Esc
↑↓navigate↵open⌘Jpreview
On this page

82. Remove Duplicates from Sorted List II

You are given the head of a sorted linked list

CompanyAsked withinFrequency
Amazon3 months35
Google3 months24
Bloomberg6 months34
Meta6 months25

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:

  • 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.

Solution

# 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: ListNode | None) -> ListNode | None:
        sentinel = ListNode(0, head)
        pred = sentinel

        while head:
            if head.next and head.val == head.next.val:
                while head.next and head.val == head.next.val:
                    head = head.next

                pred.next = head.next
            else:
                pred = pred.next

            head = head.next

        return sentinel.next

Last updated on

Was this page helpful?