Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Remove Linked List Elements

Updated
2 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "203" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.

Problem Statement

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

Explanation

Here's the solution:

  • Handle the head: Continuously remove nodes from the head of the list as long as their values match val. This simplifies the rest of the process.
  • Iterate and remove: Iterate through the remaining list, removing any nodes whose values equal val by adjusting the next pointers of the preceding nodes.

  • Time Complexity: O(n), where n is the number of nodes in the linked list.

  • Space Complexity: O(1), as we are only using a constant amount of extra space.

Code

    class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

def removeElements(head: ListNode, val: int) -> ListNode:
    """
    Removes all nodes with value val from a linked list.

    Args:
        head: The head of the linked list.
        val: The value to remove.

    Returns:
        The head of the new linked list.
    """

    # Remove nodes from the head
    while head and head.val == val:
        head = head.next

    # Remove nodes from the rest of the list
    curr = head
    while curr:
        if curr.next and curr.next.val == val:
            curr.next = curr.next.next
        else:
            curr = curr.next

    return head

More from this blog

C

Chatmagic blog

2894 posts