EasyNo. 0203

Remove Linked List Elements — LeetCode 203 Python Solution

Topics
Recursion, Linked List
Reading time
3 min

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

Example

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

Python solution

PythonSolution
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def removeElements(self, head: ListNode, val: int) -> ListNode:
        dummy = ListNode(-1, head)
        pre = dummy
        while pre.next:
            if pre.next.val != val:
                pre = pre.next
            else:
                pre.next = pre.next.next
        return dummy.next

Complexity

Time
O(n)
Space · auxiliary
O(1)

Pattern: Linked List

Rewire pointers in place, with a dummy head and a saved next to keep it safe. LeetCode 203. Remove Linked List Elements is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Linked List.

The linked list guide has the Python template for the pattern and the 75 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0206Reverse Linked ListEasy
0021Merge Two Sorted ListsEasy
0024Swap Nodes in PairsMedium
0025Reverse Nodes in k-GroupHard
0019Remove Nth Node From End of ListMedium
0061Rotate ListMedium

Frequently asked questions

How hard is LeetCode 203. Remove Linked List Elements?

LeetCode 203. Remove Linked List Elements is rated Easy on LeetCode.

What is the time complexity of LeetCode 203. Remove Linked List Elements?

The Python solution on this page runs in O(n).

What is the space complexity of LeetCode 203. Remove Linked List Elements?

The Python solution on this page uses O(1) auxiliary space.

What topics does LeetCode 203. Remove Linked List Elements cover?

LeetCode 203. Remove Linked List Elements is tagged Recursion and Linked List on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.