Shortest Bridge - Leetcode 934 - Python

  Рет қаралды 37,348

NeetCode

NeetCode

Күн бұрын

Пікірлер: 69
@vincentmarquez3096
@vincentmarquez3096 2 жыл бұрын
This is one of those "the algorithm is easy but lets see if you can write ~50 loc bug free in ten minutes" kind of tests.
@shoooozzzz
@shoooozzzz 7 ай бұрын
To be fair, I got a full 30 minutes to write all this in a Google Doc. Still wasn't enough time, lol
@mertkahyaoglu48
@mertkahyaoglu48 2 жыл бұрын
I was just trying to solve this and came here to check whether you uploaded a video for this. Surprised that you just uploaded man, thanks a lot!
@shoooozzzz
@shoooozzzz 2 жыл бұрын
This question is alive and well in FAANG interviews. Was just asked it and wish I would have known the BFS && DFS trick.
@sahilkulria7325
@sahilkulria7325 2 жыл бұрын
I love the the small python thingies you tell in-between, thanks for that also
@yukselpolatakbyk8468
@yukselpolatakbyk8468 2 жыл бұрын
I started watching you 6 months ago. Today I tried this by myself before checking your solution and I realized that I had the right idea just couldn't figure out minor bugs. If it wasn't for your videos I would have no idea how to even approach this. Thanks again!!
@xiomoen3943
@xiomoen3943 2 жыл бұрын
What a detailed explanation! You are a KZbinr who makes people feel like a treasure!Thank you sosososo much
@anarsalami9906
@anarsalami9906 4 ай бұрын
Great explanation, as always! When I search to look explanation of any of the coding problem, first I am trying to find if you have any video for that question before looking at different videos. Thanks a lot.
@cosmicgirl910
@cosmicgirl910 2 жыл бұрын
I had an interview today and legit almost cried bc I was so stuck and helpless. I studied leetcode but the question required me to implement a class, which you never have to do in leetcode. Could you solve problems where you would implement a class to solve the problem please? Thanks!
@cosmicgirl910
@cosmicgirl910 2 жыл бұрын
The question I got was from Dropbox - Permissions in a file system
@yang5843
@yang5843 2 жыл бұрын
Sorry to hear about your experience in your interview today.
@Eisae
@Eisae 2 жыл бұрын
That's unfortunate, sure you'll crush your next interview. Do you have a link to this or a similar question? Kinda interested in what exactly you had to do
@SmoothCode
@SmoothCode 2 жыл бұрын
We all be feeling dumb doing these interviews. It is as if we never coded in our life.
@vdyb745
@vdyb745 2 жыл бұрын
Neeeee(a)t explanation, visuals and code !! :) Fabulous ! Thank you.
@aloksahu1457
@aloksahu1457 2 жыл бұрын
As usual the best explanation . Thanks much for these videos. Any thoughts if there are n islands and we need to create a bridge connecting all of them in a shortest path ?
@b9944236
@b9944236 Жыл бұрын
When I understand the key point is DFS(a very basic island problem) + BFS (a very basic shortest path), then I can solve this problem by myself. Thanks a lot.
@vicnetc5964
@vicnetc5964 2 жыл бұрын
Would it be possible to go through every 1 in the first island and find its distance to the second island. For example, for the 1 at (1,0), we would find that its distance to the second island is 4. We can find this by first determining the coordinates of the second island (4,2), (4,3), and (4,4) and then using the equation x2-x1 + y2-y1. So we would have 4-1+2-0 = 5 as the smallest raw value, and then we subtract 1 to get 4 (because we only need to connect the islands). We could do this for every single point on the first island and find the minimum of the values to get the distance. I'm not sure if this would be more or less efficient than the approach you explained, but in the solution I described, you wouldn't need to look at any of the 0's in the array.
@ygwg6145
@ygwg6145 Жыл бұрын
Nice idea. It should be O(n^4).
@AnkitaNallana
@AnkitaNallana 2 ай бұрын
So, I'm familiar with dfs/bfs but for the newbs, i think an intuition as to why bfs with the visited set would've been good to provide. For me, it was easy to visualize how a visited set would help, but I think more explanation there would've been good!
@sidazhong2019
@sidazhong2019 10 ай бұрын
You can add a length value in the queue, something like q.append(r,c,length+1). Return the last length as the answer.
@halahmilksheikh
@halahmilksheikh 2 жыл бұрын
Man this is mechanically difficult. It's basically two questions in one, DFS feeding into a layered BFS. It's good practice though.
@remixowlz
@remixowlz 2 жыл бұрын
But what if I want to get the coordinates (row, col) connecting the two islands?
@Krblshna
@Krblshna Жыл бұрын
Finally it make sense how to solve this problem and why we do all of these things, thank you
@АлександрЯрулин-й7и
@АлександрЯрулин-й7и 2 жыл бұрын
Thanks. Comment: the more safe 'def invalid' will be r < 0 or c < 0 or r > N - 1 or c > N - 1 . Not r == N, c == N .
@curesnow6493
@curesnow6493 Жыл бұрын
Thank you so much for your solution. I have spent one hour stuck on this problem.
@pranavsharma7479
@pranavsharma7479 2 жыл бұрын
Voo thanks a lot bro, can you please cover , missing element in sorted array please
@MP-ny3ep
@MP-ny3ep Жыл бұрын
Beautifully explained . Thank you
@Shameer..
@Shameer.. 2 жыл бұрын
Think I found a small mistake, @ 4:26 Since it's 4-directionally connected, graph[3][2] should not be 1 so numbers in the bottom right 3x2 should all be +1. Didn't change the solution in this example tho.
@Shameer..
@Shameer.. 2 жыл бұрын
LOL never mind paused there to see if I was tripping and you recognized it soon after :) great video!
@sirmidor
@sirmidor 2 жыл бұрын
I enjoy how Neetcode continues to mangle 'Dijkstra' into 'Djikstra' in every video the algorithm comes up in so far, makes him seem human.
@vijethkashyap151
@vijethkashyap151 4 ай бұрын
Beautiful!
@tusharsharma7069
@tusharsharma7069 2 жыл бұрын
always love to learn from you
@pulkitk3388
@pulkitk3388 Жыл бұрын
awesome explanation man!!
@nakshayachaudhary
@nakshayachaudhary 10 ай бұрын
Here is what I used : I actually used DFS to find all cells of both islands, then whichever cell which has a single opening to water, I added it to an array.....This way I had 2 arrays containing boundary cells of both islands. Now to find no. of cells needed to connect any 2 cells is abs(r1-r2) + abs(c1-c2) -1, I just the found the minimum possible value for the expression and voila....you have the answer.....
@CommandantNOVA
@CommandantNOVA 2 жыл бұрын
On line 20, is the sole point of this loop just to keep res from being incremented early? Because i is not used anywhere else.
@pleasedontsubscribeme4397
@pleasedontsubscribeme4397 2 жыл бұрын
yeah, 'i' is used to traverse layer by layer, so that after first layer points are visited, res gets incremented by 1 and we move on to process the next layer of coordinates if queue is not empty, hence the while loop .
@ramankr0022
@ramankr0022 Жыл бұрын
very helpful!
@dr_drone
@dr_drone 2 жыл бұрын
you're a wizard king!
@cc-to2jn
@cc-to2jn 11 ай бұрын
intresting! I did it a very similer way but differ syntax style. Unlike you I looked for the initial starting edges for island 1 and then did the bfs. q=deque() visited=set() def findEdge(i,j): if (i
@pranavyeleti3499
@pranavyeleti3499 2 жыл бұрын
bro how long did it take to become good at data strucutres and algos
@pseudounknow5559
@pseudounknow5559 2 жыл бұрын
He is born like this
@alphabee8171
@alphabee8171 Жыл бұрын
@@pseudounknow5559 i promise you people spend lifetimes finding out one of these algorithms and some even didn't reach that point. They are born with determination for sure, practice and repeat is the only answer.
@baap6886
@baap6886 Жыл бұрын
it depends on practice but atleast 400-500 questions you need to solve to achieve a good level
@mohammedabdelkarym
@mohammedabdelkarym 2 жыл бұрын
Damn, what a question!
@fdk9913
@fdk9913 2 жыл бұрын
Hi neetcode great vid as always. Can you try solving the question: All Nodes Distance K in Binary Tree next thanks
@yukselpolatakbyk8468
@yukselpolatakbyk8468 2 жыл бұрын
Hi, Here is a solution I found 6 months ago. I hope it helps. It is easy once you understand the idea: class Solution: def distanceK(self, root: TreeNode, target: TreeNode, k: int) -> List[int]: #mark the parent of every node def dfs(node, par = None): if node: node.par = par dfs(node.left, node) dfs(node.right, node) dfs(root) queue = deque([(target, 0)]) #node, dist seen = {target} while queue: if queue[0][1] == k: #once we see one d ==2 it means everything else in q is also that level return [node.val for node, d in queue] node, d = queue.popleft() #add every neig of node with new level for nei in (node.left, node.right, node.par): if nei and nei not in seen: seen.add(nei) queue.append((nei, d+1)) return []
@fdk9913
@fdk9913 2 жыл бұрын
@@yukselpolatakbyk8468 hi thanks for that. I ended up searching that question and saw a similar code. I actually get it now. The thing that was bothering me was how was i meant to get the previous nodes, but a hash map makes so much sense.
@shensean1784
@shensean1784 2 жыл бұрын
Interesting, how do u add a par to the node, which only has left, right? I may convert it to graph instead
@allandogreat
@allandogreat 2 жыл бұрын
code is pretty neat
@linchuantian623
@linchuantian623 2 жыл бұрын
Hey I have a confusion about this question how do I guaranteed that the result will be the minimum path that connects the two island ??
@bryananananana
@bryananananana 2 жыл бұрын
We are using BFS to explore the water layer by layer, so the first land tile we encounter (not in visited) must be the shortest path from the other island
@allandogreat
@allandogreat 2 жыл бұрын
why you can use deque in leetcode without import it?
@rajastylez
@rajastylez 2 жыл бұрын
I am wondering, why not just use BFS over DFS to discover the island?
@def__init
@def__init Жыл бұрын
Neetcode finds it easier to implement DFS recursively in general, would be same complexity 👍 I also agree it’s easier than BFS
@calvinklein5223
@calvinklein5223 2 жыл бұрын
N = len(grid) only addresses the number of rows, shouldn't it be NR = len(grid) and NC = len(grid[0])?
@faithcyril513
@faithcyril513 Жыл бұрын
it's a square grid, it was stated in the problem
@cheeseborger3758
@cheeseborger3758 Жыл бұрын
I hate coding because I don’t like having to move my fingers on the keyboard to anything that isn’t just letters 😂
@valivetiswamynagasainivas6167
@valivetiswamynagasainivas6167 Жыл бұрын
What is the need of dfs in here could I not traverse the entire grid and push the values which are simply ones
@whitesaladchips
@whitesaladchips Жыл бұрын
no the ones can be from any island, so you can only traverse ones from one specific island
@ygwg6145
@ygwg6145 Жыл бұрын
Another way: O(n*k) by swelling island along the borderline.
@ChinmayAnaokar-xm4ci
@ChinmayAnaokar-xm4ci Жыл бұрын
C# Implemenation public class Solution { readonly int[][] directions = new int[][] { new int[] { 0, 1 }, new int[] { 0, -1 }, new int[] { 1, 0 }, new int[] { -1, 0 } }; HashSet visited = new HashSet(); public int ShortestBridge(int[][] grid) { Queue q = new Queue(); for (int i = 0; i < grid.Length; i++) { for (int j = 0; j < grid[0].Length; j++) { if (grid[i][j] == 1) { DFS(grid, i, j, q); return BFS(grid, q); } } } return -1; } private void DFS(int[][] grid, int row, int col, Queue q) { if (row < 0 || row >= grid.Length || col < 0 || col >= grid[0].Length || visited.Contains((row, col)) || grid[row][col] != 1) { return; } visited.Add((row,col)); q.Enqueue((row, col)); dfs(grid, row - 1, col, q); dfs(grid, row, col + 1, q); dfs(grid, row + 1, col, q); dfs(grid, row, col - 1, q); return; } private int BFS(int[][] grid, Queue q) { int res= 0; while (q.Any()) { int size = q.Count; while (size > 0) { var row_col = q.Dequeue(); foreach(int[] dir in directions) { int r = dir[0] + row_col.R; int c = dir[1] + row_col.C; if (r >= grid.Length || r < 0 || c >= grid[0].Length || c < 0 || visited.Contains((r, c))) { continue; } if (grid[r][c] == 1) { return level; } else { visited.Add((r, c)); q.Enqueue((r, c)); } } size--; } res+= 1; } return res; } }
@asheeshpathak1497
@asheeshpathak1497 2 жыл бұрын
Not in love with this question. Not much logic. Just procedures. Too big to solve in JAVA
@pseudounknow5559
@pseudounknow5559 2 жыл бұрын
Exactly !!!
@jamesmandla1192
@jamesmandla1192 Жыл бұрын
It's a pretty common question in FAANG interviews actually
@remixowlz
@remixowlz 2 жыл бұрын
NameError: name 'deque' is not defined
@spaceface2288
@spaceface2288 2 жыл бұрын
from collections import deque
@remixowlz
@remixowlz 2 жыл бұрын
@@spaceface2288 thabkew kind sir
Evaluate Division - Leetcode 399 - Python
17:37
NeetCodeIO
Рет қаралды 28 М.
Shortest Path with Alternating Colors - Leetcode 1129 - Python
13:43
SCHOOLBOY. Мама флексит 🫣👩🏻
00:41
⚡️КАН АНДРЕЙ⚡️
Рет қаралды 7 МЛН
Girl, dig gently, or it will leak out soon.#funny #cute #comedy
00:17
Funny daughter's daily life
Рет қаралды 8 МЛН
5 Useful F-String Tricks In Python
10:02
Indently
Рет қаралды 305 М.
6 Tips to write BETTER For Loops in Python
9:19
Patrick Loeber
Рет қаралды 248 М.
Shortest Path in a Binary Matrix - Leetcode 1091 - Python
12:34
NeetCodeIO
Рет қаралды 22 М.
Decode String - Leetcode 394 - Python
16:26
NeetCode
Рет қаралды 85 М.
I gave 127 interviews. Top 5 Algorithms they asked me.
8:36
Sahil & Sarra
Рет қаралды 650 М.
Push Dominoes - Leetcode 838 - Python
17:39
NeetCode
Рет қаралды 21 М.
Rotting Oranges - Leetcode 994 - Python
12:19
NeetCode
Рет қаралды 100 М.
Contiguous Array - Leetcode 525 - Python
15:41
NeetCodeIO
Рет қаралды 24 М.
3 Types of Algorithms Every Programmer Needs to Know
13:12
ForrestKnight
Рет қаралды 470 М.
SCHOOLBOY. Мама флексит 🫣👩🏻
00:41
⚡️КАН АНДРЕЙ⚡️
Рет қаралды 7 МЛН