Remove Duplicates from Sorted List - Linked List - Easy - LeetCode
💻 coding

Remove Duplicates from Sorted List - Linked List - Easy - LeetCode

1 min read 103 words
1 min read
ShareWhatsAppPost on X
  • 1The task is to remove duplicates from a sorted linked list, ensuring each element appears only once.
  • 2The provided solution uses a single traversal approach with O(n) time complexity and O(1) space complexity.
  • 3The algorithm modifies the linked list in place by adjusting the 'next' pointers of duplicate nodes.

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"The task is to remove duplicates from a sorted linked list, ensuring each element appears only once."

Remove Duplicates from Sorted List - Linked List - Easy - LeetCode

Given a sorted linked list, delete all duplicates such that each element appear only once.

Example 1:

Input: 1->1->2 Output: 1->2 Example 2:

Input: 1->1->2->3->3 Output: 1->2->3

/**
 * Definition for singly-linked list.
 * public class ListNode {
 * public int val;
 * public ListNode next;
 * public ListNode(int val=0, ListNode next=null) {
 * this.val = val;
 * this.next = next;
 * }
 * }
 */
public class Solution {
 public ListNode DeleteDuplicates(ListNode head) {
 if(head == null){
 return head;
 }
 ListNode temp = head;
 while(temp.next!=null){
 if(temp.val==temp.next.val){
 temp.next=temp.next.next;
 }
 else{
 temp=temp.next;
 }
 }
 
 return head;
 }
}

Time Complexity: O(n)

Space Complexity: O(1)

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

sumitc91

Published on 30 September 2020 · 1 min read · 103 words

Part of AskGif Blog · coding

You might also like