Defuse the Bomb - Leetcode 1652 - Python

NeetCodeIO · Intermediate ·⚡ Algorithms & Data Structures ·1y ago

Key Takeaways

Solves Defuse the Bomb problem on Leetcode using Python

Full Transcript

hey everyone welcome back and let's write some more neat code today so today let's solve the problem diffuse the bomb the idea is we're given an input array of integers and we're given another parameter K and this example let's say it's three so K is the magic number for this problem if K is zero we're going to replace everything in this array with zero when they say replace they don't necessarily mean doing it in place with the array I'm pretty sure you actually have to create create a separate array so that's what we're going to do we're going to put the new values in a separate array so if K is zero we can just return all zeros and the length is the same as this so that's pretty straightforward the other two cases are a bit more interesting if K is a positive number we're going to do this for every number we're going to create a window of size K because we want to replace the I element with the next K elements so basically a window of size K in this case and get the sum of that window in this case 7 + 1 + 4 I think that's 12 and so we take 12 and then place it over here in the second array so we'll have a 12 over here and we'll keep going we want to do the same thing for this element so get the next three elements 1 2 now we ran out of elements there's nothing left so one tricky thing about this problem is this array is considered circular I'll show you a really nice trick to deal with circular arrays so what we actually want to do is get these two elements and then the next element which is technically out of bounds but what we would actually want is for that element to have been considered to be over here and so then we get the sum of all these that's 10 we put it over here and we can keep going just like this so we' do the same thing with this that'd be looks like 16 and for this one it would be 13 so that's if K is positive K can actually also be negative so what if we had K is equal to -3 well then for each element we want to do the opposite we want to get the previous K elements and again since the array is circular we'll go around here 1 2 3 and so once again we will get a 12 in the output over here for this element we'll do the previous three so essentially we're taking the absolute value of K and we're getting a window of that size so this sort of very Brute Force approach that I'm showing you clearly the time complexity is going to be o of n because we have to fill in every single value and to fill in a particular value we have to iterate let's say k times for that window and so this Brute Force solution is going to be n * K I think it's worth coding up this solution so I'll quickly do that but before I do let me show you that trick that I promised so the trick here is actually very simple once you know it it's going to make your life so much easier think of this we we get out of bounds sometimes right and those out of bounds indexes are going to be four five up until 6 let's assume that K is equal to 3 in this case or it could also be equal to -3 either way we're going to take K spots here because we might end up out of bounds like for example if we're here give me the next K if I'm here give me the next three if I'm here next three here next three Etc so that's why I'm only putting three elements here and the cool thing is you actually don't need to create more elements you don't actually need to create a bigger array you can do modding to like assume these positions kind of exist like implicitly exist so I'm going to draw them like in Gray but assume these elements are actually like let's say these first three we get five 7 and 1 so when we do our pointer stuff like let's say my ey pointer is over here and I want the next three elements I'll do a nested Loop to do that I'll have my J pointer iterate over this portion and it works when my ey pointer is here though if I have my J go through this portion I end up out of bounds but I wish that index 4 corresponded to the element five because that would make it circular and the way to do that is to take each pointer and mod it by the length of the array which let's say is n and n is four in this case when you do that if my JP pointer was over here at index 4 and I take it and I mod it by four I'm I'm going to get zero so that's going to tell me my JP pointer isn't actually at four it's actually at zero so if a pointer gets out of bounds it will automatically be corrected that's the advantage of this approach and it actually works uh going the other way as well if we were looking at the previous K elements because I'm going to do this I'm going to have let's say my window and I'm going to populate this guy great I'm going to have my window populate this guy which is actually populating index zero I'm going to have my window and I'm going to populate uh this guy which is actually populating this index now you have a bit of the intuition let me show you the code I'm going to create my result array I'm going to make it all zeros of the size of the input and I'm actually going to save that in a variable because I think we're going to need it a few times and next I'm going to go for I in range n for every position I want to populate this position for that I need to know if K is greater than zero we're going to do something else if K is less than zero we'll do it differently and if K is equal to Z we don't need to do anything we could actually have an if statement here if K is equal to zero just return the result and then we don't even need to handle it here this is kind of a small optimization it doesn't really make a big difference our code below will actually handle this case anyway so it's a little bit unnecessary but we will I guess iterate n times which is somewhat way wasteful but not a big deal anyways here if K is greater than zero we want the next K element so I'm going to say for J starting at I + 1 going up until I + 1 + K this plus K is kind of the offet here with python this is non-inclusive so that's why we still have that plus one and so for this we want to compute the sum of all of these elements and then replace result at index I with that value so we might as well just add the values to this position because it's initialized as zero anyway we can do something similar down here but we want to go in reverse order for J in range I -1 up until I -1 - K going in reverse order there's one little bug with this K could be negative in fact it is negative if this is executing it's positive if this is executing so the plus K is fine but us K should be minus the absolute value of K and honestly I think they could have done a better job in the problem description here where they say replace it with the sum of the previous K elements they could have said the absolute value of K but anyways and in here we'll do pretty much the same thing result of I add to it code of index J and then at the end we return the result now this looks pretty straightforward and that's because there's a small issue here I'm not doing the modding that I talked about my JP pointer could end up out of bounds it's definitely going to end up out of bounds in both of these cases so what should I do well we can just take it and mod it by n and same thing over here so that's the code let's run it and you can see that it works but this is not the most optimal solution I don't think you will pass in an interview with this solution but I guess it depends on the interviewer the company and a bunch of other factors now how do we go about optimizing this well once you know the trick and if you've heard of the pattern called sliding window it's not too difficult if you haven't heard of this pattern you can consider heading to n code iio if you go to the sliding window pattern there's a bunch of problems here and you can also check out the courses which will teach you these things like from scratch got videos practice problems code animations articles all that stuff but anyways back to the sliding window what is it it's pretty simple whether our K is positive or negative we want to take like the absolute value of K and get Windows of that size we already kind of know that much so the algorithm will work like this we have two pointers a left and right pointer initially we'll just start at the beginning and then keep summing up until our window is of size K and once this is of size K we will say if our K is positive we want to take like this window and say that the sum belongs to the previous element in other words we want the next K elements to fill in this element but what is this element it's out of bounds it's actually this element over there so the modding will actually handle this even if it's like a negative index at least uh that's true in Python it actually won't work as expected in other languages like if you have a negative number and you are modding that negative number if you're doing this in other languages the easy way to get around that is to make the number non- negative and to not change the mod since like I have some number X and I'm modding it by n if I add n to this value that's not going to change the mod obviously right if I say like I have 11 modded by five I'm going to get one as the remainder if I add five to 11 I get 16 modded by five and that doesn't change the remainder at all so that's what you can do to one of the indexes if it could potentially be negative but anyways uh this trick will work and so like with the sliding window approach we can do that so in this case with our window we want this window to be filling in the value for left minus one if K is positive if K was negative we'd be wanting this window to fill in r+ one meaning this position and we can just have a couple if statements to handle that and then we can shift our window the optimization comes from the fact that when we shift the window we will uh shift like our right pointer here adding this to the current sum and we will shift our left pointer over here removing this from the current sum so this current sum might populate this or it might populate the value ahead of it and if the value ahead of it is out of bounds that will be brought back into bounds with the mod that we are doing doing it this way our window will shift only one time each like potentially up until the end of the entire input plus K like this distance over here so time complexity is going to be linear let's code this up so I'll leave some of this boiler plate here so here I'm going to change this first Loop to n + K and I'm going to change this to R and I'm going to have a left variable which is zero and I'm going to have a current sum which I'll initialize to zero so what we're going to be doing here is every single time we want to add the current number to the current sum so code at index R now index R could be at of bounds so don't forget to do the modding there's a couple of cases we need to handle either our window is too big or it's exactly the right size and maybe even both of them so if the window is too big we can get the window like this right minus left + one that's the length is it greater than K because if this is the case we want to shift the left pointer if we shift the left pointer we have to make sure that we do the modding like this oh whoops that's not mod and with the current sum before we shift the left pointer let's let's take the value that was originally there and subtract it from the current sum so this and here again don't forget to do the modding there's actually a small bug here what if K was negative well we want to compare the length of the window to the absolute value of K in that case cuz they don't mention it in the problem description but that's what we want to do so that's if the window is too big we will correct it we don't have a loop here because our Windows starts at a size of zero so it'll never exceed the size of K by more than one and down here we will check if we're exactly the right size if right minus left + 1 is exactly uh what we want it to be which is going to be K the absolute value of K as we learned then we have two choices well two different cases to handle if K is greater than zero or otherwise if K is less than Zer well what if K is exactly equal to zero well in that case we don't really need to do anything we can just leave the array as and return it so that will work even though we could add an if statement up above so here if K is greater than zero we want to update the value in the result array at left minus one but again this could be out of bounds let's mod it by n and that will be set to the current sum and we'll do something similar down here except making it right + one there you go I think the hardest thing about this problem is probably just dealing with like the circular array Parts the fact that you have to Absol value K and if you're new to the sliding window I think this would probably be challenging as well especially if you're using non-python languages you'll have to like add a plus n here and maybe a few other places and whoops I realized that this plus K also should have had an absolute value around it kind of shows you how easy it is to mess up but now you can see that this code works it's pretty efficient if you found this helpful definitely check out n cod. for a lot more thanks for watching and I'll see you soon

