LeetCode 83: Remove Duplicates from Sorted List Solution
Master LeetCode problem 83 (Remove Duplicates from Sorted List), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
83. Remove Duplicates from Sorted List
Problem Explanation
Explanation
To solve this problem, we can iterate through the linked list and remove any duplicates we encounter. Since the list is sorted, duplicates will be adjacent to each other. We can traverse the list and compare each node with its next node. If they have the same value, we can skip the next node. If they have different values, we move to the next node.
Algorithm:
- Initialize a pointer
currentto the head of the linked list. - Traverse the linked list while
currentandcurrent.nextare not null. - Compare the values of
currentandcurrent.next. - If the values are the same, set
current.nexttocurrent.next.nextto remove the duplicate. - If the values are different, move
currenttocurrent.next. - Return the modified linked list.
Solution Code
class Solution {
public ListNode deleteDuplicates(ListNode head) {
ListNode current = head;
while (current != null && current.next != null) {
if (current.val == current.next.val) {
current.next = current.next.next;
} else {
current = current.next;
}
}
return head;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 83 (Remove Duplicates from Sorted List)?
This page provides optimized solutions for LeetCode problem 83 (Remove Duplicates from Sorted List) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 83 (Remove Duplicates from Sorted List)?
The time complexity for LeetCode 83 (Remove Duplicates from Sorted List) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 83 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 83 in Java, C++, or Python.