Delete Nodes From Linked List Present in Array - Leetcode 3217 - Python

NeetCodeIO · Intermediate ·⚡ Algorithms & Data Structures ·8mo ago

Key Takeaways

The video solves the Leetcode problem 3217, deleting nodes from a linked list present in an array, using a hash set for efficient lookups and a dummy node to simplify the code. The solution is implemented in Python and has a time complexity of O(n + m) and a space complexity of O(n).

Full Transcript

Hey everyone, welcome back and let's write some more neat code today. So today, let's solve the problem delete nodes from linked list present in an array. So I'll keep this one nice and short. The idea is we're given a linked list that might look like this. We're also given an array of numbers. If any of these nodes has a value that exists within that array, we want to remove that node from the linked list. And so in this case, we would remove all three of these and then return the remaining linked list. It could be empty. I mean, it could technically be null. It could be non-mpy. And if it's non- empty, of course, we want to return the original nodes. We want to return the head of the remaining list. How do we go about solving this problem? Well, the first thing that you need to do is how do we do the lookup? How do we know if this value exists in there? We can do a linear scan. We can go through that entire thing either by looping over it or using a built-in function. But since it's an array, it's going to be linear time. Lookups though are quicker with hash data structures. Whether it's a hashmap or in this case a hash set is going to be sufficient. So that's exactly what we're going to do. The lookup in that case will go from O of N to constant time. So the algorithm is going to be this. Go through each node. If the value exists in the hash set, we will convert this into a hash set. then remove the node. Okay, so now you might be wondering how do we go about removing a node. Well, the first thing I want to tell you is that there is a trick with link list problems. You almost always want to have a dummy node when you're modifying a linked list. It makes the code just a little bit easier. Let me show you what I mean. Like this example here, if we were updating this linked list, we'd say that, okay, well, right now we have a pointer. This is the head of the linked list, and we are now trying to delete it. Okay, so since this is the head, we should probably change the head pointer to now be at the next node. But if we were removing a node from the middle, suppose this one down here, like this is our head right now. We're not removing the head. We're removing the node after the head. So in that case, we just want to take this pointer and then shift it over there. So we can remove the difference between both of these by doing something called a dummy node. The edge case comes from the fact that we could remove from the beginning of the list. So let's just create a random node. Doesn't really matter what the value is. I'll say it's zero. And let's set the next pointer to the head of the existing link list. Now, we're going to do the exact same thing as before. This is a one, so let's remove it. How do we do that? Well, one possible way is to use two pointers. Keep track of the previous node and keep track of the current node. And if the current node is something we want to delete, then take the previous next pointer and set it to current.next. That's pretty much going to remove it. And then in this particular case, the previous pointer should stay here. It should not be shifted. Our current pointer should only be shifted here. Because if we shift both of the pointers, if we put the previous pointer over here and the current pointer over here, we're going to consider removing this one. We're going to check, okay, is this a value we want to remove? And then we'll end up removing it. But we ended up skipping this guy. So that's why you don't want to shift the previous pointer if you deleted the node. Okay, but what if we don't delete the node? Suppose we weren't deleting this one. Well, then we would shift both of the pointers. Then we would shift previous by one and we would shift current by one. And then, you know, do the same thing here. So, that's more or less how you go about solving the problem. I think we're actually ready to code this up very quickly. Let's go over the time and space. We're given two inputs. The size of them is not necessarily going to be the same. Let's say this is n. Let's say this is m. So, overall the time complexity, we're going to convert this into a hash and we're going to iterate over the entire link list. That's going to be n plus m space. We are using a data structure. the hash set, remember? So that's going to be bigo of N. Now, let's code it up. So the first thing I'm going to do is just take nums and convert it into a hash set. I'm able to do this in Python because there's no like static typing. You might not be able to do that in your own language. You might have to create a new variable name. Um, but now let's do the dummy node. Let's create a random node. And let's give it a value of zero. It doesn't really matter what value we give it. Let's set the next pointer though to the head of the given linked list here. And now let's basically do that two-pointer thing I was talking about having the previous pointer set to uh the dummy node initially and then the current pointer set to the head or we could say dummy.ext but it doesn't really matter. They're both the same. And now we say while current because current is the node that we're considering to delete. And so we're going to check if the current.val is in the nums hash set then we want to delete it. And that's very easy to do. We just say previous.n next is equal to current.n next. And remember in this case we don't shift the previous pointer. We don't want to do that. We don't want to skip a node. We only shift the current pointer. So say current is now going to be current.ext. Now the alternative is where we don't delete the node. In that case it's pretty simple. We just shift both of the pointers. So previous will be previous next. Current will be current.ext. You might notice that there is a duplicate line in both of these conditions. It doesn't really matter in a real interview. I personally wouldn't care that much, but it does make the code a little bit better. So, I'm going to go ahead and move this line out of the if statement and then delete this one. Lastly, at the end, we are going to return dummy.next. If we ended up deleting every single node in the linked list, what would dummy do.next point to? It would probably point to null. If we didn't delete every single node, it's going to point to the new head of the linked list. because even though we're deleting nodes, we're never changing the order of them. So this is the whole solution. Let's run it. As you can see, it works. It's pretty efficient. You can actually solve this problem without keeping track of two pointers. You can get away with just using one pointer. So let's do that. I guess I'll leave it as previous. And then instead of current, I'm going to say previous.n next because we know that current was always one ahead of previous anyway. For current here, I'm going to change that again to previous.next. And to current here, I'm also going to change it to previous.next. So now this is just, you know, being shifted by one. Here I'm going to change this to previous next. And same thing here. Actually, I think I'm going a little bit too much on autopilot because we don't need to shift all of these. So let me delete this line and just reread what we're doing here. So if the next node is one that we want to delete, let's delete it. Otherwise, just shift the pointer. I think that's actually enough. I don't think we actually need anything else since we only have one pointer anyway. And let me go ahead and run this. And you can see this one works as well. I don't think it's necessarily more efficient to be honest. Um, but the runtime says so. But if you found this helpful, check out necode.io for a lot more. I'm going to be launching a free newsletter pretty soon. It's going to be covering data structures, system design, and a lot more. I'll also be making a lot more system design videos pretty soon. I'm really excited about that. So subscribe if you want to see