Original Description

🚀 https://neetcode.io/ - 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/defuse-the-bomb/description/ 0:00 - Read the problem 0:30 - Drawing Explanation 5:06 - Coding Explanation 7:58 - Drawing Explanation 11:00 - Coding Explanation leetcode 1652 #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

Related AI Lessons

Bloom Filters, Explained Properly
Learn how Bloom filters work and their benefits, including tiny memory and blazing speed, in exchange for potential false positives.
Dev.to · Daksh Gargas
Prefix Sums: The Preprocessing Trick That Makes Range Queries Instant
Learn how prefix sums enable instant range queries in arrays, boosting performance in various applications
Medium · Programming
I Thought I Was Ready for the Interview — Then One Simple Math Question Destroyed Me
A simple math question can destroy a developer's interview, highlighting the importance of being prepared for unexpected questions
Medium · Programming
Week 2(Day 10): LeetCode Two Pointers(slow & fast): Remove Duplicates from Sorted Array (Brute…
Learn to remove duplicates from a sorted array using the two pointers technique, improving from brute force to optimized solutions
Medium · Python

Chapters (5)

Read the problem
0:30 Drawing Explanation
5:06 Coding Explanation
7:58 Drawing Explanation
11:00 Coding Explanation
Up next
Stump Grinder Carbide Wheel Grinds Hardwood To Chips
Innoforge Studio
Watch →