Solving Leetcode Interviews in Seconds with AI: Delete Nodes From Linked List Present in Array
Introduction
In this blog post, we will explore how to solve the LeetCode problem "3217" 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
You are given an array of integers nums and the head of a linked list. Return the head of the modified linked list after removing all nodes from the linked list that have a value that exists in nums. Example 1: Input: nums = [1,2,3], head = [1,2,3,4,5] Output: [4,5] Explanation: Remove the nodes with values 1, 2, and 3. Example 2: Input: nums = [1], head = [1,2,1,2,1,2] Output: [2,2,2] Explanation: Remove the nodes with value 1. Example 3: Input: nums = [5], head = [1,2,3,4] Output: [1,2,3,4] Explanation: No node has value 5. Constraints: 1 <= nums.length <= 105 1 <= nums[i] <= 105 All elements in nums are unique. The number of nodes in the given list is in the range [1, 105]. 1 <= Node.val <= 105 The input is generated such that there is at least one node in the linked list that has a value not present in nums.
Explanation
Here's the solution:
- Convert
numsto a Set: Create asetfrom thenumsarray for O(1) average time complexity lookups. This is much faster than searching the array repeatedly. - Iterate and Remove: Iterate through the linked list, using a "dummy head" to simplify removing the actual head of the list if needed. If a node's value is in the
set, remove it by adjusting thenextpointer of the previous node. Return Modified Head: Return the
nextpointer of the dummy head, which will be the new head of the modified list.Time Complexity: O(N + M), where N is the length of the linked list and M is the length of the
numsarray. Space Complexity: O(M), for storing thenumsin aset.
Code
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def remove_nodes(nums, head):
"""
Removes nodes from a linked list whose values are present in a given array.
Args:
nums: A list of integers.
head: The head of the linked list.
Returns:
The head of the modified linked list.
"""
nums_set = set(nums)
dummy_head = ListNode(0) # Dummy node to handle removal of the head
dummy_head.next = head
current = dummy_head
while current.next:
if current.next.val in nums_set:
current.next = current.next.next # Remove the node
else:
current = current.next # Move to the next node
return dummy_head.next # Return the new head of the list