Original Description

🚀 https://neetcode.io/yt - A better way to prepare for Coding Interviews 🧑‍💼 LinkedIn: https://www.linkedin.com/in/navdeep-singh-3aaa14161/ 🐦 Twitter: https://twitter.com/neetcode1 ⭐ BLIND-75 PLAYLIST: https://www.youtube.com/watch?v=KLlXCFG5TnA&list=PLot-Xpze53ldVwtstag2TL4HQhAnC8ATf Problem Link: https://leetcode.com/problems/delete-nodes-from-linked-list-present-in-array/description/ 0:00 - Read the problem 0:30 - Drawing Explanation 3:42 - Coding Explanation leetcode 3217 #neetcode #leetcode #python
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from NeetCodeIO · NeetCodeIO · 0 of 60

← Previous Next →
1 Leetcode 149 - Maximum Points on a Line - Python
Leetcode 149 - Maximum Points on a Line - Python
NeetCodeIO
2 Design Linked List - Leetcode 707 - Python
Design Linked List - Leetcode 707 - Python
NeetCodeIO
3 Minimum Time to Collect All Apples in a Tree - Leetcode 1443 - Python
Minimum Time to Collect All Apples in a Tree - Leetcode 1443 - Python
NeetCodeIO
4 Design Browser History - Leetcode 1472 - Python
Design Browser History - Leetcode 1472 - Python
NeetCodeIO
5 Number of Good Paths - Leetcode 2421 - Python
Number of Good Paths - Leetcode 2421 - Python
NeetCodeIO
6 Flip String to Monotone Increasing - Leetcode 926 - Python
Flip String to Monotone Increasing - Leetcode 926 - Python
NeetCodeIO
7 Maximum Sum Circular Subarray - Leetcode 918 - Python
Maximum Sum Circular Subarray - Leetcode 918 - Python
NeetCodeIO
8 Find Closest Node to Given Two Nodes - Leetcode 2359 - Python
Find Closest Node to Given Two Nodes - Leetcode 2359 - Python
NeetCodeIO
9 Concatenated Words - Leetcode 472 - Python
Concatenated Words - Leetcode 472 - Python
NeetCodeIO
10 Data Stream as Disjoint Intervals - Leetcode 352 - Python
Data Stream as Disjoint Intervals - Leetcode 352 - Python
NeetCodeIO
11 LFU Cache - Leetcode 460 - Python
LFU Cache - Leetcode 460 - Python
NeetCodeIO
12 N-th Tribonacci Number - Leetcode 1137
N-th Tribonacci Number - Leetcode 1137
NeetCodeIO
13 Best Team with no Conflicts - Leetcode 1626 - Python
Best Team with no Conflicts - Leetcode 1626 - Python
NeetCodeIO
14 Greatest Common Divisor of Strings - Leetcode 1071 - Python
Greatest Common Divisor of Strings - Leetcode 1071 - Python
NeetCodeIO
15 Shortest Path in a Binary Matrix - Leetcode 1091 - Python
Shortest Path in a Binary Matrix - Leetcode 1091 - Python
NeetCodeIO
16 Insert into a Binary Search Tree - Leetcode 701 - Python
Insert into a Binary Search Tree - Leetcode 701 - Python
NeetCodeIO
17 Delete Node in a BST - Leetcode 450 - Python
Delete Node in a BST - Leetcode 450 - Python
NeetCodeIO
18 Shuffle the Array (Constant Space) - Leetcode 1470 - Python
Shuffle the Array (Constant Space) - Leetcode 1470 - Python
NeetCodeIO
19 Fruits into Basket - Leetcode 904 - Python
Fruits into Basket - Leetcode 904 - Python
NeetCodeIO
20 Number of Subarrays of size K and Average Greater than or Equal to Threshold - Leetcode 1343 Python
Number of Subarrays of size K and Average Greater than or Equal to Threshold - Leetcode 1343 Python
NeetCodeIO
21 Naming a Company - Leetcode 2306 - Python
Naming a Company - Leetcode 2306 - Python
NeetCodeIO
22 As Far from Land as Possible - Leetcode 1162 - Python
As Far from Land as Possible - Leetcode 1162 - Python
NeetCodeIO
23 Shortest Path with Alternating Colors - Leetcode 1129 - Python
Shortest Path with Alternating Colors - Leetcode 1129 - Python
NeetCodeIO
24 Minimum Fuel Cost to Report to the Capital - Leetcode 2477 - Python
Minimum Fuel Cost to Report to the Capital - Leetcode 2477 - Python
NeetCodeIO
25 Count Odd Numbers in an Interval Range - Leetcode 1523 - Python
Count Odd Numbers in an Interval Range - Leetcode 1523 - Python
NeetCodeIO
26 Contains Duplicate II - Leetcode 219 - Python
Contains Duplicate II - Leetcode 219 - Python
NeetCodeIO
27 Path with Maximum Probability - Leetcode 1514 - Python
Path with Maximum Probability - Leetcode 1514 - Python
NeetCodeIO
28 Add to Array-Form of Integer - Leetcode 989 - Python
Add to Array-Form of Integer - Leetcode 989 - Python
NeetCodeIO
29 Unique Paths II - Leetcode 63 - Python
Unique Paths II - Leetcode 63 - Python
NeetCodeIO
30 Minimum Distance between BST Nodes - Leetcode 783 - Python
Minimum Distance between BST Nodes - Leetcode 783 - Python
NeetCodeIO
31 Design Hashmap - Leetcode 706 - Python
Design Hashmap - Leetcode 706 - Python
NeetCodeIO
32 Range Sum Query Immutable - Leetcode 303 - Python
Range Sum Query Immutable - Leetcode 303 - Python
NeetCodeIO
33 Binary Tree Zigzag Level Order Traversal - Leetcode 103 - Python
Binary Tree Zigzag Level Order Traversal - Leetcode 103 - Python
NeetCodeIO
34 Middle of the Linked List - Leetcode 876 - Python
Middle of the Linked List - Leetcode 876 - Python
NeetCodeIO
35 Course Schedule IV - Leetcode 1462 - Python
Course Schedule IV - Leetcode 1462 - Python
NeetCodeIO
36 Single Element in a Sorted Array - Leetcode 540 - Python
Single Element in a Sorted Array - Leetcode 540 - Python
NeetCodeIO
37 Capacity to Ship Packages - Leetcode 1011 - Python
Capacity to Ship Packages - Leetcode 1011 - Python
NeetCodeIO
38 IPO - Leetcode 502 - Python
IPO - Leetcode 502 - Python
NeetCodeIO
39 Minimize Deviation in Array - Leetcode 1675 - Python
Minimize Deviation in Array - Leetcode 1675 - Python
NeetCodeIO
40 Longest Turbulent Array - Leetcode 978 - Python
Longest Turbulent Array - Leetcode 978 - Python
NeetCodeIO
41 Last Stone Weight II - Leetcode 1049 - Python
Last Stone Weight II - Leetcode 1049 - Python
NeetCodeIO
42 Construct Quad Tree - Leetcode 427 - Python
Construct Quad Tree - Leetcode 427 - Python
NeetCodeIO
43 Find Duplicate Subtrees - Leetcode 652 - Python
Find Duplicate Subtrees - Leetcode 652 - Python
NeetCodeIO
44 Sort an Array - Leetcode 912 - Python
Sort an Array - Leetcode 912 - Python
NeetCodeIO
45 Ones and Zeroes - Leetcode 474 - Python
Ones and Zeroes - Leetcode 474 - Python
NeetCodeIO
46 Remove Duplicates from Sorted Array II - Leetcode 80 - Python
Remove Duplicates from Sorted Array II - Leetcode 80 - Python
NeetCodeIO
47 Maximum Twin Sum of a Linked List - Leetcode 2130 - Python
Maximum Twin Sum of a Linked List - Leetcode 2130 - Python
NeetCodeIO
48 Concatenation of Array - Leetcode 1929 - Python
Concatenation of Array - Leetcode 1929 - Python
NeetCodeIO
49 Symmetric Tree - Leetcode 101 - Python
Symmetric Tree - Leetcode 101 - Python
NeetCodeIO
50 Check Completeness of a Binary Tree - Leetcode 958 - Python
Check Completeness of a Binary Tree - Leetcode 958 - Python
NeetCodeIO
51 Construct Binary Tree from Inorder and Postorder Traversal - Leetcode 106 - Python
Construct Binary Tree from Inorder and Postorder Traversal - Leetcode 106 - Python
NeetCodeIO
52 Find Peak Element - Leetcode 162 - Python
Find Peak Element - Leetcode 162 - Python
NeetCodeIO
53 Accounts Merge - Leetcode 721 - Python
Accounts Merge - Leetcode 721 - Python
NeetCodeIO
54 Binary Tree Preorder Traversal (Iterative) - Leetcode 144 - Python
Binary Tree Preorder Traversal (Iterative) - Leetcode 144 - Python
NeetCodeIO
55 Binary Tree Postorder Traversal (Iterative) - Leetcode 145 - Python
Binary Tree Postorder Traversal (Iterative) - Leetcode 145 - Python
NeetCodeIO
56 Number of Zero-Filled Subarrays - Leetcode 2348 - Python
Number of Zero-Filled Subarrays - Leetcode 2348 - Python
NeetCodeIO
57 Minimum Score of a Path Between Two Cities - Leetcode 2492 - Python
Minimum Score of a Path Between Two Cities - Leetcode 2492 - Python
NeetCodeIO
58 Sqrt(x) - Leetcode 69 - Python
Sqrt(x) - Leetcode 69 - Python
NeetCodeIO
59 Successful Pairs of Spells and Potions - Leetcode 2300 - Python
Successful Pairs of Spells and Potions - Leetcode 2300 - Python
NeetCodeIO
60 Optimal Partition of String - Leetcode 2405 - Python
Optimal Partition of String - Leetcode 2405 - Python
NeetCodeIO

