> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Remove Linked List Elements Python Solution

> Tested Python solution for LeetCode 203 with 16 pytest cases. Generate a practice environment with lcpy.

LeetCode 203, [Easy](/catalog/easy). Topics: [Linked List](/catalog/topics/linked-list), [Recursion](/catalog/topics/recursion). [View on LeetCode](https://leetcode.com/problems/remove-linked-list-elements/description/).

Generate this problem as a practice environment: tested reference solution, 16 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 203   # by problem number
lcpy gen -s remove_linked_list_elements   # by problem name
```

## Problem

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

### Examples

![Example 1](https://assets.leetcode.com/uploads/2021/03/06/removelinked-list.jpg)

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

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

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

### Constraints

* The number of nodes in the list is in the range \[0, 10\<sup>4\</sup>]
* 1 \<= Node.val \<= 50
* 0 \<= val \<= 50

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/remove_linked_list_elements/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/remove_linked_list_elements/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from leetcode_py import ListNode


class Solution:
    # Time: O(n)
    # Space: O(1)
    def remove_linked_list_elements(
        self, head: ListNode[int] | None, val: int
    ) -> ListNode[int] | None:
        dummy = ListNode[int](0)
        dummy.next = head
        current = dummy
        while current.next is not None:
            if current.next.val == val:
                current.next = current.next.next
            else:
                current = current.next
        return dummy.next
```

## Complexity

| Time | Space |
| - | - |
| O(n) | O(1) |

## Tags

[NeetCode All](/catalog/neetcode).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.