203. Remove Linked List Elements LeetCode Solution

In this guide, you will get 203. Remove Linked List Elements LeetCode Solution with the best time and space complexity. The solution to Remove Linked List Elements 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 Linked List Elements solution in C++
  4. Remove Linked List Elements solution in Java
  5. Remove Linked List Elements solution in Python
  6. Additional Resources
203. Remove Linked List Elements LeetCode Solution image

Problem Statement of Remove Linked List Elements

Given the head of a linked list and an integer val, remove all the nodes of the linked list that has Node.val == val, and return the new head.

Example 1:

Input: head = [1,2,6,3,4,5,6], val = 6
Output: [1,2,3,4,5]

Example 2:

Input: head = [], val = 1
Output: []

Example 3:

Input: head = [7,7,7,7], val = 7
Output: []

Constraints:

The number of nodes in the list is in the range [0, 104].
1 <= Node.val <= 50
0 <= val <= 50

Complexity Analysis

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

203. Remove Linked List Elements LeetCode Solution in C++

class Solution {
 public:
  ListNode* removeElements(ListNode* head, int val) {
    ListNode dummy(0, head);
    ListNode* prev = &dummy;

    for (; head; head = head->next)
      if (head->val != val) {
        prev->next = head;
        prev = prev->next;
      }
    prev->next = nullptr;  // In case that the last value equals `val`.

    return dummy.next;
  }
};
/* code provided by PROGIEZ */

203. Remove Linked List Elements LeetCode Solution in Java

class Solution {
  public ListNode removeElements(ListNode head, int val) {
    ListNode dummy = new ListNode(0, head);
    ListNode prev = dummy;

    for (; head != null; head = head.next)
      if (head.val != val) {
        prev.next = head;
        prev = prev.next;
      }
    prev.next = null; // In case that the last value equals `val`.

    return dummy.next;
  }
}
// code provided by PROGIEZ

203. Remove Linked List Elements LeetCode Solution in Python

class Solution:
  def removeElements(self, head: ListNode, val: int) -> ListNode:
    dummy = ListNode(0, head)
    prev = dummy

    while head:
      if head.val != val:
        prev.next = head
        prev = prev.next
      head = head.next
    prev.next = None

    return dummy.next
# code by PROGIEZ

Additional Resources

See also  767. Reorganize String LeetCode Solution

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