The video teaches how to solve the Leetcode problem 3217 by using a hash set and a dummy node to delete nodes from a linked list. The solution is implemented in Python and has a time complexity of O(n + m) and a space complexity of O(n).

Key Takeaways
  1. Create a hash set from the given array
  2. Initialize a dummy node and set its next pointer to the head of the linked list
  3. Use two pointers (previous and current) to iterate through the linked list and delete nodes that are present in the hash set
  4. Shift the previous pointer only when a node is deleted
  5. Return the next pointer of the dummy node as the new head of the linked list
💡 Using a hash set for efficient lookups and a dummy node to simplify the code can make the solution more efficient and easier to implement.

Related Reads

📰
KMP Algorithm (Knuth-Morris-Pratt): The Smart Way to Perform String Matching in O(N)
Learn the KMP algorithm for efficient string matching in O(N) time complexity and improve your coding skills
Dev.to · Jaspreet singh
📰
Every Backtracking Problem Is the Same Three Lines. I Just Couldn't See the Tree.
Master backtracking problems with a simple three-line approach to improve problem-solving skills in coding interviews and challenges
Dev.to · Alex Mateo
📰
DSA From Zero to Hero #3: Sliding Window (Fixed Size) Explained With a Java Example
Learn to solve subarray problems efficiently using the sliding window technique, a crucial skill for software engineers and data scientists
Medium · Programming
📰
Two Pointers & Sliding Window: Turn O(n²) Into O(n)
Learn to optimize algorithms from O(n²) to O(n) using Two Pointers and Sliding Window techniques
Medium · Programming

Chapters (3)

Read the problem
0:30 Drawing Explanation
3:42 Coding Explanation
Up next
Stump Grinder Carbide Wheel Grinds Hardwood To Chips
Innoforge Studio
Watch →