Change language

Leetcode Visualized: Number of Islands – Typescript – LC200

Leetcode Visualized: Number of Islands - Typescript - LC200

imagine youre looking at the ocean from above theres a 2d grid in the grid there can either be water represented by zero or land represented by one islands can be made up of land tiles or vertically but not diagonally given a 2d array of ones and zeros write a function to return the number of islands number of islands aka elite code number 200 or lc200 is a deceptively simple sounding medium difficulty technique progression with lots of potential pitfalls hidden just beneath the surface lc200 has been frequently used interview candidates at amazon microsoft facebook google and more whether you believe whiteboard style interviews are right or wrong they are the reality at most tech companies today big or small in this video well visualize both the problem description and an effective solution in typescript as well as discuss some of the numerous pitfalls that can come up during your interview so that you can best prepare lets get started lets set up a grid so the top left row column is zero zero like so a helpful strategy is to handle the edge cases or boundary conditions so you dont forget about them later for example what happens if you receive a null or empty input oh we should probably just return zero islands great what about initial conditions we have an islands counter that should start at zero thats pretty much it great okay so were gonna have to loop over this 2d array what if it is non-empty and we land on a zero do we really care we dont need to track zeros or count them at all so we can pretty much skip them and do nothing move on the next square so if we grid full of zeros we can just loop over it return our initial islands counter call it a day great now onto the important bits what happens if we land on a one so how do we know if this tile of land is part of a larger island after we mark this square as visited lets say by setting the value from one to zero we just pick a direction lets say right and check its neighbor tile to see if it is also land if it is theyre part of the same island then for that neighbor after we mark it as visited we can continue right until we reach an end condition like water or the edge of the grid after hitting the end condition we can backtrack one step check the next direction down and if land we go right again to the end backtrack backtrack do this over and over until we visit every connected tile of land in the current island from your starting position then it is a matter of looping over the entire grid skipping the visited tiles or water and counting to the times we find isolated unvisited land tiles this approach is called depth first search or dfs were going as deep as we can before backtracking and moving on dfs is a graph traversal algorithm which makes this a problem a graph traverse a problem code wise dfs is short and easy to write and therefore remember if this is your first time encountering this type of problem please take a moment to try your hand at analyzing the time and space complexity of this solution and writing code for this from the pseudocode it helps check if you understand the solution as well as you think you do makes for excellent practice and will help you remember via engagement in action if youd like to do that please pause now ill wait okay so by now youve given it a try or not youre ready to see someone elses search youre looping through the entire grid which will be of size rows times columns this time complexity will therefore be o m times n where m is rows and its columns whatever you want in practice however the algorithm may repeat squares one additional time like checking a tile dfs already visited which in the worst case makes it o 2 times n times n which is still of m times n for space complexity this is a recursive algorithm with no additional data structures so the space is determined mostly by how many recursive stack calls are made if the entire grid is all land after that first tile you just keep calling dfs for every other tile and increase the stack until it hits o m times n space so worst case scenario it is o m times n in space complexity if the entire grid is water itll never run dfs so the best case scenario is a one space for the code as mentioned i like to start with the base case so if theres no grid its empty its null return zero next ill do the loop but to do that we need to first define the data structures in javascript and typescript 2d arrays are typically implemented as nested arrays hence the type definition the inputs from the lead code website are received as an array of rows so the first array is actually the column aka the y-axis which may be a little confusing so if you receive this question in a real interview double check with your interviewers to avoid confusion while communicating now we can actually add in the loop because we only care about the one case we need an if condition in that condition we run the dfs and increment the counter to be fair you could do either of these two lines in any order counter first dfs doesnt matter and now well implement the dfs what about the base case if the visit to tile zero return [Music] otherwise set it to zero because we visited it [Music] check its not absolutely necessary since were already calling it with the tao valley being one but just to be safe so now we want to go lets sew right first so if the row is less than grid a length one we havent hit the edge to the right yet and we can just call islands dfs again increment row leave column the same lets go down if a column is less than grid row thats one we want to do row and then we want to increment the column by one so thats going down lets go left so if row grows greater than zero and grid [Music] zero [Music] and that should be it lets test it out [Music] success okay that was easy except some pitfalls you might encounter in the real world solutions to these pitfalls are left as an exercise for you to think about but if you leave a comment about what youd like to see visualized pitfall number one the downsides of recursion as of 2022 most modern javascript runtimes do not fully support tail call optimization this means that every recursive call you add will keep stacking memory and using up your finite resources most modern browsers will limit this to about a hundred thousand calls and throw errors if you exceed it so if your grid size will exceed the limit for your runtime and platform you may want to consider using an iterative approach instead it fall number two only knowing one approach recognizing that this problem is a graph traversal problem which can be solved with dfs is an important skill to practice but dfs is not the only way to solve this problem and interviewers may also want to test whether you know how to go about the other approaches so it helps to be prepared to handle converting recursive to iterative and vice versa another approach to the problem is with breadth first search or bfs instead instead of going right all the way to the end and so on you go one step in each direction before going to the neighbor and repeating it fall three immutability in my solution i modified the original grid input your interviewer may require you to keep the original input intact how would you go about modifying the code to support this give it a try its a good grasp of how to go about solving a number of islands you should be able to adapt to any graph traversal problem without having to memorize every lead code problem and solution ever made thats it for this video if youd like to see more visualizations please put a topic or problem request in the comments like and subscribe otherwise good luck for the sunrise [Music] you [Music]