Number of Islands

Поділитися
Вставка
  • Опубліковано 29 вер 2024
  • For business inquiries email partnerships@k2.codes One of Google's most commonly asked interview questions according to LeetCode.
    Google Coding Interviews Number of Islands (LeetCode) and explanation.
    This interview question is from LeetCode and commonly asked by the following companies: Google, Facebook, Amazon, Lyft, Uber, LinkedIn, Apple, Bloomberg, Microsoft, Alibaba, and more.
    Problem description: Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
    Example 1:
    Input:
    11110
    11010
    11000
    00000
    Output: 1
    Example 2:
    Input:
    11000
    11000
    00100
    00011
    Output: 3
    Support me on Patreon: / kevinnaughtonjr
    Follow me on GitHub: github.com/kdn251
    Follow me on Instagram: / programeme
    My Desk Setup
    Desk - bit.ly/3jfY195
    Chair - amzn.to/2O9TM3r
    Monitor - amzn.to/3rcSHGa
    Webcam - amzn.to/2NUmwgi
    Desktop - amzn.to/3tiySPL
    Laptops - amzn.to/3aRoN3Z
    iPad - amzn.to/2LlJzzJ
    Keyboard - amzn.to/3jfbxdd
    Mouse - amzn.to/36ElWtT
    Wrist Rest - amzn.to/3trrHF4 (pls don't buy this)
    Mouse Pad - amzn.to/2Myz2lt
    Microphone - amzn.to/3atNyTA
    Lamp - amzn.to/3jjfZYp
    Headphones - amzn.to/3tvr0KU (new model)
    Headphone Hook - amzn.to/3tr8uTC
    Blue Light Glasses - amzn.to/3cDVUdK
    Wireless Charger - amzn.to/39LY1uu
    Keyboard cable - amzn.to/2O5p2R5
    Mic arm - amzn.to/3cECZj8
    Audio interface - amzn.to/36HdWIi
    Cloudlifter - amzn.to/36VO6kf
    Laptop dock - amzn.to/2O2DsBw
    Motherboard - amzn.to/3rkiWuA
    Solid state - amzn.to/3rk5vuo
    CPU cooler - amzn.to/3tnwwPA
    CableMod - amzn.to/3tqbtM8
    CPU - amzn.to/3auG1ns
    Power supply - amzn.to/3trsAxo
    RAM - amzn.to/39JZcuf
    Designing Data-Intensive Applications - amzn.to/2YK4ek1
    Clean Code - amzn.to/3txqfB5
    Meditations - amzn.to/3cDa4fi Discord: bit.ly/K2-discord

КОМЕНТАРІ • 331

  • @KevinNaughtonJr
    @KevinNaughtonJr  4 роки тому +25

    If you found this video helpful be sure to check out the interviewing service I made! thedailybyte.dev/?ref=kevin

  • @harshalpatil5523
    @harshalpatil5523 4 роки тому +111

    Bro you are a legend .. you are a natural in making ppl understand stuff .. great work keep going

    • @KevinNaughtonJr
      @KevinNaughtonJr  4 роки тому +9

      Harshal Patil thanks Harshal I really appreciate that thanks so much for your support!

    • @zainabalhaidary
      @zainabalhaidary 4 роки тому +1

      Right? He deserves wayyyy more subscribers

  • @faithfultrader6340
    @faithfultrader6340 2 роки тому +1

    I love your work man, how you break down complicated problems into very simple terms, keep up the great work!

  • @gabrielabdul
    @gabrielabdul 2 роки тому

    I've been following you on LinkedIn for a while -- you, amongst others, are inspiring me to work harder than ever (and be happy doing so) to achieve something I never considered to be in the realm of my possibility. My google interview may be sometime in September (pending interview slowdown status). Thank you for your insight and perspective!

  • @billnaris7735
    @billnaris7735 5 років тому +2

    Dude you explain everything so clear. please don't stop making vids.

  • @AbhishekKumar-oz6oo
    @AbhishekKumar-oz6oo 4 роки тому +2

    I really like the solution and the way you went through the thinking of it. Keep posting it and Big Thank you Bro.

  • @iiju8212
    @iiju8212 4 роки тому

    You make the questions look so easy ! Gem of a person you are!

  • @chiragkedia708
    @chiragkedia708 5 років тому

    Hi Kevin .thank you very much ...your videos are real saviour ...can you please make a video on how to
    1> think the recursive solution
    2> decide the base case
    3> your general approach to break down any problem into a recursive solution
    like... almost everything about recursion
    thanks

  • @sarmadsiddiqui1630
    @sarmadsiddiqui1630 4 роки тому

    Awesome solve but you your recursion can simply return a void and you can just keep a count of how many islands you have had to sink in your main loop.

  • @yolopassion
    @yolopassion 4 роки тому

    I am going to follow your playlist as you are the only youtube here who is so fluent and clear with his coding skills. I wish I could solve problems like you one day.What is the secret ingredient ??

    • @KevinNaughtonJr
      @KevinNaughtonJr  4 роки тому

      SANKALP TYAGI thanks and just practice!

    • @yolopassion
      @yolopassion 4 роки тому

      @@KevinNaughtonJr Seriously I am not able to think as you do. I recently got kicked off the Facebook interview. Some problems are so damn hard that I feel like quitting now. Sometimes I think its not even my cup of tea as I flunk at it always :(

  • @tgiflying
    @tgiflying 2 роки тому

    You don't have to return anything from the DFS. If you call it from a '1' location you are guaranteed an island.

  • @sukhmeetsc
    @sukhmeetsc 4 роки тому

    nice video.. dfs doesn't need to return a number and could just be used to clear up the island.

  • @sju9227
    @sju9227 5 років тому +2

    Immutability should be preferred, this might be considered really bad by some interviewers as changing grid content is something not good.

    • @CarlosRomero-ef4uv
      @CarlosRomero-ef4uv 5 років тому

      then you can have memory tradeoff. Dont modify original.. make a copy. you have to have some way to keep track of where you have been.

  • @haria8779
    @haria8779 4 роки тому

    Oh man! you made me feel it as an easy problem, which I originally felt very very hard. Thanks a buddy!

  • @avadheshsingh4255
    @avadheshsingh4255 3 роки тому

    Great explanation kevin thanks a lot

  • @shambog
    @shambog 4 роки тому

    Excellent explanation, a video on recursion would be wonderful.

  • @sanskaarpatni9137
    @sanskaarpatni9137 4 роки тому +1

    Kevin helpp! Which was the question you solved which added a string index : count or something into a hashset
    For Memoization

  • @1sankey2
    @1sankey2 3 роки тому

    very easily u explained thank you

  • @theducksneezes4987
    @theducksneezes4987 4 роки тому

    Wait, why didn't you make the grid global? How can the dfs() method access the grid and mark it 0 if grid is only local to the numIslands() method?

  • @indiansoftwareengineer4899
    @indiansoftwareengineer4899 5 років тому +1

    Where can I start?
    Could you please give serial number to video, eg. Problem no 200?
    So that I can start from beginning.
    Seriously man, I want to get hands on competitive coding and you seems to be helpful, where can I start to watch?

    • @ZenNoah
      @ZenNoah 5 років тому

      I don't think he does them in order. He just does problems commonly asked by big N companies.

  • @BRBallin1
    @BRBallin1 4 роки тому

    God dammit. This is one of those problems that are very simple once you see the solution.

  • @90krishika
    @90krishika 4 роки тому

    Hi Kevin, Sorry for posting out of topic question. In BFS why do we have to define the 2d Dirs like below:
    int[][] dirs = {{-1,0},{1,0},{0,1},{0,-1}};
    When getting the new cell coordinates. Any idea please?
    generic code below:
    while(!queue.isEmpty()) {
    int size = queue.size();
    for(int i = 0; i < size; i++) {
    int[] cur = queue.poll();
    for(int[] dir : dirs) {
    int nx = dir[0] + cur[0];
    int ny = dir[1] + cur[1];

    if(inValidArea(nx, ny) && res[nx][ny] > length){
    res[nx][ny] = length;
    queue.offer(new int[] {nx, ny});
    }
    }
    }
    length++;
    }

    • @KevinNaughtonJr
      @KevinNaughtonJr  4 роки тому +1

      Nilanjan Chowdhury doing so makes sure you traverse the 4 adjacent cells to the cell you’re currently on (so {0, 1} simulates moving right one cell, {1, 0} simulates moving down one cell, etc)

    • @90krishika
      @90krishika 4 роки тому

      @@KevinNaughtonJr Thank you.That makes sense. Is it same as I mentioned earlier?
      int[] xDirs = new int[] {0,0,1, -1};
      int[] yDirs = new int[] {1,-1, 0, 0};

  • @kooljay999
    @kooljay999 3 роки тому

    Time complexity = space complexity = O(M*N)

  • @saikiranreddy7889
    @saikiranreddy7889 4 роки тому

    Nice solution!!!Is it not necessary to catch the returning value from the function,like when we call dfs(grid,i+1,j) something will be returned, right?

    • @suyashisinghal7175
      @suyashisinghal7175 3 роки тому

      It doesn't matter what we are returning from the dfs function to get to the answer. We just need to return from the function when the base cases are satisfied. Instead of returning an int, 'void' and 'return' could be used as well!

  • @Naveen-xz6ml
    @Naveen-xz6ml 5 років тому

    you are a legend bro

  • @salonidoshi154
    @salonidoshi154 3 роки тому

    CAN I GET UR FULL CODE ,FOE SOME WEIRD REASON SAME CODE I WROTE BUT ISNT WORKING

  • @ptk1
    @ptk1 4 роки тому

    What's the runtime complexity for the solution?

    • @luisady8990
      @luisady8990 3 роки тому

      // TIme complexity O(N*M) - N number of rows, M - number of columns
      // Why? In the worst case we would have grid with ones. We would go through each cell using recursion on the
      // first step of the loop. Then we will do constant operation for other steps of the loop, so O(N*M + N*M)
      // Space O(N*M) - deepness of recursion
      From Github: github.com/chopdev/leetcode_tasks/blob/0df3657e8f02f53f81f7c6e48d7eb17e27857271/union_find/200_union_find/Solution.java

  • @chinmaykhobre6034
    @chinmaykhobre6034 5 років тому

    what if they want to add diagonal 1 also, i.e in 2nd eg o/p will be 1 like that

  • @mridulmittal5953
    @mridulmittal5953 5 років тому +1

    standard flood fill algo!

  • @nicolasvargas5835
    @nicolasvargas5835 5 років тому

    Does anyone have good suggestions for similar questions on Leetcode?

  • @sakhori05
    @sakhori05 4 роки тому

    Why is it returning 4 instead of 3?
    public static int numIslands(char[][] grid) {
    if(grid==null || grid.length==0) {
    return 0;
    }
    int numIslands =0;
    for(int i =0; i

  • @rryann088
    @rryann088 Рік тому

    sweet

  • @Marco-sj5lg
    @Marco-sj5lg 5 років тому +83

    I love your videos seriously. If possible, I hope to see more DFS, BFS, or shortest path related questions as well.
    Keep up the great work, buddy!

    • @KevinNaughtonJr
      @KevinNaughtonJr  5 років тому +6

      Thank you so much I really appreciate it! Thanks for the suggestions, I'll see what I can do!

  • @darod6098
    @darod6098 4 роки тому +89

    Thank you for covering this problem, it's pretty important.
    By the way, it is absolutely not necessary to return an integer from the dfs, actually an interviewer can ask you why are you doing that.
    dfs can be void and just increment after calling it in the main function, because you already know that you have one island (grid[i][j] == '1') and you can't have more than one in that recursive calls, because if it find more one they belong to the same island.
    Another follow-up question that can be done in an interview is "What if you cannot modify the matrix?" In that case, an option would be creating a boolean[][] of seen/visited, which takes space but also solve the problem.
    Thanks for all your work Kevin, I really appreciate it.

    • @ahmadalbaz6059
      @ahmadalbaz6059 4 роки тому +1

      a stupid question here i hope to get help with
      was the grid passed to the dfs method by value?? if that is the case if we did not update the original grid dfs will be called on every appearance of 1?

    • @nmnjn
      @nmnjn 4 роки тому +3

      @@ahmadalbaz6059 by default arrays are passed as reference in parameters.

    • @ahmadalbaz6059
      @ahmadalbaz6059 4 роки тому

      @@nmnjn
      ahh thank you!

    • @darod6098
      @darod6098 4 роки тому +5

      Actually not by reference, but you can think it as reference. It passes a copy of the memory address, because it is an object. Google how objects are passed as parameters in Java :)

    • @ahmadalbaz6059
      @ahmadalbaz6059 4 роки тому

      @@darod6098
      Thanks man
      I'm not that familiar with java that's why I'm asking

  • @christiantith2843
    @christiantith2843 5 років тому +23

    Good stuff, I like the length of your videos and readable code. I’m prepping for an interview in the midst of finals and it’s nice to not have to be mentally exhausted after going through LC questions. Keep up the good work!!😁

    • @KevinNaughtonJr
      @KevinNaughtonJr  5 років тому +5

      haha thanks Christian I really appreciate that. Lmk if there's anything I can do to try and help you!

    • @yashpreetbathla4653
      @yashpreetbathla4653 4 роки тому

      @@KevinNaughtonJr Hey kevin i just love your way of make us understanding of solution, can you make some videos of interview bit questions aswell?

  • @ohhdannyyboyy2919
    @ohhdannyyboyy2919 5 років тому +7

    Deep dive on the recursion part would be great! I understand generally what is going on, but little things like the returning of int 1 screw me up as far as how that return statement gets carried over into all of the other calls.

    • @vyshnavramesh9305
      @vyshnavramesh9305 4 роки тому +3

      All connected 1s will return 1 (after altering itself from 1 to 0) , so the top level 1 which called all these recursions will receive only one 1; which is then added to numIslands.

  • @gingeral253
    @gingeral253 Рік тому +1

    I wouldn’t have done it that way, but it’s actually so much more elegant than my solution. It’s like a wave spreading out to flip the 1s to 0s if they are connected to the initial 1. That just reduces all connected squares to 1 island.
    Also when he typed the semicolon I was confused initially, but it seems that even good programmers can make syntax errors. Good to see I can catch errors while reading code.

  • @srivatsanramesh9375
    @srivatsanramesh9375 5 років тому +5

    Amazing solution man!. Keep going. It really helps people like me without a background in CS to learn more about writing optimal codes in a simple way. Thanks

    • @KevinNaughtonJr
      @KevinNaughtonJr  5 років тому +4

      Idk how I never responded to this, my bad!!! Thanks so so much for the kind words they mean a lot to me. So happy to hear my videos are helping :)

  • @Nobody2310
    @Nobody2310 5 років тому +3

    Kevin thanks for the videos! Your explanation is very easy to understand, now it has become for me like i am sure i will understand when i watch your video more than i trust my own understanding 😊 well, would you mind just discussing the time complexity also? For some some complex problems that involve recursion, like this one in this case. Thanks again!

  • @krishnachakravarthy
    @krishnachakravarthy 4 роки тому +4

    Hey Kevin.. thanks for the videos. I got the same question in Amazon on call interview. They asked the distinct count. I followed same approach per your video but saved the path which we visited in a list. Thanks again.. you are doing great job!

    • @shraddhakharche1107
      @shraddhakharche1107 4 роки тому

      @Krishna, Can you please ellaborate more on what do you mean by distinct count?

    • @krishnachakravarthy
      @krishnachakravarthy 4 роки тому

      @@shraddhakharche1107 - AMZ asked to provide count on distinct count of islands. i.e. islands coordinates are unique.

  • @camilaj.8137
    @camilaj.8137 4 роки тому +1

    How does grid gets updated when it gets back to the for? Are you passing it by reference?

  • @BangMaster96
    @BangMaster96 3 роки тому +1

    I am such an idiot, DFS and BFS get confusing for me.

  • @jalthi1
    @jalthi1 5 років тому +2

    Thanks for posting this. I have one question - It feels like your dfs() is dangerously close to just producing side effects when you could increment numIslands and then run some kind of "sink()" recursive helper function. Where do you draw the line if you were considering OOP?

  • @dragon65533
    @dragon65533 5 років тому +6

    Love your vids man, I've been prepping for my interviews and your explanations are super clear!

    • @KevinNaughtonJr
      @KevinNaughtonJr  5 років тому

      Thanks Jay, anytime! If you need any help please be sure to let me know!

  • @Laxatangeek
    @Laxatangeek 3 роки тому +1

    Interesting video ! The technique is correct, but you are going to get an heap overflow (atleast in C++). You better check before your next recursive call to dfs if the grid[x][y] you are going to use is valid and a '1' to avoid unnecessary calls.

  • @pritamghosh270
    @pritamghosh270 4 роки тому +2

    Thanks brother. Could please elaborate the line 24 : grid[i][j] == '0' and the time complexity. Thanks again

    • @gxtube
      @gxtube 4 роки тому +1

      The complexity is O( n x m ). grid[i][j] == '0' means to press each stone of the island under water, and as a reward, obtain one "dfs"(island)

  • @satyanarayanmohanty3415
    @satyanarayanmohanty3415 4 роки тому +2

    You are amazing man. Explaining such complex problems with such ease is sheer brilliance.
    It's a great great service you are providing to us who seek for these explanations. God bless you.

    • @KevinNaughtonJr
      @KevinNaughtonJr  4 роки тому

      Thanks so much! If you need help with these questions and like my explanations sign up for the interviewing service I created: thedailybyte.dev/?ref=kevin I recommend joining the annual tier if you can! :)

  • @shameekagarwal4872
    @shameekagarwal4872 4 роки тому +1

    instead of having a visited 2d matrix , u are making the original visited cells as 0 itself ??to prevent traversing them again?

  • @jocavuleta
    @jocavuleta 5 років тому +2

    A video about recursion and discussion on that subject more deeply would be really useful. Overall really good explanation !

  • @Eugene.Berezin
    @Eugene.Berezin 5 років тому +4

    Your channel is super helpful!
    Thank you for what you do!

    • @KevinNaughtonJr
      @KevinNaughtonJr  5 років тому

      Thanks Eugene and anytime! I'm super happy to hear my channel has been helpful for you :')

  • @zentekvideogames3589
    @zentekvideogames3589 4 роки тому

    Javascript version:
    const islands = (grid) => {
    if (grid === null || grid.length === 0) {
    return 0;
    }
    let numIslands = 0;
    for (let i = 0; i < grid.length; i++) {
    for (let j = 0; j < grid[i].length; j++) {
    if (grid[i][j] === 1) {
    numIslands += depthFirstSearch(grid, i, j);
    }
    }
    }
    return numIslands;
    };
    function depthFirstSearch(grid, i, j) {
    if(i= grid.length || j=grid.length || grid[i][j] === 0){
    return 0;
    }
    grid[i][j] = 0;
    depthFirstSearch(grid, i + 1, j);
    depthFirstSearch(grid, i - 1, j);
    depthFirstSearch(grid, i, j + 1);
    depthFirstSearch(grid, i, j - 1);
    return 1;
    }

  • @wendybrooks8416
    @wendybrooks8416 4 роки тому +1

    Thanks for the video. It's obvious that you know this problem very well. I think this would be even better if you really outlined your mental model and problem solving approach a bit more, as if you were seeing the problem for the first time.

  • @jeffreylee911
    @jeffreylee911 4 роки тому +1

    This is nice bro. There is only one advice is that we actually don't need a return value when we are dealing with the base case. Just return and numIslands++ every time we "sank" an whole island.

  • @sourishisavailable
    @sourishisavailable 4 роки тому +2

    What is the run time and space complexity of this solution? Nice explanation btw.

    • @ashconnor
      @ashconnor 4 роки тому

      Space is O(1). Runtime is O(nm).

  • @HornOKPlease
    @HornOKPlease 3 роки тому

    I was so scared of this problem you made it look so easy

  • @jeetpatitundi6128
    @jeetpatitundi6128 4 роки тому +3

    Hey Thanks Kevin. I had been preparing for online assessment of Amazon. Kudos to your explanation, I was able to solve both the questions. Thanks :)

    • @KevinNaughtonJr
      @KevinNaughtonJr  4 роки тому +1

      Jeet Patitundi amazing and anytime!

    • @TheMsnitish
      @TheMsnitish 4 роки тому

      just solved the amazon tagged questions ?

    • @jeetpatitundi6128
      @jeetpatitundi6128 4 роки тому +1

      Yes. Even I bagged the job. Thank you Kevin. You are a life saver.

    • @JT-yn4zk
      @JT-yn4zk 4 роки тому

      @@jeetpatitundi6128 were you able to solve all questions in the final interview ?

    • @KevinNaughtonJr
      @KevinNaughtonJr  4 роки тому +1

      Jeet Patitundi anytime and congrats Jeet super happy for you!!!

  • @luisady8990
    @luisady8990 3 роки тому

    // TIme complexity O(N*M) - N number of rows, M - number of columns
    // Why? In the worst case we would have grid with ones. We would go through each cell using recursion on the
    // first step of the loop. Then we will do constant operation for other steps of the loop, so O(N*M + N*M)
    // Space O(N*M) - deepness of recursion
    From Github: github.com/chopdev/leetcode_tasks/blob/0df3657e8f02f53f81f7c6e48d7eb17e27857271/union_find/200_union_find/Solution.java

  • @tobedecidedlater
    @tobedecidedlater Рік тому

    The time complexity of the code is O(m * n), where m is the number of rows and n is the number of columns in the input grid. This is because the DFS function is called for each cell in the grid, and each cell is visited at most once.
    The space complexity of the code is O(m * n), as the maximum depth of the recursion is the number of cells in the grid, and in the worst case, all cells could be part of the same island. This means that the call stack could have up to m * n frames. Additionally, the DFS function modifies the input grid in-place, which requires O(1) extra space.

  • @siddharthsharma8297
    @siddharthsharma8297 4 роки тому

    ok, this might be a really stupid question, but how does the calling (numIslands) "grid" get modified ? All the work that's happening is in the helper method's grid, and we dont return those changes back to the numIslands... :////
    So how? :/

  • @michaeldang8189
    @michaeldang8189 4 роки тому

    Why do we use the dfs() to return 1 and do numIslands += dfs().
    I would think it would be more clear to change dfs() name to sinkIsland(), then do
    sinkIsland();
    numIslands++;

  • @gingeral253
    @gingeral253 Рік тому

    I’m wonder if there is a way to optimize it by somehow moving the selected cell to the end of an island before the start of the other. Doesn’t seem like it would work optimally though cuz it has too many checks.
    Also, is there a specific reason for making the helper method return 1s or 0s? Is that more efficient than checking it within the loop and having the helper be a void? Even if it doesn’t change the runtime or memory usage, having it return the value is more elegant.

  • @udaythota737
    @udaythota737 4 роки тому +1

    Good video, but it would be nice if you could also say about the time and space complexity of your solutions.

  • @nuitblanche5798
    @nuitblanche5798 2 роки тому

    Great content and very clear explanation. Thank you very much for your video! It really helped me understand this question. Please continue making more videos like this!

  • @nabhaskar5691
    @nabhaskar5691 2 роки тому

    each element in 2d metrix represent the color, how many minium number of rectangles we can form for same color? can we achieve solving this with this approach? if it is already solved can you pl share the link? if not, can you pl help in solving this?

  • @chengxue6741
    @chengxue6741 2 роки тому

    Could you please explain 733. Flood Fill, you are the best UA-camr for me who can explain everything so clear. Thank you!

  • @yourboyzzz4974
    @yourboyzzz4974 2 роки тому

    I am a new graduate and I have hard time doing these questions. I haven’t done any internships to finish my degree faster but it’s been really hard to get a job in software if you don’t have experience. Can you please give me some advice

  • @sergten
    @sergten 3 роки тому

    Do we need to go up and to the left? It seems like we would have encountered '1's from these directions because we're scanning up-to-down and left-to-right.

  • @kamalakantsingh601
    @kamalakantsingh601 3 роки тому

    this is not a complete solution it will fail if there is 1's in diagonal. I think you have to check diagonal cases also
    dfs(a,i+1,j);
    dfs(a,i-1,j);
    dfs(a,i,j+1);
    dfs(a,i,j-1);
    dfs(a,i-1,j-1);
    dfs(a,i+1,j+1);
    dfs(a,i-1,j+1);
    dfs(a,i+1,j-1);

  • @willturner3440
    @willturner3440 3 роки тому +2

    Congratulations!! Once again you won my heart 💕

  • @sarthaknikhal5540
    @sarthaknikhal5540 3 роки тому

    You make it sound easy. Have you come across this problem before? Because I could've never solved it in my first ever attempt

  • @amolmishra7891
    @amolmishra7891 4 роки тому +1

    Could you do coding questions of relatively more complex graph algorithms especially for weighted graphs?

  • @dimakavetskyy2082
    @dimakavetskyy2082 2 роки тому

    best explanation. thanks for explaining every loop instead of just writing it and assuming we know everything

  • @theceo4744
    @theceo4744 2 роки тому

    So is the time complexity O(n^2) ..? Plus what would be the space complexity?

  • @JitendraSingh-rw9bt
    @JitendraSingh-rw9bt 4 роки тому +1

    What is time complexity ?

  • @namanvohra8262
    @namanvohra8262 2 роки тому

    Thanks Kevin! I was able to solve max area of island after understanding this video of yours.

  • @soumyasengupta7018
    @soumyasengupta7018 6 років тому +2

    The return 1 ; inside the DFS call is really not required as the DFS call of any index with 1 always returns 1.
    We can straight away update islandCount if we see a 1 inside main function.
    Code is super clean btw!!!

    • @KevinNaughtonJr
      @KevinNaughtonJr  6 років тому

      Thanks! I believe that the return 1 is necessary otherwise we wouldn't be able to actually count each island. As an alternative though we could move the +1 inside the nested for loop!

    • @soumyasengupta7018
      @soumyasengupta7018 6 років тому

      Once u recursively Call DFS again on the horizontally and vertically adjacent nodes and keep calling them do you use the returned 1 anywhere except for the time you are calling from the main function.
      No right?
      So do we really need to return anything?
      In each DFS call we just want to erase the corresponding 1's.

    • @KevinNaughtonJr
      @KevinNaughtonJr  6 років тому

      Right I see what you're saying. So we can just make it the inner loop look like numberOfIslands += 1 and then call the DFS function?

    • @soumyasengupta7018
      @soumyasengupta7018 6 років тому

      @@KevinNaughtonJr
      Yes!!
      😀

    • @CarlosRomero-ef4uv
      @CarlosRomero-ef4uv 5 років тому

      I agree with Soumya here, the whole time I was like " why is there a return". You can code things up multiple ways, but Soumya explained it well. I feel its more intuitive.
      you find a 1
      Increase count by 1 and then perform a void dfs that just flips the 1's to 0's and then continue until you find another 1. (insert DJ Khalid voice)

  • @victoriac7257
    @victoriac7257 3 роки тому

    I do have a question, why do we have to search for four directions, why can't we search for only right and down directions?

  • @IsaacPiera
    @IsaacPiera 4 роки тому

    wouldn't it make more sense to make dfs not return anything and just increment num_islands after the call to dfs?

  • @isoplayers
    @isoplayers 5 років тому +2

    Great explanation! Please consider making videos on Systems Design :)

    • @KevinNaughtonJr
      @KevinNaughtonJr  5 років тому +1

      Thanks! I've been thinking about doing that...maybe I'll start doing that soon

  • @14BIDISHA
    @14BIDISHA 3 роки тому +1

    Understood this problem for the first time. Thanks

  • @ambermichellemartinez
    @ambermichellemartinez Рік тому

    this video was so clear and easy to understand, thank you so much always!!!!

  • @sasirekhamsvl9504
    @sasirekhamsvl9504 3 роки тому

    nice video. Why don't you make a video on "m-coloring graph"

  • @k.alipardhan6957
    @k.alipardhan6957 6 років тому +2

    if you ever have the time, id love to see you take on the higher difficulty questions (medium/hard)

    • @KevinNaughtonJr
      @KevinNaughtonJr  6 років тому +1

      Thanks for the input, I'll try and start doing some harder problems!

  • @miraqiu4470
    @miraqiu4470 5 років тому +1

    Thanks so much. Your video is so clear to the point.

  • @thecheekychinaman6713
    @thecheekychinaman6713 4 роки тому +1

    This is pretty genius, and very clearly explained. Essentially, even though the neighbours of your island grid point are 1, your dfs method returns 1 for each neighbour but these arent stored anywhere. Only the original dfs call is returned as an increment of the island. Simultaneously, you avoid the double count (as you said) through this approach.
    I was thinking of an iterative approach of checking the row above you and to your right, each time, but it quickly span out of control. I think your solution is the best thus far!

  • @JanacMeena
    @JanacMeena 3 роки тому

    Does anyone know why leetcode lists "union find" as a related topic?

  • @Ajaykumar-nj7lf
    @Ajaykumar-nj7lf 4 роки тому

    Even Odd
    Problem Description
    Given a range [low, high] (both inclusive), select K numbers from the range (a number can be chosen multiple times) such that sum of those K numbers is even.
    Calculate the number of all such permutations.
    As this number can be large, print it modulo (1e9 +7).
    Constraints
    0

  • @DurgaShiva7574
    @DurgaShiva7574 2 роки тому

    what a video.. amamzing.. awesome, best, and crispy!

  • @ivanleon6164
    @ivanleon6164 3 роки тому

    if you start in 0,0 do you really need to call i-1 and j-1? if you go always to the right and down, you dont need to go back as its already visited, at least thats what seems to me for a quick inspection.

  • @mastbawa
    @mastbawa 5 років тому +4

    Thank you for explaining this one!

    • @KevinNaughtonJr
      @KevinNaughtonJr  5 років тому

      Anytime I hope it was helpful!

    • @mastbawa
      @mastbawa 5 років тому

      @@KevinNaughtonJr Totally! It was asked to me 2 years back in fb and i was not able to solve. Only addition they added is, find the longest island as well.

    • @KevinNaughtonJr
      @KevinNaughtonJr  5 років тому

      It's a tough one! Interesting modification, thanks for sharing :)

    • @vyshnavramesh9305
      @vyshnavramesh9305 4 роки тому

      @@mastbawa wild guess: maintain another variable localLongestIsland. Increment it by 1 inside dfs(). Maintain another variable globalLongestIsland. Update globalLongestIsland whenever its smaler than localLongestIsland.

  • @a2xd94
    @a2xd94 Рік тому

    Can you comment on why you'd use DFS instead of BFS on this particular problem? I've seen other solutions recommending to use BFS instead, and I'm having a hard time explaining to myself why you'd go one way or the other, for this particular problem. Thanks!

  • @neetisharma3768
    @neetisharma3768 4 роки тому +2

    Thanks for making it so simple :)

  • @ythalorossy
    @ythalorossy 2 роки тому

    Hi Kevin,
    thank you very much for sharing.

  • @weijiewen3392
    @weijiewen3392 2 роки тому

    Using BFS would be much easier to understand

  • @abhijitpatwardhan8406
    @abhijitpatwardhan8406 5 років тому

    What would be the runtime complexity of this? I wish I could answer this right now. On a different (from Leetcode) site I am seeing that a DFS solution times out vs. BFS works. On Leetcode though, this DFS solution clearly wins in terms of runtime. Unable to reconcile those two observations. Anyways, keep up the great job! Your videos are very helpful!

  • @markonikolic6346
    @markonikolic6346 4 роки тому

    What is the difference between i++, and i+1? I failed task, trying to use i++, and i-- in last few lines of code.

    • @vidyasagar5819
      @vidyasagar5819 4 роки тому

      i++ increase the value of i but i+1 dosen't

  • @menogenfang4351
    @menogenfang4351 5 років тому +1

    Lucky to find your videos. Set my first aim in new year, to watch all the videos you made as soon as possible. Two at least one day. Hopefully help me with my near feature interview with Google。

    • @menogenfang4351
      @menogenfang4351 5 років тому

      near future...

    • @KevinNaughtonJr
      @KevinNaughtonJr  5 років тому +1

      Haha thanks that sounds like a great resolution to me! Thank you so much for all the support and let me know if there's anything I can do to help you prepare for your interview!

    • @menogenfang4351
      @menogenfang4351 5 років тому

      @@KevinNaughtonJr Thank you for your help in advance.I think I need to overcome the poor expression...Explained them in English something hard for me and often go blank. I will persist in watching your video to learn from it !!!

  • @ronifintech9434
    @ronifintech9434 2 роки тому

    beautiful and better than any paid services out there :)

  • @NotNotNithin
    @NotNotNithin 3 роки тому

    I have my Google interview and my small term goal is to solve at least a 100 Google related problems. Thanks Kevin! This helped me a lot! :-) Also would appreciate if you could add more Google related problems.

  • @RanjuRao
    @RanjuRao 3 роки тому

    Although I liked the way solution is derived in limited time , it would have been better, if visual explanation of the sample test case is considered while you code!