question_slug stringlengths 3 77 | title stringlengths 1 183 | slug stringlengths 12 45 | summary stringlengths 1 160 ⌀ | author stringlengths 2 30 | certification stringclasses 2
values | created_at stringdate 2013-10-25 17:32:12 2025-04-12 09:38:24 | updated_at stringdate 2013-10-25 17:32:12 2025-04-12 09:38:24 | hit_count int64 0 10.6M | has_video bool 2
classes | content stringlengths 4 576k | upvotes int64 0 11.5k | downvotes int64 0 358 | tags stringlengths 2 193 | comments int64 0 2.56k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
number-of-closed-islands | Easy to understand DFS solution with COMMENTS | easy-to-understand-dfs-solution-with-com-uxbm | Yo, since I spent some time on this question, just want to help you guy save time.\n\n\nclass Solution {\n boolean dfs(int [][] grid, int i, int j) {\n | nhatdinh041 | NORMAL | 2019-11-10T08:08:20.689247+00:00 | 2019-11-10T08:21:22.742249+00:00 | 537 | false | Yo, since I spent some time on this question, just want to help you guy save time.\n\n```\nclass Solution {\n boolean dfs(int [][] grid, int i, int j) {\n int row = grid.length;\n int col = grid[0].length;\n \n // go beyond of the border is not a good idea\n if (i < 0 || j < 0 || i >= row || j >= col) return false;\n \n // okay we hit the wall but at least we are okay\n if (grid[i][j] == 1 || grid[i][j] == 2) return true;\n \n // visit this cell, mark it as visited by changing the value to 2\n grid[i][j] = 2;\n \n // go go go\n boolean down = dfs(grid, i - 1, j);\n boolean up = dfs(grid, i + 1, j);\n boolean left = dfs(grid, i, j - 1);\n boolean right = dfs(grid, i, j + 1);\n \n // if this return true, we know that we are standing on a close island\n return down && up && left && right;\n }\n \n public int closedIsland(int[][] grid) {\n int row = grid.length;\n int col = grid[0].length;\n int result = 0;\n \n for (int r = 0; r < row; r++) {\n for (int c = 0; c < col; c++) {\n if (grid[r][c] == 0) {\n if (dfs(grid, r, c)) result++;\n }\n }\n }\n \n return result;\n }\n}\n``` | 6 | 0 | ['Depth-First Search', 'Java'] | 2 |
number-of-closed-islands | c++ bfs/dfs without vis array approach | c-bfsdfs-without-vis-array-approach-by-z-aiea | Intuition\n Describe your first thoughts on how to solve this problem. \nbfs dfs \nthe code is well explained\n//also i had a third approach whichi knew but i | zaidokhla | NORMAL | 2023-04-06T20:24:05.807362+00:00 | 2023-04-06T20:24:05.807476+00:00 | 1,658 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nbfs dfs \nthe code is well explained\n//also i had a third approach whichi knew but i dont why it is not working on leetcode \nin that we basically we ran dfs from the boundary cell and mark islands from there as 1 \nthen we iterated over the main grid when encountered with a 0 visited that island via a dfs and updated the counter finally returned the counter\nif you know plz let me know\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n\n vector<vector<int>>dir={{0,1},{0,-1},{1,0},{-1,0}};\n bool dfs(int i,int j,vector<vector<int>>&grid){\n //what each dfs call will tell \n //each dfs call will tell that whether the island centered around given \n //corndinate cell is a closed one or note\n //so in the base of this recursive dfs function we checked whether \n // it is directory touching any border of the grid\n\n // if the the current grid is non zero it is an indication that either there is1 \n //or that cell has already been visited \n // then in recurrence we checked whether any neighbour of it is unclosed or not \n //if so then the island from the currrent cell will also be an unclosed one\n\n\n\n if(i<0||j<0||i>=grid.size()||j>=grid[0].size()){\n return false;\n }\n if(grid[i][j]!=0){\n return true;\n }\n // vis[i][j]=1;\n grid[i][j]=1;\n bool ist=true;\n for(auto e:dir){\n int nx=e[0]+i;\n int ny=e[1]+j;\n if(dfs(nx,ny,grid)==false){\n ist=false;\n }\n }\n return ist;\n\n }\n\n bool bfs (int i,int j,vector<vector<int>>&grid){\n\n //here each bfs call will tell whether the island of which the current cell is \n //part of is a closed one or not \n queue<vector<int>>qp;\n qp.push({i,j});\n bool pos=true;\n\n while(!qp.empty()){\n auto t= qp.front();\n qp.pop();\n grid[t[0]][t[1]]=1;\n for(auto e:dir){\n int nx=t[0]+e[0];\n int ny=t[1]+e[1];\n if(nx<0||ny<0||nx>=grid.size()||ny>=grid[0].size()){\n pos=false;\n }else if(grid[nx][ny]==1){\n continue;\n }else{\n qp.push({nx,ny});\n\n }\n }\n }\n return pos;\n\n }\n \n int closedIsland(vector<vector<int>>& grid) {\n\n\n\n //intuition is that each time a zero cell is encountered we try to find \n //whether any cell in its connected component is touching the boundary of the grid \n //in that case that island cannot be a closed island in rest of the cases that \n //island will be a connected component \n //do not use a visited array just modify the grid in place as visted array \'\n //this is a space optimsation step\n\n int n=grid.size();\n int m=grid[0].size();\n int c=0;\n \n for(int i=0;i<n;i++){\n for(int j=0;j<m;j++){\n if(grid[i][j]==0 && bfs(i,j,grid)){\n c++;\n }\n }\n }\n return c;\n\n\n\n\n \n }\n};\n``` | 5 | 0 | ['C++'] | 2 |
number-of-closed-islands | Striver type approch :) | striver-type-approch-by-piyush512002-divy | Intuition\nFirst traverse through boundary just like in surrounded region question then we need to traverse in island just like number of island type question b | piyush512002 | NORMAL | 2023-04-06T10:17:09.378347+00:00 | 2023-05-13T18:24:48.583861+00:00 | 323 | false | # Intuition\nFirst traverse through boundary just like in surrounded region question then we need to traverse in island just like number of island type question basically its a mixture of surrounded region + number od island question.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\nO(n*m)\n\n- Space complexity:\nO(n*m)\n\n# Code\n```\nclass Solution {\npublic:\n void dfs(int row,int col,vector<vector<int>> &grid,vector<vector<int>> &visited){\n int n=grid.size();\n int m=grid[0].size();\n \n visited[row][col]=1;\n int drow[4]={-1,0,1,0};\n int dcol[4]={0,1,0,-1};\n for(int i=0;i<4;i++){\n int nrow=row+drow[i];\n int ncol=col+dcol[i];\n if (nrow>=0 && nrow<n && ncol>=0 && ncol<m \n && !visited[nrow][ncol] && grid[nrow][ncol]==0){\n dfs(nrow,ncol,grid,visited);\n }\n }\n }\n int closedIsland(vector<vector<int>>& grid) {\n int n=grid.size();\n int m=grid[0].size();\n vector<vector<int>>visited(n,vector<int>(m,0));\n for(int j=0;j<m;j++){\n if(!visited[0][j] && grid[0][j]==0){\n dfs(0,j,visited,grid);\n }\n if(!visited[n-1][j] && grid[n-1][j]==0){\n dfs(n-1,j,visited,grid);\n }\n }\n for(int i=0;i<n;i++){\n if(!visited[i][0] && grid[i][0]==0){\n dfs(i,0,visited,grid);\n }\n if(!visited[i][m-1] && grid[i][m-1]==0){\n dfs(i,m-1,visited,grid);\n }\n }\n\n int count = 0;\n for (int i = 1; i < n-1; i++) {\n for (int j = 1; j < m-1; j++) {\n if (!visited[i][j] && grid[i][j] == 0) {\n dfs(i, j, grid,visited);\n count++;\n }\n }\n }\n return count;\n }\n};\n``` | 5 | 0 | ['Depth-First Search', 'C++', 'Java'] | 1 |
number-of-closed-islands | JAVA || BEATS 100% || EASY UNDERSTANDING || SIMPLE || DFS || BIT MANIPULATION | java-beats-100-easy-understanding-simple-3k7w | Code\n\nclass Solution {\n public int closedIsland(int[][] grid) {\n int cnt=0;\n int n=grid.length,m=grid[0].length;\n boolean vis[][]= | shaikhu3421 | NORMAL | 2023-04-06T05:08:11.853084+00:00 | 2023-04-06T05:12:18.678912+00:00 | 549 | false | # Code\n```\nclass Solution {\n public int closedIsland(int[][] grid) {\n int cnt=0;\n int n=grid.length,m=grid[0].length;\n boolean vis[][]=new boolean[n][m];\n for(int i=0;i<n;i++){\n for(int j=0;j<m;j++){\n if(grid[i][j]==0){\n cnt+=dfs(i,j,grid,vis,n,m);\n }\n }\n }\n return cnt;\n }\n public static int dfs(int i,int j,int a[][],boolean vis[][],int n,int m){\n if(i>=n||j>=m||i<0||j<0) return 0;\n if(a[i][j]==1) return 1;\n a[i][j]=1;\n int up=dfs(i-1,j,a,vis,n,m);\n int down=dfs(i+1,j,a,vis,n,m);\n int left=dfs(i,j-1,a,vis,n,m);\n int right=dfs(i,j+1,a,vis,n,m);\n return up&down&left&right;\n }\n}\n```\nUPVOTE IF U LIKE THE APPROACH | 5 | 1 | ['Bit Manipulation', 'Depth-First Search', 'Java'] | 4 |
number-of-closed-islands | Easy & Clear Solution Python 3 DFS | easy-clear-solution-python-3-dfs-by-moaz-htmx | \n# Code\n\nclass Solution:\n def closedIsland(self, grid: List[List[int]]) -> int:\n def dfs(i,j,newval):\n if grid[i][j]==0:\n | moazmar | NORMAL | 2023-04-06T04:01:01.222455+00:00 | 2023-04-06T04:01:01.222488+00:00 | 574 | false | \n# Code\n```\nclass Solution:\n def closedIsland(self, grid: List[List[int]]) -> int:\n def dfs(i,j,newval):\n if grid[i][j]==0:\n grid[i][j]=2\n if i<len(grid)-1 : dfs(i+1,j,newval)\n if i >0 : dfs(i-1,j,newval)\n if j<len(grid[0])-1 : dfs(i,j+1,newval)\n if j>0 : dfs(i,j-1,newval)\n for i in range(len(grid)):\n for j in range(len(grid[0])):\n if i==0 or j==0 or i==len(grid)-1 or j == len(grid[0])-1:\n if grid[i][j]==0:\n dfs(i,j,2)\n res=0\n for i in range(1,len(grid)-1):\n for j in range(1,len(grid[0])-1):\n if grid[i][j]==0:\n res+=1\n dfs(i,j,2)\n return res\n``` | 5 | 0 | ['Depth-First Search', 'Python3'] | 1 |
number-of-closed-islands | Python DFS, BFS, Recursive, Iterative, DSU | python-dfs-bfs-recursive-iterative-dsu-b-av6k | DFS \n## recursive\nDeal with the borders first (we ignore them) and then proceed to inner islands\npython\nclass Solution:\n def closedIsland(self, grid: Li | nth-attempt | NORMAL | 2022-12-29T05:07:41.480444+00:00 | 2022-12-29T05:07:41.480491+00:00 | 671 | false | # DFS \n## recursive\nDeal with the borders first (we ignore them) and then proceed to inner islands\n```python\nclass Solution:\n def closedIsland(self, grid: List[List[int]]) -> int:\n R, C = len(grid), len(grid[0])\n directions = [(1,0), (0,1), (-1,0), (0,-1)]\n \n def is_valid(r, c):\n return 0 <= r < R and 0 <= c < C\n \n def is_border(r, c):\n return r == 0 or r == R-1 or c == 0 or c == C-1\n \n def dfs(r, c):\n if not is_valid(r, c) or grid[r][c] != 0:\n return\n grid[r][c] = 1\n for dr, dc in directions:\n dfs(r+dr, c+dc)\n \n for r in range(R):\n for c in range(C):\n if is_border(r, c) and grid[r][c] == 0:\n dfs(r, c)\n\n res = 0\n for r in range(R):\n for c in range(C):\n if grid[r][c] == 0:\n dfs(r, c)\n res += 1\n return res\n \n```\n## iterative\n```python\nclass Solution:\n def closedIsland(self, grid: List[List[int]]) -> int:\n R, C = len(grid), len(grid[0])\n directions = [(1,0), (0,1), (-1,0), (0,-1)]\n \n def is_valid(r, c):\n return 0 <= r < R and 0 <= c < C\n \n def is_border(r, c):\n return r == 0 or r == R-1 or c == 0 or c == C-1\n \n def dfs(r, c):\n stack = [(r, c)]\n while stack:\n r, c = stack.pop()\n grid[r][c] = 1\n for dr, dc in directions:\n nr, nc = r+dr, c+dc\n if is_valid(nr, nc) and grid[nr][nc] == 0:\n stack.append((nr, nc))\n \n for r in range(R):\n for c in range(C):\n if is_border(r, c) and grid[r][c] == 0:\n dfs(r, c)\n\n res = 0\n for r in range(R):\n for c in range(C):\n if grid[r][c] == 0:\n dfs(r, c)\n res += 1\n return res\n \n```\n# BFS\n```python\nclass Solution:\n def closedIsland(self, grid: List[List[int]]) -> int:\n R, C = len(grid), len(grid[0])\n directions = [(1,0), (0,1), (-1,0), (0,-1)]\n \n def is_valid(r, c):\n return 0 <= r < R and 0 <= c < C\n \n def is_border(r, c):\n return r == 0 or r == R-1 or c == 0 or c == C-1\n \n def bfs(r, c):\n grid[r][c] = 1\n queue = collections.deque([(r, c)])\n while queue:\n r, c = queue.popleft()\n for dr, dc in directions:\n nr, nc = r+dr, c+dc\n if is_valid(nr, nc) and grid[nr][nc] == 0:\n grid[nr][nc] = 1\n queue.append((nr, nc))\n\n \n for r in range(R):\n for c in range(C):\n if is_border(r, c) and grid[r][c] == 0:\n bfs(r, c)\n\n res = 0\n for r in range(R):\n for c in range(C):\n if grid[r][c] == 0:\n bfs(r, c)\n res += 1\n return res\n```\n\n# Union Find\n```python\nclass DSU:\n def __init__(self):\n self.parent = {}\n self.count = 0\n\n def insert(self, x):\n if x not in self.parent:\n self.parent[x] = x\n self.count += 1\n\n def find(self, x):\n if x != self.parent[x]:\n self.parent[x] = self.find(self.parent[x])\n return self.parent[x]\n \n def union(self, x, y):\n px, py = self.find(x), self.find(y)\n if px != py:\n self.parent[px] = py\n self.count -= 1\n\nclass Solution:\n def closedIsland(self, grid: List[List[int]]) -> int:\n R, C = len(grid), len(grid[0])\n directions = [(1,0), (0,1)]\n \n def is_valid(r, c):\n return 0 <= r < R and 0 <= c < C\n \n def is_border(r, c):\n return r == 0 or r == R-1 or c == 0 or c == C-1\n \n dsu = DSU()\n # adding an extra component/island to collect all border islands\n dsu.insert((R, C))\n for r in range(R):\n for c in range(C):\n if grid[r][c] == 0:\n dsu.insert((r, c))\n if is_border(r, c):\n dsu.union((r, c), (R, C))\n for dr, dc in directions:\n nr, nc = r+dr, c+dc\n if is_valid(nr, nc) and grid[nr][nc] == 0:\n dsu.insert((nr, nc))\n dsu.union((nr, nc), (r, c))\n # need to subtract 1 because of the extra component/island we added (R, C)\n # if any islands are present on the borders, they all get added to the (R, C) component. \n return dsu.count - 1\n``` | 5 | 0 | ['Depth-First Search', 'Breadth-First Search', 'Union Find', 'Python', 'Python3'] | 0 |
number-of-closed-islands | 1254. Number of Closed Islands Using DFS | 1254-number-of-closed-islands-using-dfs-aoga7 | Similar Problem\n 130. Surrounded Regions\n# Code \n\nclass Solution {\npublic:\n void dfs(int i,int j,vector<vector<int>>& grid,vector<vector<int>>&v | Pallavi_Dhakne | NORMAL | 2022-12-27T09:15:28.936393+00:00 | 2022-12-27T09:15:28.936433+00:00 | 1,059 | false | # Similar Problem\n 130. Surrounded Regions\n# Code \n```\nclass Solution {\npublic:\n void dfs(int i,int j,vector<vector<int>>& grid,vector<vector<int>>&vis,int n,int m,int drow[],int dcol[])\n {\n vis[i][j]=1;\n for(int k=0;k<4;k++)\n {\n int nrow=drow[k]+i;\n int ncol=dcol[k]+j;\n if(nrow<n && nrow>=0 && ncol<m && ncol>=0 && !vis[nrow][ncol] && grid[nrow][ncol]==0)\n {\n dfs(nrow,ncol,grid,vis,n,m,drow,dcol);\n }\n }\n }\n int closedIsland(vector<vector<int>>& grid) {\n int n=grid.size();\n int m=grid[0].size();\n int drow[]={-1,0,1,0};\n int dcol[]={0,1,0,-1};\n vector<vector<int>>vis(n,vector<int>(m,0));\n for(int j=0;j<m;j++)\n {\n if(!vis[0][j] && grid[0][j]==0)\n {\n dfs(0,j,grid,vis,n,m,drow,dcol);\n }\n if(!vis[n-1][j]&& grid[n-1][j]==0)\n {\n dfs(n-1,j,grid,vis,n,m,drow,dcol);\n }\n }\n for(int i=0;i<n;i++)\n {\n if(!vis[i][0]&& grid[i][0]==0)\n {\n dfs(i,0,grid,vis,n,m,drow,dcol);\n }\n if(!vis[i][m-1] && grid[i][m-1]==0)\n {\n dfs(i,m-1,grid,vis,n,m,drow,dcol);\n }\n }\n int cnt=0;\n for(int i=1;i<n;i++)\n {\n for(int j=1;j<m;j++)\n {\n if(grid[i][j]==0 && !vis[i][j])\n {\n cnt++;\n dfs(i,j,grid,vis,n,m,drow,dcol);\n }\n }\n }\n return cnt;\n }\n};\n```\n\n**Bold** | 5 | 0 | ['Array', 'Depth-First Search', 'Breadth-First Search', 'C++'] | 2 |
number-of-closed-islands | Java DFS || 2ms || Beats 96.01%🔥 | java-dfs-2ms-beats-9601-by-anujpanchal20-90pn | To solve this problem efficiently, we first need to understand how this problem is different from 2000. Number of Islands.\nThe difference is that we have to ex | anujpanchal2001 | NORMAL | 2022-11-19T14:32:16.617827+00:00 | 2022-11-19T14:34:57.394353+00:00 | 844 | false | To solve this problem efficiently, we first need to understand how this problem is different from [2000. Number of Islands](https://leetcode.com/problems/number-of-islands/?envType=study-plan&id=graph-i).\nThe difference is that we have to exclude the islands that have a land cell at the top, left, right or bottom border.\nEasy way to solve this question is that:\n1. Start from every border land cell and mark islands with that border cell as water, because they can\'t be part of the answer.\n2. Then we would be left with grid having only internal *islands*.\n3. For every land cell call a `BFS` or `DFS` util function and mark all *4-directional neighbours* as visited or a special symbol, I am using \'2\'.\n4. Marking with special symbol helps in avoiding using a 2-d visited array, thus saves memory.\n\nTime Complexity: `O(m*n)`\nSpace Complexity: `O(m*n)`\nRuntime: `2ms`\nBeats: `96.01%`\n\n**Code**:\n```\nclass Solution {\n public int closedIsland(int[][] grid) {\n int m = grid.length;\n int n = grid[0].length;\n for(int i=0;i<m;i++) {\n //mark border land cell islands\n markWater(grid, i, 0);\n //mark border land cell islands\n markWater(grid, i, n - 1);\n }\n for(int j=0;j<n;j++) {\n //mark border land cell islands\n markWater(grid, 0, j);\n //mark border land cell islands\n markWater(grid, m - 1, j);\n }\n int ans = 0;\n for(int i=0;i<m;i++) {\n for(int j=0;j<n;j++) {\n if(grid[i][j] == 0) {\n ans++;\n //if there is a land cell, increment the answer and mark all 4-directional neighbours as visited or a special symbol.\n dfs(grid, i, j);\n }\n }\n }\n return ans;\n }\n //marks every land cell as water that are attached to border land cell\n static void markWater(int[][] grid, int i, int j) {\n if(i < 0 || i >= grid.length || j < 0 || j >= grid[0].length || grid[i][j] == 1)\n return;\n grid[i][j] = 1;\n markWater(grid, i - 1, j);\n markWater(grid, i, j - 1);\n markWater(grid, i + 1, j);\n markWater(grid, i, j + 1);\n }\n //marks all 4-directional neighbours as special symbol\n static void dfs(int[][] grid, int i, int j) {\n if(i < 0 || i >= grid.length || j < 0 || j >= grid[0].length || grid[i][j] == 1 || grid[i][j] == 2)\n return;\n grid[i][j] = 2;\n dfs(grid, i - 1, j);\n dfs(grid, i, j - 1);\n dfs(grid, i + 1, j);\n dfs(grid, i, j + 1);\n }\n}\n``` | 5 | 0 | ['Depth-First Search', 'Java'] | 0 |
number-of-closed-islands | Java | DFS | explanation | java-dfs-explanation-by-f096t004-8udx | Closed islands is the islands which a island or multiple connected-islands closed by water 4-directionally. Hence, if you look the image below, then you\'ll fi | f096t004 | NORMAL | 2022-06-21T17:46:52.957533+00:00 | 2022-06-21T17:46:52.957582+00:00 | 658 | false | Closed islands is the islands which a island or multiple connected-islands closed by water **4-directionally**. Hence, if you look the image below, then you\'ll find out that the islands on the right-top side is not defined as closed islands. That\'s because it is not totally surrendered by the water. The rest side of that islands is out of the boundary of our 2D array. \n \n\n\nBelow is my solution in Java with the note and explanation. Hope it helps.\n\n```\nclass Solution \n{\n public int closedIsland(int[][] grid)\n {\n // O(n * m) time \n // O(n * m) space\n int count = 0;\n \n for(int i = 0; i < grid.length; i++)\n {\n for(int j = 0; j < grid[i].length; j++)\n {\n // trigger DFS once we visit land\n if(grid[i][j] == 0 && isClosed(grid, i, j))\n count++;\n }\n }\n return count;\n }\n \n public boolean isClosed(int[][] grid, int i, int j)\n {\n if(i < 0 || i >= grid.length || j < 0 || j >= grid[0].length)\n return false;\n \n if(grid[i][j] == 1) \n return true;\n \n // once we visited the land, we change it from land -> water\n grid[i][j] = 1;\n \n boolean up = isClosed(grid, i+1, j);\n boolean down = isClosed(grid, i-1, j);\n boolean left = isClosed(grid, i, j-1);\n boolean right = isClosed(grid, i, j+1);\n \n return (up && down && left && right);\n }\n}\n```\n | 5 | 0 | ['Depth-First Search', 'Java'] | 0 |
number-of-closed-islands | [C++] dfs + UnionFind ( disjoint set ) | c-dfs-unionfind-disjoint-set-by-kormulev-q4gv | Sure it is far from the optimal solution but just one of the possible implementatoin.\nThe idea is that first of all we invert all the islands that are not cons | kormulev | NORMAL | 2021-08-19T14:31:41.357857+00:00 | 2021-08-19T14:31:41.357905+00:00 | 504 | false | Sure it is far from the optimal solution but just one of the possible implementatoin.\nThe idea is that first of all we invert all the islands that are not considered closed, i.e. not enclosed with water. It means that such islands are on borders. By inversion i mean that we flood them with water. After that we are only left with relevent islands and we only need to count them. For flooding islands with water i use dfs and for counting islands i use Disjoint Set to gather each separate island by their roots, kind of clustering. then i just walk through the input and count related roots.\n```\nclass UnionFind {\n std::vector<int> roots;\n std::vector<int> ranks;\n \npublic:\n UnionFind( const std::vector<std::vector<int>> &grid )\n {\n roots.resize( grid.size() * ( grid.front().size() + 1 ) );\n ranks.resize( roots.size() );\n for( int i = 0; i < roots.size(); ++i ) {\n roots[ i ] = i;\n ranks[ i ] = 1;\n }\n }\n\n // time O( 1 )\n int find( int x )\n {\n if( x == roots[ x ] )\n return x;\n return roots[ x ] = find( roots[ x ] );\n }\n\n // time O( 1 )\n void unite( int x, int y )\n {\n int rootX = find( x );\n int rootY = find( y );\n if( rootX == rootY )\n return;\n\n if( ranks[ rootX ] > ranks[ rootY ] ) {\n roots[ rootY ] = rootX;\n } else if( ranks[ rootX ] < ranks[ rootY ] ) {\n roots[ rootX ] = rootY;\n } else {\n roots[ rootY ] = rootX;\n ++ranks[ rootX ];\n }\n }\n \n // time O( 1 )\n bool is_connected( int x, int y )\n {\n return find( x ) == find( y );\n }\n};\n\nclass Solution {\n int hsize{ 0 };\npublic:\n // time O( N^2 x M^2 ), where N == g.size() and M == g.front().size()\n // space O( N x M ), where N == g.size() and M == g.front().size()\n int closedIsland(vector<vector<int>>& grid)\n {\n flood_islands( grid );\n hsize = grid.front().size();\n UnionFind uf{ grid };\n for( int i = 0; i < grid.size(); ++i ) {\n for( int j = 0; j < grid.front().size(); ++j ) {\n if( !grid[ i ][ j ] ) {\n if( i > 0 && !grid[ i - 1 ][ j ] )\n uf.unite( transform( i, j ), transform( i - 1, j ) );\n \n if( j > 0 && !grid[ i ][ j - 1 ] )\n uf.unite( transform( i, j ), transform( i, j - 1 ) );\n \n if( ( i + 1 ) < grid.size() && !grid[ i + 1 ][ j ] )\n uf.unite( transform( i, j ), transform( i + 1, j ) );\n \n if( ( j + 1 ) < grid.front().size() && !grid[ i ][ j + 1 ] )\n uf.unite( transform( i, j ), transform( i, j + 1 ) );\n }\n }\n }\n \n std::unordered_set<int> roots;\n for( int i = 0; i < grid.size(); ++i ) {\n for( int j = 0; j < grid.front().size(); ++j ) {\n if( !grid[ i ][ j ] )\n roots.insert( uf.find( transform( i, j ) ) );\n }\n }\n \n return roots.size();\n }\n \n // time O( N^2 x M^2 ), where N == g.size() and M == g.front().size()\n // space O( N x M ), where N == g.size() and M == g.front().size()\n void flood_islands( std::vector<std::vector<int>> &g )\n {\n for( int i = 0; i < g.size(); ++i ) {\n for( int j = 0; j < g.front().size(); ++j ) {\n if( !g[ i ][ j ] && is_onboard( g, i, j ) )\n dfs( g, i, j );\n }\n }\n }\n \n bool is_onboard( const std::vector<std::vector<int>> &g, int i, int j )\n {\n if( !i || !j || i >= ( g.size() - 1 ) || j >= ( g.front().size() - 1 ) )\n return true;\n return false;\n }\n \n // time O( N x M ), where N == g.size() and M == g.front().size()\n // space O( N x M ), where N == g.size() and M == g.front().size()\n void dfs( std::vector<std::vector<int>> &g, int i, int j )\n {\n if( i < 0 || j < 0 || i >= g.size() || j >= g.front().size() )\n return;\n \n if( g[ i ][ j ] )\n return;\n \n g[ i ][ j ] = 1;\n dfs( g, i + 1, j );\n dfs( g, i - 1, j );\n dfs( g, i, j + 1 );\n dfs( g, i, j - 1 );\n }\n \n int transform( int y, int x )\n {\n return y * hsize + x;\n }\n};\n``` | 5 | 0 | ['Depth-First Search', 'Union Find', 'C'] | 0 |
number-of-closed-islands | Well explained Python solution with DFS | well-explained-python-solution-with-dfs-u2xn0 | Number of closed Islands\nhttps://leetcode.com/problems/number-of-closed-islands/submissions/\n\nclass Solution(object):\n def closedIsland(self, grid):\n | pakilamak | NORMAL | 2020-08-19T03:11:26.685801+00:00 | 2020-09-21T01:44:52.001553+00:00 | 849 | false | **Number of closed Islands**\nhttps://leetcode.com/problems/number-of-closed-islands/submissions/\n```\nclass Solution(object):\n def closedIsland(self, grid):\n """\n :type grid: List[List[int]]\n :rtype: int\n """\n count =0\n \n # iterate through the grid from 1 to length og grid for rows\n # and columns.\n # the iteration starts from 1 because if a 0 is present\n # in the 0th column, it can\'t be a closed island.\n for i in range(1, len(grid)-1):\n for j in range(1, len(grid[0])-1):\n \n # if the item in the grid is 0 and it is surrounded by\n # up, down, left, right 1\'s then increment the count.\n if grid[i][j] == 0 and self.dfs(grid, i , j):\n count +=1\n return count\n \n def dfs(self, grid, i, j):\n \n # if grid[i][j] is 1 then return True, this helps is checking the\n # final return conditons.\n if grid[i][j]==1:\n return True\n \n # now check if the element 0 is present at the outmost rows and column\n # then return False\n if i<=0 or j<=0 or i>=len(grid)-1 or j >=len(grid[0])-1:\n return False\n \n # initialize the item as 1\n grid[i][j] = 1\n \n # now check the conditions for up, down, left, right\n up = self.dfs(grid, i+1, j)\n down = self.dfs(grid, i-1, j)\n right = self.dfs(grid, i, j+1)\n left = self.dfs(grid, i, j-1)\n \n # if up, down , left, right is True, then return to main function\n return up and down and left and right\n```\n\n**Number of islands**\nhttps://leetcode.com/problems/number-of-islands/\n```\nclass Solution(object):\n def numIslands(self, grid):\n """\n :type grid: List[List[str]]\n :rtype: int\n """\n \n # intialize a variable count to count the number of islands\n count =0\n \n # iterate through the grid\n for i in range(len(grid)):\n for j in range(len(grid[0])):\n \n # if the element in grid is 1 then do dfs\n if grid[i][j] == \'1\':\n self.dfs(grid, i, j)\n \n # increment the count once dfs is done\n count +=1\n \n return count\n \n def dfs(self, grid, i , j):\n \n # check for edge conditions and items as 0\n if i<0 or j<0 or i>=len(grid) or j>=len(grid[0]) or grid[i][j]!= \'1\':\n return\n \n # if the above conditions passes then update the element in the list with \'#\'\n # every we visit a node with one change it to \'#\' so that there is no duplicate iteration.\n grid[i][j] = \'#\'\n \n # perform dfs for the particular element.\n self.dfs(grid, i+1, j )\n self.dfs(grid, i-1, j)\n self.dfs(grid, i, j+1)\n self.dfs(grid, i, j-1) \n\t\t\n\t\t\n#BFS with queue\nclass Solution:\n def numIslands(self, grid: List[List[str]]) -> int:\n if not grid:\n return 0\n \n count =0\n directions = [(1,0), (-1, 0), (0, 1), (0, -1)]\n \n for i in range(len(grid)):\n for j in range(len(grid[0])):\n if grid[i][j]=="1":\n q = deque([(i,j)])\n grid[i][j] = \'#\'\n \n while q:\n r, c = q.popleft()\n for x, y in directions:\n nr = r +x\n nc = c +y\n \n if nr>=0 and nr< len(grid) and nc >=0 and nc <len(grid[0]) and grid[nr][nc]==\'1\':\n q.append((nr, nc))\n grid[nr][nc]= \'#\'\n count +=1\n \n return count\n``` | 5 | 0 | ['Python'] | 0 |
number-of-closed-islands | Java. BFS. Island search. | java-bfs-island-search-by-red_planet-77kk | \n\nclass Solution {\n public int isIsland(int []ij, int[][] grid)\n {\n boolean yes = true;\n int [][]moves = new int[][]{{1,0}, {-1,0}, {0 | red_planet | NORMAL | 2023-04-06T20:03:29.103064+00:00 | 2023-04-06T20:03:29.103097+00:00 | 308 | false | \n```\nclass Solution {\n public int isIsland(int []ij, int[][] grid)\n {\n boolean yes = true;\n int [][]moves = new int[][]{{1,0}, {-1,0}, {0,1}, {0,-1}};\n LinkedList<int[]> island = new LinkedList<>();\n island.add(ij);\n grid[ij[0]][ij[1]] = 2;\n int []cur;\n while (island.size() > 0)\n {\n cur = island.getFirst();\n island.removeFirst();\n for (int [] m: moves)\n {\n int tmp = grid[cur[0] + m[0]][cur[1] + m[1]];\n if (tmp == -2) yes = false;\n else if (tmp == 0) {\n island.add(new int[]{cur[0] + m[0], cur[1] + m[1]});\n grid[cur[0] + m[0]][cur[1] + m[1]] = 2;\n }\n }\n }\n if (yes) return 1;\n return 0;\n }\n public void borders(int[][] grid)\n {\n for (int i = 0; i < grid[0].length; i++) {\n if (grid[0][i] == 1) grid[0][i] = -1;\n else grid[0][i] = -2;\n if (grid[grid.length - 1][i] == 1) grid[grid.length - 1][i] = -1;\n else grid[grid.length - 1][i] = -2;\n }\n for (int i = 0; i < grid.length; i++) {\n if (grid[i][0] == 1) grid[i][0] = -1;\n else grid[i][0] = -2;\n if (grid[i][grid[0].length - 1] == 1) grid[i][grid[0].length - 1] = -1;\n else grid[i][grid[0].length - 1] = -2;\n }\n }\n\n public int closedIsland(int[][] grid) {\n int count = 0;\n borders(grid);\n for (int i = 1; i < grid.length - 1; i++)\n {\n for (int j = 1; j < grid[0].length - 1; j++)\n {\n if (grid[i][j] == 0)\n count += isIsland(new int[]{i,j}, grid);\n }\n }\n return count;\n }\n}\n``` | 4 | 0 | ['Java'] | 0 |
number-of-closed-islands | JAVA || 100% || easy hai re yeh soln dekh le samjh jayega | java-100-easy-hai-re-yeh-soln-dekh-le-sa-yhgn | Intuition \n Describe your first thoughts on how to solve this problem. \n1. dekh bahi har ek index pe iterate karna hai\n2. if 0 aaya toh check karenge agar is | ankitmaurya- | NORMAL | 2023-04-06T12:22:35.524623+00:00 | 2023-04-06T12:22:35.524666+00:00 | 151 | false | # Intuition \n<!-- Describe your first thoughts on how to solve this problem. -->\n1. dekh bahi har ek index pe iterate karna hai\n2. if 0 aaya toh check karenge agar iska network end me(0 ,grid.length-1) join hota hai toh toh bhai wo island nahi hai\n3. aur jidhar jidhar jayega mark chor ke janeka\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. if i,j==0 || grid.length-1 hai toh mat chala phukat time waste hai \n2. if i+1 ,i-1 ,j+1 ,j-1 se poritve news aata hai means island surrended hai water ke toh usko count kar le\n# Complexity\n- Time complexity:O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public static boolean travel(int[][] grid,int i,int j){\n if(grid[i][j]==1)return true;\n grid[i][j]=1;\n if(i==0 || j==0 || i==grid.length-1 || j==grid[0].length-1){\n return false;\n }\n boolean one=travel(grid,i+1,j);\n boolean two=travel(grid,i-1,j);\n boolean three=travel(grid,i,j+1);\n boolean four=travel(grid,i,j-1);\n return (one && two && three && four);\n }\n public int closedIsland(int[][] grid) {\n int count=0;\n for(int i=1;i<grid.length-1;i++){\n for(int j=1;j<grid[0].length-1;j++){\n if(grid[i][j]==0){\n if(travel(grid,i,j)){\n count++;\n }\n }\n }\n }\n return count;\n }\n}\n``` | 4 | 0 | ['Java'] | 1 |
number-of-closed-islands | c++ easy solution using bfs method | c-easy-solution-using-bfs-method-by-pooj-085u | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\nBFS method\n\n# Complexity\n- Time complexity:\nNear to O(nm)\n\n- Space | pooja_9154 | NORMAL | 2023-04-06T10:44:54.260379+00:00 | 2023-04-06T10:46:17.716390+00:00 | 537 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nBFS method\n\n# Complexity\n- Time complexity:\nNear to O(nm)\n\n- Space complexity:\nO(nm)+space taken by queue(O(n))\n\n# Code\n```\nclass Solution {\npublic:\nvoid bfs(int x,int y,vector<vector<int>>&vis,vector<vector<int>>&grid){\n int n=grid.size();\n int m=grid[0].size();\n \n queue<pair<int,int>>q;\n q.push({x,y});\n vis[x][y]=1;\n \n \n int delr[]={-1,0,1,0};\n int delc[]={0,-1,0,1};\n while(!q.empty()){\n int row=q.front().first;\n int col=q.front().second;\n q.pop();\n for(int i=0;i<4;i++){\n int r=row+delr[i];\n int c=col+delc[i];\n if(r>=0 && r<n && c>=0 && c<m && !vis[r][c] && grid[r][c]==0){\n q.push({r,c});\n vis[r][c]=1;\n }\n }\n }\n\n}\n int closedIsland(vector<vector<int>>& grid) {\n int n=grid.size();\n int m=grid[0].size();\n vector<vector<int>>vis(n,vector<int>(m,0));\n for(int i=0;i<n;i++){\n for(int j=0;j<m;j++){\n if(i==0 || i==n-1 || j==0 || j==m-1){\n if(!vis[i][j] && grid[i][j]==0){\n bfs(i,j,vis,grid);\n }\n }\n \n } \n }\n int cnt=0;\n for(int i=0;i<n;i++){\n for(int j=0;j<m;j++){\n if(!vis[i][j] && grid[i][j]==0){\n cnt++;\n bfs(i,j,vis,grid);\n }\n }\n }\n return cnt;\n\n }\n};\n``` | 4 | 0 | ['Breadth-First Search', 'Queue', 'C++'] | 3 |
number-of-closed-islands | Two Unique Solutions Using DFS and Union Find | two-unique-solutions-using-dfs-and-union-hmfe | Readable Names and Self Explanatory if both concepts known.\n# Code Using DFS\n\nclass Solution {\npublic:\n vector<vector<bool>>visited;\n vector<int>add | Heisenberg2003 | NORMAL | 2023-04-06T05:35:53.596853+00:00 | 2023-04-06T05:39:19.298129+00:00 | 1,650 | false | Readable Names and Self Explanatory if both concepts known.\n# Code Using DFS\n```\nclass Solution {\npublic:\n vector<vector<bool>>visited;\n vector<int>adderx={0,0,1,-1};\n vector<int>addery={1,-1,0,0};\n void explore_area(vector<vector<int>>&grid,int i,int j)\n {\n for(int k=0;k<4;k++)\n {\n if((i+addery[k])<grid.size() && (i+addery[k])>=0 && (j+adderx[k])<grid[0].size() && (j+adderx[k])>=0 && grid[i+addery[k]][j+adderx[k]]==0 && !visited[i+addery[k]][j+adderx[k]])\n {\n visited[i+addery[k]][j+adderx[k]]=true;\n explore_area(grid,i+addery[k],j+adderx[k]);\n }\n }\n return;\n }\n int closedIsland(vector<vector<int>>&grid) \n {\n //Using DFS\n visited.assign(grid.size(),vector<bool>(grid[0].size(),false));\n int total_islands=0,boundary_islands=0;\n for(int i=0;i<grid.size();i++)\n {\n for(int j=0;j<grid[0].size();j++)\n {\n if(grid[i][j]==0 && !visited[i][j])\n {\n visited[i][j]=true;\n explore_area(grid,i,j);\n total_islands++;\n }\n }\n }\n visited.assign(grid.size(),vector<bool>(grid[0].size(),false));\n for(int i=0;i<grid.size();i++)\n {\n if(grid[i][0]==0 && !visited[i][0])\n {\n visited[i][0]=true;\n explore_area(grid,i,0);\n boundary_islands++;\n }\n if(grid[i][grid[0].size()-1]==0 && !visited[i][grid[0].size()-1])\n {\n visited[i][grid[0].size()-1]=true;\n explore_area(grid,i,grid[0].size()-1);\n boundary_islands++;\n }\n }\n for(int j=0;j<grid[0].size();j++)\n {\n if(grid[0][j]==0 && !visited[0][j])\n {\n visited[0][j]=true;\n explore_area(grid,0,j);\n boundary_islands++;\n }\n if(grid[grid.size()-1][j]==0 && !visited[grid.size()-1][j])\n {\n visited[grid.size()-1][j]=true;\n explore_area(grid,grid.size()-1,j);\n boundary_islands++;\n }\n }\n return (total_islands-boundary_islands);\n }\n};\n```\n# Code Using Union Find\n```\nclass Solution {\npublic:\n vector<int>parent,size;\n int m,n;\n void make(int i,int j)\n {\n parent[(n*i)+j]=(n*i)+j;\n size[(n*i)+j]=1;\n return;\n }\n int findparent(int var)\n {\n if(var==-1)\n {\n return -1;\n }\n if(parent[var]==var)\n {\n return var;\n }\n parent[var]=findparent(parent[var]);\n return parent[var];\n }\n void Union(int var1,int var2)\n {\n var1=findparent(var1);\n var2=findparent(var2);\n if(var1==var2)\n {\n return;\n }\n if(size[var1]>size[var2])\n {\n parent[var2]=var1;\n size[var1]+=size[var2];\n }\n else\n {\n parent[var1]=var2;\n size[var2]+=size[var1];\n }\n return;\n }\n int closedIsland(vector<vector<int>>& board) \n {\n //Using Union Find\n m=board.size();\n n=board[0].size();\n int i,j;\n parent.assign(m*n,-1);\n size.assign(m*n,0);\n for(i=0;i<m;i++)\n {\n for(j=0;j<n;j++)\n {\n if(board[i][j]==0)\n {\n make(i,j);\n }\n }\n }\n for(i=0;i<m;i++)\n {\n for(j=0;j<n;j++)\n {\n if(board[i][j]==0)\n {\n if(i>0 && board[i-1][j]==0)\n {\n Union(i*n+j,(i-1)*n+j);\n }\n if(j>0 && board[i][j-1]==0)\n {\n Union(i*n+j,i*n+j-1);\n }\n if(i<m-1 && board[i+1][j]==0)\n {\n Union(i*n+j,(i+1)*n+j);\n }\n if(j<n-1 && board[i][j+1]==0)\n {\n Union(i*n+j,i*n+j+1);\n }\n }\n }\n }\n for(i=0;i<parent.size();i++)\n {\n parent[i]=findparent(i);\n }\n unordered_set<int>connectedatedges,total;\n for(i=0;i<m;i++)\n {\n if(board[i][0]==0)\n {\n connectedatedges.insert(parent[i*n]);\n }\n if(board[i][n-1]==0)\n {\n connectedatedges.insert(parent[(i+1)*n-1]);\n }\n }\n for(j=0;j<n;j++)\n {\n if(board[0][j]==0)\n {\n connectedatedges.insert(parent[j]);\n }\n if(board[m-1][j]==0)\n {\n connectedatedges.insert(parent[(m-1)*n+j]);\n }\n }\n for(i=0;i<parent.size();i++)\n {\n if(parent[i]!=-1)\n {\n total.insert(parent[i]);\n }\n }\n return total.size()-connectedatedges.size();\n }\n};\n```\n | 4 | 1 | ['Depth-First Search', 'Union Find', 'Matrix', 'C++'] | 0 |
number-of-closed-islands | Easy C++ Solution || USING DFS | easy-c-solution-using-dfs-by-lakshya_12-2vtz | Intuition\n Describe your first thoughts on how to solve this problem. \nUpvote if its help!!\n\n# Approach\n Describe your approach to solving the problem. \nS | lakshya_12 | NORMAL | 2023-04-06T03:40:45.402505+00:00 | 2023-04-06T03:40:45.402562+00:00 | 850 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nUpvote if its help!!\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nSolving This question by Depth First Search (DFS)\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n void solve(int i, int j,int n, int m, vector<vector<int>>&grid, vector<vector<bool>>&vis, int &count)\n {\n if(i<0 || i>=n || j<0 || j>=m || grid[i][j]==1 || vis[i][j]==true) return;\n vis[i][j]=true;\n\n if(i==0 || j==0 || i==n-1 || j==m-1) count++;\n\n solve(i+1,j,n,m,grid,vis,count);\n solve(i,j+1,n,m,grid,vis,count);\n solve(i-1,j,n,m,grid,vis,count);\n solve(i,j-1,n,m,grid,vis,count);\n }\n int closedIsland(vector<vector<int>>& grid) {\n int n= grid.size();\n int m= grid[0].size();\n int ans=0;\n vector<vector<bool>>vis(n, vector<bool>(m));\n\n for(int i=0;i<n;i++)\n {\n for(int j=0;j<m;j++)\n {\n if(grid[i][j]==1 || vis[i][j]==true) continue;\n int count=0;\n solve(i,j,n,m,grid,vis,count);\n\n if(count==0) ans++; \n }\n }\n return ans;\n }\n};\n``` | 4 | 0 | ['Depth-First Search', 'Graph', 'C++'] | 0 |
number-of-closed-islands | C++ || Beats 89% || simple brute force Explained💯 | c-beats-89-simple-brute-force-explained-3vqh8 | \n# Approach\n Describe your approach to solving the problem. \n- Make a vis2DArray initialise it with 0\n- Find cells having 0 (land) in the grid from two Loop | wasim_khan0101 | NORMAL | 2022-12-30T09:34:36.428696+00:00 | 2022-12-30T09:34:36.428732+00:00 | 608 | false | \n# Approach\n<!-- Describe your approach to solving the problem. -->\n- Make a **vis2DArray** initialise it with **0**\n- Find cells having 0 (land) in the grid from two Loops\n- Call dfs for that cell having 0 in the grid\n- **Check 4-direc if 0 is at the boundary return false After marking that piece of land in the vis array**\uD83E\uDD2F\n- DRY Run for better understanding\n\n\n\n# Code\n```\nclass Solution {\n private:\n void dfs(int row, int col, vector<vector<int>>& grid,vector<vector<int>>& vis, bool &check){\n\n vis[row][col]=1;\n int delrow[]={-1,0,1,0};\n int delcol[]={0,1,0,-1};\n int n = grid.size();\n int m = grid[0].size();\n\n for(int i =0; i<4; i++){\n int nrow = row+delrow[i];\n int ncol = col+delcol[i];\n if(nrow<0 || ncol<0 || nrow>=n || ncol>=m){\n check = false;\n }\n if(nrow>=0 && ncol>=0 && nrow<n && ncol<m && vis[nrow][ncol]!=1 \n && grid[nrow][ncol]==0){\n dfs(nrow,ncol,grid,vis,check);\n\n }\n \n }\n \n \n }\npublic:\n int closedIsland(vector<vector<int>>& grid) {\n int n = grid.size();\n int m = grid[0].size();\n int cnt =0;\n //visted 2d vector create\n vector<vector<int>>vis(n,vector<int>(m,0));\n \n \n for(int i =0; i<n; i++){\n for(int j = 0; j<m; j++){\n if(grid[i][j]==0 && vis[i][j] != 1){\n bool check =true;\n dfs(i, j, grid, vis,check);\n if(check)cnt++;\n }\n }\n }\n return cnt;\n }\n};\n```\n\n | 4 | 0 | ['C++'] | 3 |
number-of-closed-islands | Clean C++ solution using DFS with faster than 94.43% of C++ || With easy explanation of code | clean-c-solution-using-dfs-with-faster-t-k0ds | Logic\n\t1. First of all visit all the lands which are in boundary using DFS , i.e take a single 1 from the corner and stretch the spread in all 4 directions s | _D_I_V_A_K_A_R | NORMAL | 2022-06-07T01:42:07.692490+00:00 | 2022-07-27T17:51:54.899294+00:00 | 254 | false | **Logic**\n\t1. First of all ***visit all the lands which are in boundary using DFS*** , i.e take a single 1 from the corner and stretch the spread in **all 4 directions** so as to cover the boundaries and parallely **make\nthem visited** .\n\t2. As now we have covered all the islands which are in the corners, now our work is very simple,\n\t\twe **are left with zeroes which are inside the boundary islands**\n\t\tSo **now go and count and once a spread of 0 is done** , **make them as visited** .\n\n* At **last the count intern means that we have counted only those who have a closed boundary/island**\n\n***CODE***\n```\nclass Solution {\npublic:\n int res=0;\n int closedIsland(vector<vector<int>>& grid) {\n if(grid.empty())\n return 0;\n int m = grid.size();\n \t\tint n = grid[0].size();\n\t\t\n\t\t// Visited array \n vector<vector<bool>>vis(m, vector<bool>(n, false));\n for(int i=0;i<m;i++){\n for(int j=0;j<n;j++){\n if(j==0||j==n-1||i==0||i==m-1) \n\t\t\t\t\t// only the boundaries ones are to be chosen and send it to DFS.\n dfs(grid,vis,i,j,m,n);\n }\n }\n \n for(int i=0;i<m;i++){\n for(int j=0;j<n;j++){\n if(grid[i][j] == 0 && !vis[i][j]){\n\t\t\t\t\t// Only those who are zeroes and not visited till\n dfs(grid,vis,i,j,m,n);\n\t\t\t\t\t// So after a complete spread of 0, then count \n res++; // gives the closed number of islands\n }\n }\n }\n return res;\n }\n void dfs(vector<vector<int>>& grid,vector<vector<bool>>& vis, int i, int j,int m,int n){\n // Base case\n\t // If its out of bounds and already visited, so do nothing just return.\n if(i<0||i>=m||j<0||j>=n||grid[i][j]==1||vis[i][j]){\n return ;\n }\n\t\t// make it as visited.\n vis[i][j]=true;\n \n // calling dfs in all the four directions. \n dfs(grid,vis,i+1,j,m,n);\n dfs(grid,vis,i-1,j,m,n);\n dfs(grid,vis,i,j+1,m,n);\n dfs(grid,vis,i,j-1,m,n);\n \n }\n};\n``` | 4 | 0 | ['Depth-First Search', 'C'] | 0 |
number-of-closed-islands | c++ || easy to understand || DFS | c-easy-to-understand-dfs-by-drishti1210-oxxl | \nclass Solution {\npublic:\n int n;\n int m;\n \n bool waterPresent(vector<vector<int>>& grid, int i, int j){\n if(grid[i][j])\n | drishti1210 | NORMAL | 2022-05-22T12:39:55.250061+00:00 | 2022-05-22T12:39:55.250094+00:00 | 218 | false | ```\nclass Solution {\npublic:\n int n;\n int m;\n \n bool waterPresent(vector<vector<int>>& grid, int i, int j){\n if(grid[i][j])\n return true;\n if(i <= 0 || i >= n-1 || j <= 0 || j >= m-1)\n\t\t\treturn false;\n grid[i][j] = 1;\n\t\tbool l = waterPresent(grid, i, j-1);\n\t\tbool r = waterPresent(grid, i, j+1);\n\t\tbool up = waterPresent(grid, i-1, j);\n\t\tbool down = waterPresent(grid, i+1, j);\n\t\treturn (l&&r&&up&&down);\n \n }\n \n int closedIsland(vector<vector<int>>& grid) {\n n= grid.size();\n m= grid[0].size();\n int ans=0;\n for(int i =1 ;i<n-1;i++){\n for(int j =1;j<m-1;j++){\n if(grid[i][j]==0 && waterPresent(grid, i, j))\n ++ans;\n }\n }\n return ans;\n }\n};\n``` | 4 | 1 | ['Depth-First Search', 'Graph', 'C', 'C++'] | 0 |
number-of-closed-islands | Java Easy Self Expalantory | java-easy-self-expalantory-by-bharat194-s62p | \nclass Solution {\n public int closedIsland(int[][] grid) {\n int res = 0;\n for(int i=0;i<grid.length;i++){\n if(grid[i][0] == 0) | bharat194 | NORMAL | 2022-03-25T05:17:59.469532+00:00 | 2022-03-25T05:17:59.469569+00:00 | 201 | false | ```\nclass Solution {\n public int closedIsland(int[][] grid) {\n int res = 0;\n for(int i=0;i<grid.length;i++){\n if(grid[i][0] == 0) dfs(grid,i,0);\n if(grid[i][grid[0].length-1] == 0) dfs(grid,i,grid[0].length-1);\n }\n for(int i=0;i<grid[0].length;i++){\n if(grid[0][i] == 0) dfs(grid,0,i);\n if(grid[grid.length-1][i] == 0) dfs(grid,grid.length-1,i);\n }\n for(int i=1;i<grid.length-1;i++)\n for(int j=1;j<grid[0].length-1;j++){\n if(grid[i][j] == 0){\n dfs(grid,i,j);\n res++;\n }\n }\n return res;\n }\n public void dfs(int[][] grid, int i ,int j){\n if(i<0 || j<0 || i>=grid.length || j>=grid[0].length || grid[i][j] == 1) return;\n grid[i][j] = 1;\n dfs(grid,i-1,j);\n dfs(grid,i,j+1);\n dfs(grid,i+1,j);\n dfs(grid,i,j-1);\n }\n}\n``` | 4 | 0 | ['Java'] | 0 |
number-of-closed-islands | Simple c++ soution | simple-c-soution-by-amartya_k-zlpv | \nint closedIsland(vector<vector<int>>& grid) {\n int count=0;\n bool flag;\n \n for(int i=1;i<grid.size()-1;i++){\n \n | amartya_k | NORMAL | 2022-03-19T05:47:40.077241+00:00 | 2022-03-19T05:47:40.077287+00:00 | 258 | false | ```\nint closedIsland(vector<vector<int>>& grid) {\n int count=0;\n bool flag;\n \n for(int i=1;i<grid.size()-1;i++){\n \n for(int j=1;j<grid[0].size()-1;j++){\n if(grid[i][j]==0){\n flag=false;\n dfs(grid,i,j,flag);\n if(!flag)\n count++;\n }\n }\n }\n return count;\n }\n \n void dfs(vector<vector<int>>& grid,int r,int c, bool &flag){\n if(r<0 || c<0 || r>=grid.size() || c>=grid[0].size() || grid[r][c]!=0){\n return;\n }\n if((r==0|| c==0 || r== grid.size()-1 || c==grid[0].size()-1) && grid[r][c]==0 && flag==false){\n flag=true;\n }\n \n grid[r][c]=1;\n \n dfs(grid,r+1,c,flag);\n dfs(grid,r-1,c,flag);\n dfs(grid,r,c+1,flag);\n dfs(grid,r,c-1,flag);\n }\n``` | 4 | 0 | ['Depth-First Search', 'C', 'C++'] | 1 |
number-of-closed-islands | [Python3] DFS - logic operator - easy undestanding | python3-dfs-logic-operator-easy-undestan-puhw | \ndef closedIsland(self, grid: List[List[int]]) -> int:\n m, n = len(grid), len(grid[0])\n closed_island = 0\n \n def dfs(row: int, | dolong2110 | NORMAL | 2021-12-22T17:12:49.293628+00:00 | 2021-12-22T17:12:49.293659+00:00 | 123 | false | ```\ndef closedIsland(self, grid: List[List[int]]) -> int:\n m, n = len(grid), len(grid[0])\n closed_island = 0\n \n def dfs(row: int, col: int) -> bool:\n if row < 0 or row >= m or col < 0 or col >= n:\n return False\n \n if grid[row][col] == 1:\n return True\n \n grid[row][col] = 1\n \n top = dfs(row - 1, col)\n down = dfs(row + 1, col)\n left = dfs(row, col - 1)\n right = dfs(row, col + 1)\n \n return top and down and left and right\n \n for i in range(m):\n for j in range(n):\n if grid[i][j] == 0:\n closed_island += dfs(i, j)\n \n return closed_island\n``` | 4 | 1 | ['Depth-First Search', 'Recursion', 'Python', 'Python3'] | 0 |
number-of-closed-islands | C++ | DFS on boundary | Approach Explained | c-dfs-on-boundary-approach-explained-by-hpk78 | Approach-We apply dfs on boundary and mark all boundary Os and its connected components as -1(to recognize they are visited). Now,the matrix consists of only th | nidhi_ranjan | NORMAL | 2021-10-01T18:24:45.828308+00:00 | 2021-10-01T18:26:06.752343+00:00 | 412 | false | Approach-We apply dfs on boundary and mark all boundary Os and its connected components as -1(to recognize they are visited). Now,the matrix consists of only those Os that are surrounded by water.So, we perform dfs on the matrix and find the number of connected components.\n```\nclass Solution {\npublic:\n void dfs(int i,int j,vector<vector<int>>& grid){\n int m=grid.size(),n=grid[0].size();\n if(i<0 ||i>m-1 || j<0 || j>n-1 || grid[i][j]!=0) return;\n grid[i][j]=-1;\n dfs(i-1,j,grid);\n dfs(i,j-1,grid);\n dfs(i+1,j,grid);\n dfs(i,j+1,grid);\n }\n\n int closedIsland(vector<vector<int>>& grid) {\n int m=grid.size(),n=grid[0].size(),ans=0;\n for(int i=0;i<m;i++){\n for(int j=0;j<n;j++){\n if((i==0||j==0||i==m-1||j==n-1)&&grid[i][j]==0){\n dfs(i,j,grid);\n\n }\n }\n }\n for(int i=0;i<m;i++){\n for(int j=0;j<n;j++){\n if(grid[i][j]==0){\n dfs(i,j,grid);\n ans++;\n }\n }\n }\n return ans;\n }\n};\n```\nHope you found this useful :) | 4 | 0 | ['Depth-First Search', 'Recursion', 'C', 'C++'] | 0 |
number-of-closed-islands | Java simple BFS | java-simple-bfs-by-hobiter-ii09 | \nclass Solution {\n int[][] g;\n int m, n;\n boolean[][] vs;\n int[][] dir = new int[][]{{0, 1}, {1, 0}, {0, -1}, {-1, 0}};\n public int closedI | hobiter | NORMAL | 2020-06-29T03:06:05.865244+00:00 | 2020-06-29T03:06:05.865276+00:00 | 561 | false | ```\nclass Solution {\n int[][] g;\n int m, n;\n boolean[][] vs;\n int[][] dir = new int[][]{{0, 1}, {1, 0}, {0, -1}, {-1, 0}};\n public int closedIsland(int[][] grid) {\n g = grid;\n m = g.length; \n n = g[0].length;\n vs = new boolean[m][n];\n int res = 0;\n for (int i = 1; i < m - 1; i++) {\n for (int j = 1; j < n - 1; j++) {\n if (bfs(i, j)) res++;\n }\n }\n return res;\n }\n \n private boolean bfs(int i, int j) {\n if (g[i][j] != 0 || vs[i][j]) return false;\n vs[i][j] = true;\n Queue<int[]> q = new LinkedList<>();\n q.offer(new int[]{i, j});\n boolean res = true;\n while (!q.isEmpty()) {\n int[] curr = q.poll();\n for (int[] d : dir) {\n int r = curr[0] + d[0], c = curr[1] + d[1];\n if (r < 0 || r >= m || c < 0 || c >= n) {\n res = false;\n continue;\n }\n if (vs[r][c] || g[r][c] != 0) continue;\n vs[r][c] = true;\n q.offer(new int[]{r, c});\n }\n }\n return res;\n }\n}\n``` | 4 | 0 | [] | 0 |
number-of-closed-islands | Java, DFS, Union Find, explained | java-dfs-union-find-explained-by-gthor10-1x2r | In this problem we can use Union-Find structure which is usually faster then dfs. THe only catch w need to take care of is these land cells on the edge.\nFor ed | gthor10 | NORMAL | 2019-11-11T20:32:22.968193+00:00 | 2019-11-11T20:37:21.996264+00:00 | 722 | false | In this problem we can use Union-Find structure which is usually faster then dfs. THe only catch w need to take care of is these land cells on the edge.\nFor edge land I scan 0-th and last row and 0 and last column and mark land cell as water. For every land cell do dfs cause it could be a whole island connected to the edge.\nOnly after this step done we form our Union Find. Initialize it with count = number of land cells, when union any cell with existing one decrement the count. At the end count will have number of islands left after union operations. To speed-up UnionFind use ranks \n```\n int[][] g;\n\n public int closedIsland(int[][] grid) {\n g = grid;\n int rows = g.length, cols = g[0].length;\n //mark edge land cells as water cells\n for (int r = 0; r < rows; ++r) {\n dfs(r, 0);\n dfs(r, cols - 1);\n }\n for (int c = 1; c < cols - 1; ++c) {\n dfs(0, c);\n dfs(rows - 1, c);\n }\n //init UF, now we can count the rest of islands without limit for the edge cells\n UnionFind uf = new UnionFind(g);\n //skip 0 and last row and column - we can\'t take land cell from there even if we meet one\n for (int r = 1; r < rows - 1; ++r) {\n for (int c = 1; c < cols - 1; ++c) {\n //if this is island - mark is as water and union neighbouring cells\n if (g[r][c] == 0) {\n g[r][c] = 1;\n int coord = r * cols + c;\n //check four neighbours\n if (r - 1 > 0 && g[r - 1][c] == 0)\n uf.union(coord, coord - cols);\n if (c - 1 > 0 && g[r][c - 1] == 0)\n uf.union(coord, coord- 1);\n if (r + 1 < rows - 1 && g[r + 1][c] == 0)\n uf.union(coord, coord + cols);\n if (c + 1 < cols - 1 && g[r][c + 1] == 0)\n uf.union(coord, coord + 1);\n }\n }\n }\n return uf.count;\n }\n\n\n void dfs(int r, int c) {\n if (g[r][c] == 0) {\n g[r][c] = 1;\n if (r > 0) dfs(r - 1, c);\n if (c > 0) dfs(r, c - 1);\n if (r < g.length - 1) dfs(r + 1, c);\n if (c < g[0].length - 1) dfs(r, c + 1);\n }\n }\n}\n\nclass UnionFind {\n int[] parent;\n int count = 0;\n int ranks[];\n\n UnionFind(int[][] g) {\n int rows = g.length, cols = g[0].length;\n parent = new int[rows * cols];\n for (int r = 0; r < rows; ++r) {\n for (int c = 0; c < cols; ++c) {\n if (g[r][c] == 0) {\n int i = (r * cols) + c;\n parent[i] = i;\n count++;\n }\n }\n }\n ranks = new int[rows * cols];\n }\n\n int find(int n) {\n if (n != parent[n])\n parent[n] = find(parent[n]);\n return parent[n];\n }\n\n void union(int a, int b) {\n int rootA = find(a);\n int rootB = find(b);\n\n if (rootA != rootB) {\n if (ranks[rootA] > ranks[rootB]) {\n parent[rootB] = rootA;\n } else if (ranks[rootB] > ranks[rootA]) {\n parent[rootA] = rootB;\n } else {\n parent[rootA] = rootB;\n ranks[rootB] += 1;\n }\n count--;\n }\n }\n}\n``` | 4 | 0 | ['Depth-First Search', 'Union Find', 'Java'] | 1 |
number-of-closed-islands | Simple DFS Solution with comments | simple-dfs-solution-with-comments-by-man-e241 | We do a simple dfs for the 0s which are at the boundary of the grid and mark them by changing their value to -2.\nNow we call dfs using the function func in the | manrajsingh007 | NORMAL | 2019-11-10T04:04:55.165381+00:00 | 2019-11-10T04:34:15.719335+00:00 | 524 | false | We do a simple dfs for the 0s which are at the boundary of the grid and mark them by changing their value to -2.\nNow we call dfs using the function func in the code to get the number of islands which are surrounded by water on all sides. While doing this we also mark the cells as visited by making cell value as -1.\n```\nclass Solution {\n \n public static boolean func(int[][] grid, int n, int m, int i, int j){\n \n // either you reached a boundary 0 or went out of the cell\n if(i == - 1 || j == -1 || i == n || j == m || grid[i][j] == -2) return false;\n \n // you landed at the same cell that was visited earlier or you landed on a water cell\n if(grid[i][j] == -1 || grid[i][j] == 1) return true;\n \n // mark current element with -1 so that you don\'t revisit it\n grid[i][j] = -1;\n \n return func(grid, n, m, i, j - 1) && func(grid, n, m, i, j + 1) && func(grid, n, m, i - 1, j) && func(grid, n, m, i + 1, j);\n \n }\n \n // do dfs for all the boundary cells with grid[i][j] == 0 and mark them.\n public static void dfs(int[][] grid, int n, int m, int i, int j){\n \n if(i < 0 || j < 0 || i == n || j == m || grid[i][j] == -2 || grid[i][j] == 1) return;\n \n grid[i][j] = -2;\n // mark boundary 0s by -2\n \n dfs(grid, n, m, i + 1, j);\n dfs(grid, n, m, i - 1, j);\n dfs(grid, n, m, i, j - 1);\n dfs(grid, n, m, i, j + 1);\n return ;\n \n }\n \n public int closedIsland(int[][] grid) {\n \n int n = grid.length;\n if(n == 0) return 0;\n int m = grid[0].length;\n \n int count = 0;\n \n // mark all the boundary 0s\n for(int i = 0; i < n; i++) dfs(grid, n, m, i, 0);\n for(int i = 0; i < n; i++) dfs(grid, n, m, i, m - 1);\n for(int i = 0; i < m; i++) dfs(grid, n, m, 0, i);\n for(int i = 0; i < m; i++) dfs(grid, n, m, n - 1, i);\n \n for(int i = 0; i < n; i++){\n for(int j = 0; j < m; j++){\n // perform dfs by calling func on only those 0s which weren\'t marked while dfs of boundary 0s.\n if(grid[i][j] == 0 && func(grid, n, m, i, j)) count ++;\n }\n }\n \n return count;\n \n }\n} | 4 | 3 | ['Depth-First Search', 'Java'] | 2 |
number-of-closed-islands | 💢☠💫Easiest👾Faster✅💯 Lesser🧠 🎯 C++✅Python3🐍✅Java✅C✅Python🐍✅C#✅💥🔥💫Explained☠💥🔥 Beats 100 | easiestfaster-lesser-cpython3javacpython-q30y | \n\n# Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n\n Describe your first thoughts on how to solve this problem. \n- J | Edwards310 | NORMAL | 2024-11-29T13:08:52.262868+00:00 | 2024-11-29T13:08:52.262902+00:00 | 134 | false | \n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n\n<!-- Describe your first thoughts on how to solve this problem. -->\n- ***JavaScript Code -->*** https://leetcode.com/problems/number-of-closed-islands/submissions/1465775177\n- ***C++ Code -->*** https://leetcode.com/problems/number-of-closed-islands/submissions/1465493299\n- ***Python3 Code -->*** https://leetcode.com/problems/number-of-closed-islands/submissions/1465500662\n- ***Java Code -->*** https://leetcode.com/problems/number-of-closed-islands/submissions/1465495883\n- ***C Code -->*** https://leetcode.com/problems/number-of-closed-islands/submissions/1465509394\n- ***Python Code -->*** https://leetcode.com/problems/number-of-closed-islands/submissions/1465499684\n- ***C# Code -->*** https://leetcode.com/problems/number-of-closed-islands/submissions/1465769385\n- ***Go Code -->*** https://leetcode.com/problems/number-of-closed-islands/submissions/1465777243\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n O(N * M)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n O(N * M)\n\n | 3 | 0 | ['Depth-First Search', 'C', 'Matrix', 'Python', 'C++', 'Java', 'Go', 'Python3', 'JavaScript', 'C#'] | 0 |
number-of-closed-islands | Detailed Solution for beginners 🤗🤗🤗🤗 | detailed-solution-for-beginners-by-utkar-hgpi | Welcome, Keep working hard and thank you for visiting \uD83E\uDD17\uD83E\uDD17\n\nNow, on to the solution \u23ED\uFE0F\n# Approach\n 1. Mark Water at the Border | utkarshpriyadarshi5026 | NORMAL | 2024-05-08T18:56:23.538966+00:00 | 2024-05-08T18:56:23.538995+00:00 | 34 | false | # Welcome, Keep working hard and thank you for visiting \uD83E\uDD17\uD83E\uDD17\n\nNow, on to the solution \u23ED\uFE0F\n# Approach\n 1. **Mark Water at the Borders**\nFirst, we need to ensure that any 0s connected to the grid\'s border are marked as water (`1`), because these are not part of any closed island.\n\n ```\n private void visitAllIslandsAtBorder(int[][] grid) {\n int rows = grid.length;\n int cols = grid[0].length;\n\n // Loop through each cell at the grid\'s borders\n for (int i = 0; i < rows; i++) {\n for (int j = 0; j < cols; j++) {\n boolean isBorder = i == 0 || i == rows - 1 || j == 0 || j == cols - 1;\n if (isBorder && grid[i][j] == 0)\n dfs(i, j, grid, rows, cols); // Use DFS to mark connected `0`s as `1`s\n }\n }\n }\n ```\n2. **Implement DFS for Marking**\nThe dfs function is used to explore the grid and mark parts of the grid as water. It will recursively visit all neighboring cells that are land (`0`) and convert them to water (`1`).\n\n ```\n private void dfs(int x, int y, int[][] grid, int rows, int cols) {\n boolean outside = x < 0 || x >= rows || y < 0 || y >= cols;\n if (outside || grid[x][y] == 1)\n return;\n\n grid[x][y] = 1; // Mark the current cell as visited/water\n int[][] directions = { { 0, 1 }, { 1, 0 }, { 0, -1 }, { -1, 0 } };\n\n for (int[] dir : directions) {\n dfs(x + dir[0], y + dir[1], grid, rows, cols); // Visit all 4 neighboring cells\n }\n }\n\n ```\n\n3. **Count and Mark Closed Islands**\nAfter marking all `0s` connected to borders as `1`, the remaining `0s` represent closed islands. We can count and mark these islands using another round of DFS.\n\n ```\n private int getClosedIslands(int[][] grid) {\n int rows = grid.length;\n int cols = grid[0].length;\n int closedIslands = 0;\n\n for (int i = 0; i < rows; i++) {\n for (int j = 0; j < cols; j++) {\n if (grid[i][j] == 0) { // Found an unvisited island\n dfs(i, j, grid, rows, cols); // Mark the entire island\n closedIslands++; // Increment the count of closed islands\n }\n }\n }\n return closedIslands;\n }\n ```\n\n\n# Complexity\n- Time complexity:\n$$O(n \\times m)$$ - The time complexity of this solution is O$$(n \\times m)$$, where `n` is the number of rows and `m` is the number of columns in the grid. This complexity is due to the fact that the solution potentially requires visiting every cell \uD83D\uDFE2 in the grid:\n\n- Space complexity:\n$$O(n \\times m)$$ - The space complexity is $$O(n \\times m)$$ due to the recursive depth of the DFS potentially reaching the total number of cells in the grid in the worst-case scenario \uD83D\uDE2D (a completely filled grid without any actual barriers). The space is utilized by the call stack during the recursive calls of DFS\n\n# Code\n```\nclass Solution {\n public int closedIsland(int[][] grid) {\n visitAllIslandsAtBorder(grid);\n return getClosedIslands(grid);\n }\n\n private void dfs(int x, int y, int[][] grid, int rows, int cols) {\n\n boolean outside = x < 0 || x >= rows || y < 0 || y >= cols;\n if (outside || grid[x][y] == 1)\n return;\n\n grid[x][y] = 1;\n int[][] directions = { { 0, 1 }, { 1, 0 }, { 0, -1 }, { -1, 0 } };\n\n for (int[] dir : directions) {\n int dx = dir[0];\n int dy = dir[1];\n dfs(x + dx, y + dy, grid, rows, cols);\n }\n }\n\n private void visitAllIslandsAtBorder(int[][] grid) {\n int rows = grid.length;\n int cols = grid[0].length;\n\n for (int i = 0; i < rows; i++) {\n for (int j = 0; j < cols; j++) {\n boolean isBorder = i == 0 || i == rows - 1 || j == 0 || j == cols - 1;\n\n if (isBorder && grid[i][j] == 0)\n dfs(i, j, grid, rows, cols);\n }\n }\n }\n\n private int getClosedIslands(int[][] grid) {\n int rows = grid.length;\n int cols = grid[0].length;\n\n int closedIslands = 0;\n for (int i = 0; i < rows; i++) {\n for (int j = 0; j < cols; j++) {\n if (grid[i][j] == 1)\n continue;\n dfs(i, j, grid, rows, cols);\n closedIslands++;\n }\n }\n\n return closedIslands;\n }\n\n}\n``` | 3 | 0 | ['Depth-First Search', 'Graph', 'Matrix', 'Java'] | 0 |
number-of-closed-islands | Easy Union Find Approach | easy-union-find-approach-by-anupsingh556-gxod | Intuition\nCreate Union of all connected water bodies and land bodies then remove those land bodies which are connected with borders.\n\n\n# Code\n\nclass Solut | anupsingh556 | NORMAL | 2024-03-26T18:00:33.887369+00:00 | 2024-03-26T18:00:33.887401+00:00 | 7 | false | # Intuition\nCreate Union of all connected water bodies and land bodies then remove those land bodies which are connected with borders.\n\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> p;\n int findP(int a){\n if(p[a]==a)return a;\n return findP(p[a]);\n }\n\n void merge(int a, int b) {\n int pa = findP(a);\n int pb = findP(b);\n p[pb] = pa;\n }\n int closedIsland(vector<vector<int>>& g) {\n int n = g.size();\n int m = g[0].size();\n vector<int> tmp;\n for(int i=0;i<m*n;i++)tmp.push_back(i);\n p=tmp;\n for(int i=0;i<n;i++) {\n for(int j=0;j<m;j++) {\n int val = i*m+j;\n if((i+1)<n && g[i][j] == g[i+1][j])merge(val, i*m+m+j);\n if((i-1)>=0 && g[i][j] == g[i-1][j])merge(val, i*m-m+j);\n if((j+1)<m && g[i][j] == g[i][j+1])merge(val, i*m+1+j);\n if((j-1)>=0 && g[i][j] == g[i][j-1])merge(val, i*m-1+j);\n }\n }\n set<int> allPs;\n for(int i=0;i<m*n;i++) {\n int r = i/m;\n int c = i%m;\n if(g[r][c]==0)allPs.insert(findP(i));\n }\n\n //cout<<allPs.size();\n for(int i=0;i<m;i++) {\n int p = findP(i);\n allPs.erase(p);\n allPs.erase(findP((n-1)*m + i));\n }\n\n for(int i=0;i<n;i++) {\n int p = findP(i*m);\n allPs.erase(p);\n allPs.erase(findP((i+1)*m-1));\n }\n\n return allPs.size();\n }\n};\n``` | 3 | 0 | ['C++'] | 0 |
number-of-closed-islands | ✅Java Solution | 🚀2ms runtime | 🔥Depth First Search | 💚Beginner Friendly | java-solution-2ms-runtime-depth-first-se-lvtd | Approach\nTraverse the array and\n- First do Depth-First Search with elements 0 (i.e. land ) as boundarys and make them 1 as they are not our concern.\n- Secon | 5p7Ro0t | NORMAL | 2023-04-09T19:09:05.088991+00:00 | 2023-04-09T19:09:31.649419+00:00 | 200 | false | # Approach\nTraverse the array and\n- First do Depth-First Search with elements `0` (i.e. land ) as boundarys and make them `1` as they are not our concern.\n- Second do Depth-First Search on the remaining lands (`0`) that are present, they are not connected with boundary.\n\nand count each time we call dfs, so that much islands are present.\n# Complexity\n- Time complexity: O(mn)\n - Traversing each element one time.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int closedIsland(int[][] grid) {\n int ans = 0;\n int m = grid.length;\n int n = grid[0].length;\n for(int r = 0; r < m; r++){\n for(int c = 0; c < n; c++){\n if( (r == 0 || c == 0 || r == m-1 || c == n-1) && grid[r][c] == 0){\n dfs(grid,r,c);\n }\n }\n } \n for(int r = 0; r < m; r++){\n for(int c = 0; c < n; c++){\n if(grid[r][c] == 0){\n dfs(grid,r,c);\n ans++;\n }\n }\n }\n return ans;\n }\n public void dfs(int[][] grid,int r, int c){\n if(r < 0 || c < 0 || r >= grid.length || c >= grid[0].length){\n return;\n }\n if(grid[r][c] == 1){\n return;\n }\n grid[r][c] = 1;\n dfs(grid,r-1,c);\n dfs(grid,r,c-1);\n dfs(grid,r,c+1);\n dfs(grid,r+1,c);\n }\n}\n```\n\nPlease DO Upvote !!\n\nThank You :) | 3 | 0 | ['Depth-First Search', 'Matrix', 'Java'] | 2 |
number-of-closed-islands | ✅C++ Solution || Simple DFS || Queue(Iterative) || Explained and commented | c-solution-simple-dfs-queueiterative-exp-s4g3 | \n\n# Code\n\nclass Solution {\npublic:\n int closedIsland(vector<vector<int>>& grid) {\n int r=grid.size(),c=grid[0].size();\n int ans=0;\n | Devanshul | NORMAL | 2023-04-06T20:06:03.537589+00:00 | 2023-04-06T20:06:33.422961+00:00 | 60 | false | \n\n# Code\n```\nclass Solution {\npublic:\n int closedIsland(vector<vector<int>>& grid) {\n int r=grid.size(),c=grid[0].size();\n int ans=0;\n int dir_r[]={0,-1,0,1}; // Left,Up,Right,Down\n int dir_c[]={-1,0,1,0}; // Just for making directions easy \n vector<vector<bool>> vis(r,vector(c,false));\n\n for(int i=0;i<r;i++){\n for(int j=0;j<c;j++){\n if(grid[i][j]==1 || vis[i][j]){ // We dont have do anything if we encounter water or it is visited before\n continue;\n }\n queue<pair<int,int>> q;\n q.push({i,j});\n bool closed_land=true;\n while( !q.empty()){\n pair<int,int> present=q.front();\n q.pop();\n for(int d=0;d<4;d++){\n int qr = present.first + dir_r[d];\n int qc = present.second + dir_c[d]; \n if(qr < 0 || qr >= r || qc < 0 || qc >= c){ // Checking if its the corner or the edge land if it is that means its not closed land and we can just leave all the rest connected land as marked and make the closed land as false as its not closed\n closed_land=false;\n continue;\n }\n if(grid[qr][qc] == 1) continue; // If we found water then just we dont need to do anything \n if(vis[qr][qc]) continue; // If we already visited then why, so just continue \n q.push({qr,qc});\n vis[qr][qc] = true; // We visited the land so make it visited \n } \n } // When while ends that means all the connected land has be visited\n if(closed_land){\n ans++; // It means that all the connected land was closed by water\n }\n }\n }\n return ans; \n }\n};\n```\n\n | 3 | 0 | ['Graph', 'Queue', 'C++'] | 0 |
number-of-closed-islands | Explained approach and Easy solution in Java, C++ and JavaScript (beats 91%) | explained-approach-and-easy-solution-in-ug686 | Intuition\nThe function closedIsland takes a 2D grid as input and returns the number of closed islands in the grid. The function first initializes some variable | Aryan_rajput_ | NORMAL | 2023-04-06T17:57:53.392342+00:00 | 2023-04-06T17:57:53.392374+00:00 | 75 | false | # Intuition\nThe function closedIsland takes a 2D grid as input and returns the number of closed islands in the grid. The function first initializes some variables: rows and cols to store the dimensions of the grid, and closedIslands to store the count of closed islands.\n\nThe function then defines a helper function traverseIsland which recursively traverses an island starting from a given cell (row, col). The function returns false if the cell is out of bounds, true if the cell is water or has already been visited, and recursively checks the neighboring cells to see if they are water. If all neighboring cells are water, the function returns true to indicate that the island is closed.\n\nFinally, the function iterates over each cell in the grid, and if the cell is land and has not already been visited, it calls traverseIsland to check if the island is closed. If the island is closed, closedIslands is incremented. The function then returns the count of closed islands.\n\n# Approach\nInitialize variables for the number of rows, number of columns, and the number of closed islands.\nDefine a helper function called traverseIsland that takes in the current row and column indices and returns a boolean value indicating whether the island is closed or not.\nIn the traverseIsland function, check if the current row and column indices are within the bounds of the grid and if the cell is a water cell or if it has already been visited. If either of these conditions are true, return true.\nMark the current cell as visited by setting its value to 1.\nRecursively call the traverseIsland function for the four adjacent cells (up, down, left, and right).\nIf any of the adjacent cells is not part of a closed island (i.e., it is not surrounded by water on all sides), return false.\nIf all adjacent cells are part of a closed island, return true.\nTraverse the entire grid using two nested loops, checking if the cell is a land cell and if it is part of a closed island by calling the traverseIsland function.\nIncrement the closedIslands variable if the island is closed.\nReturn the number of closed islands.\n\n# Complexity\n- Time complexity: O(rows * cols)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(rows * cols)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# JavaScript Code\n```\n/**\n * @param {number[][]} grid\n * @return {number}\n */\nvar closedIsland = function(grid) {\n const rows = grid.length;\n const cols = grid[0].length;\n let closedIslands = 0;\n \n // Helper function to traverse the island and check if it is closed.\n function traverseIsland(row, col) {\n if (row < 0 || row >= rows || col < 0 || col >= cols) {\n return false; // Out of bounds.\n }\n if (grid[row][col] === 1) {\n return true; // Water or already visited.\n }\n grid[row][col] = 1; // Mark as visited.\n const left = traverseIsland(row, col - 1);\n const right = traverseIsland(row, col + 1);\n const up = traverseIsland(row - 1, col);\n const down = traverseIsland(row + 1, col);\n return left && right && up && down; // Check if all surrounding cells are water.\n }\n \n // Traverse the grid and count the number of closed islands.\n for (let i = 0; i < rows; i++) {\n for (let j = 0; j < cols; j++) {\n if (grid[i][j] === 0 && traverseIsland(i, j)) {\n closedIslands++;\n }\n }\n }\n \n return closedIslands;\n};\n\n```\n# Java Code\n```\nclass Solution {\n public int closedIsland(int[][] grid) {\n int rows = grid.length;\n int cols = grid[0].length;\n int closedIslands = 0;\n \n // Helper function to traverse the island and check if it is closed.\n boolean traverseIsland(int row, int col) {\n if (row < 0 || row >= rows || col < 0 || col >= cols) {\n return false; // Out of bounds.\n }\n if (grid[row][col] == 1) {\n return true; // Water or already visited.\n }\n grid[row][col] = 1; // Mark as visited.\n boolean left = traverseIsland(row, col - 1);\n boolean right = traverseIsland(row, col + 1);\n boolean up = traverseIsland(row - 1, col);\n boolean down = traverseIsland(row + 1, col);\n return left && right && up && down; // Check if all surrounding cells are water.\n }\n \n // Traverse the grid and count the number of closed islands.\n for (int i = 0; i < rows; i++) {\n for (int j = 0; j < cols; j++) {\n if (grid[i][j] == 0 && traverseIsland(i, j)) {\n closedIslands++;\n }\n }\n }\n \n return closedIslands;\n }\n}\n\n```\n# C++ Code\n```\nclass Solution {\npublic:\n int closedIsland(vector<vector<int>>& grid) {\n int rows = grid.size();\n int cols = grid[0].size();\n int closedIslands = 0;\n \n // Helper function to traverse the island and check if it is closed.\n bool traverseIsland(int row, int col) {\n if (row < 0 || row >= rows || col < 0 || col >= cols) {\n return false; // Out of bounds.\n }\n if (grid[row][col] == 1) {\n return true; // Water or already visited.\n }\n grid[row][col] = 1; // Mark as visited.\n bool left = traverseIsland(row, col - 1);\n bool right = traverseIsland(row, col + 1);\n bool up = traverseIsland(row - 1, col);\n bool down = traverseIsland(row + 1, col);\n return left && right && up && down; // Check if all surrounding cells are water.\n }\n \n // Traverse the grid and count the number of closed islands.\n for (int i = 0; i < rows; i++) {\n for (int j = 0; j < cols; j++) {\n if (grid[i][j] == 0 && traverseIsland(i, j)) {\n closedIslands++;\n }\n }\n }\n \n return closedIslands;\n }\n};\n\n``` | 3 | 0 | ['Array', 'Depth-First Search', 'C++', 'Java', 'JavaScript'] | 0 |
number-of-closed-islands | Simple dfs solution!! | simple-dfs-solution-by-venkataakhil4518-ikae | Code\n\nclass Solution:\n def closedIsland(self, grid: List[List[int]]) -> int:\n vis=defaultdict(lambda:False)\n n=len(grid)\n m=len(gr | venkataakhil4518 | NORMAL | 2023-04-06T17:28:04.104699+00:00 | 2023-04-06T17:28:04.104726+00:00 | 1,197 | false | # Code\n```\nclass Solution:\n def closedIsland(self, grid: List[List[int]]) -> int:\n vis=defaultdict(lambda:False)\n n=len(grid)\n m=len(grid[0])\n \'\'\'\n \'\'\'\n def dfs(x,y):\n vis[(x,y)]=True\n isedge=True\n for i,j in ((x+1,y),(x-1,y),(x,y+1),(x,y-1)):\n if 0<=i<n and 0<=j<m:\n if not vis[(i,j)] and (not grid[i][j]):\n isedge=(dfs(i,j) and isedge)\n else:\n isedge=(False and isedge)\n return isedge\n res=0\n for i in range(n):\n for j in range(m):\n if not vis[(i,j)] and (not grid[i][j]):\n if dfs(i,j):\n res+=1\n # print(vis)\n return res\n\n``` | 3 | 0 | ['Python', 'Python3'] | 1 |
number-of-closed-islands | DSU || C++ || Explained | dsu-c-explained-by-mikerufy-6hv3 | \n# Approach\n Describe your approach to solving the problem. \n\n\n\n\nPlease upvote :)\n\nIf its possible without using a set please share\n# Code\n\nclass So | mikerufy | NORMAL | 2023-04-06T17:17:46.581032+00:00 | 2023-04-06T17:17:46.581067+00:00 | 127 | false | \n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n\n\n\nPlease upvote :)\n\nIf its possible without using a set please share\n# Code\n```\nclass Solution {\npublic:\n vector<int> parent;\n vector<int> rank;\n // int x = 100005;\n void makeset(int x){\n for(int i=0;i<x;i++){\n parent[i] = i;\n rank[i] = 0;\n }\n }\n int findPar(int node){\n if(node == parent[node])\n return node;\n return parent[node] = findPar(parent[node]);\n }\n int hash(int i,int j,int m){\n return m*i + j;\n }\n void merge(int u,int v){\n u = findPar(u);\n v = findPar(v);\n if(rank[u]<rank[v]){\n parent[u] = v;\n }else if(rank[u] > rank[v]){\n parent[v] = u;\n }\n else{\n parent[v] = u;\n rank[u]++;\n }\n }\n int closedIsland(vector<vector<int>>& g) {\n int n = g.size();\n int m = g[0].size();\n parent.resize(n*m);\n rank.resize(n*m);\n makeset(n*m);\n for(int i=0;i<n;i++){\n for(int j=0;j<m;j++){\n if(g[i][j] == 0){\n if(i+1 < n and g[i+1][j]==0)merge(hash(i,j,m),hash(i+1,j,m));\n if(j+1 < m and g[i][j+1]==0)merge(hash(i,j,m),hash(i,j+1,m));\n }\n }\n }\n int cnt = 0;\n set<int> st;\n for(int i=1;i<n-1;i++)\n for(int j=1;j<m-1;j++){\n if(g[i][j]==0)st.insert(findPar(hash(i,j,m)));\n }\n\n for(int i=0;i<n;i++){\n if (g[i][0] == 0 and st.count(findPar(hash(i,0,m)))>0)st.erase(findPar(hash(i,0,m)));\n if (g[i][m - 1] == 0 and st.count(findPar(hash(i,m-1,m)))>0)st.erase(findPar(hash(i,m-1,m))); \n }\n for(int i=1;i<m-1;i++){\n if (g[0][i] == 0 and st.count(findPar(hash(0,i,m)))>0)st.erase(findPar(hash(0,i,m)));\n if (g[n-1][i] == 0 and st.count(findPar(hash(n-1,i,m)))>0)st.erase(findPar(hash(n-1,i,m))); \n }\n return st.size();\n }\n};\n``` | 3 | 0 | ['Union Find', 'C++'] | 1 |
number-of-closed-islands | Easy DFS solution 🔥 | In-depth explanation | various methods discussed (C++) | easy-dfs-solution-in-depth-explanation-v-vagn | Intuition\nIts a variation of a basic dfs problem where we need to count the number of islands (ie, group of 0s). But doing that here would result in overcounti | moinak878 | NORMAL | 2023-04-06T14:49:04.274178+00:00 | 2023-04-06T14:49:04.274221+00:00 | 114 | false | # Intuition\nIts a variation of a basic dfs problem where we need to count the number of islands (ie, group of `0`s). But doing that here would result in overcounting. `How do we solve this problem ?`\n\n# Approach\nThere can be two methods :-\n1) We can encorporate the boundary check condition in the dfs itself wherein we return true when we hit a boundary `1`. Now we need to check if all the directions(left,right,top,bottom) has returned true; and only then count it as a valid `closed island`.\n<br/>\n2) **[My Approach here]** We can see that the islands that are surrounded by an edge is causing the problem here. So we can solve it just by doing another dfs from the edge of the grid (where land is present) and set them as `1`s. So we dont end up overcounting them. <br/>\n## **To summarise :-**\n* Start from the edges , if you find a `0` start dfs and mark adjacent land as `1`. \n* Now you are only left with land that is not on the edge ie, has proper boundaries around it.\n* Iterate through the grid , do dfs if you find `0` that has not yet been visited. Increment your answer\n\n# Complexity\n- Time complexity:\n$$O(n^2)$$\n\n- Space complexity:\n$$O(n^2)$$\n\n# Code\n```\nclass Solution {\npublic:\n void dfs(int x , int y, vector<vector<bool>>& visited , vector<vector<int>>& grid){\n // add out of bound checks\n if(x<0 || x>=grid.size() || y<0 || y>=grid[0].size()) return;\n\n // checks if already visited\n if(grid[x][y] || visited[x][y]) return;\n\n // set visited as true\n visited[x][y]=true , grid[x][y]=1;\n\n // visit surrounding land\n dfs(x,y-1,visited,grid);\n dfs(x-1,y,visited,grid);\n dfs(x,y+1,visited,grid);\n dfs(x+1,y,visited,grid);\n }\n int closedIsland(vector<vector<int>>& grid) {\n int rows = grid.size();\n int columns = grid[0].size();\n\n vector<vector<bool>> visited(rows, vector<bool> (columns,false));\n\n int islands = 0;\n\n // lands on the edges causing problem , so start dfs from edges\' land and mark them as 1\n vector<vector<bool>> visitedEdge(rows, vector<bool> (columns,false));\n for(int i=0;i<rows;i++){\n for(int j=0;j<columns;j++){\n if(i==0||j==0||i==rows-1||j==columns-1){\n if(grid[i][j]==0 || !visitedEdge[i][j])\n dfs(i,j,visitedEdge,grid);\n }\n }\n }\n\n for(int i=0;i<rows;i++){\n for(int j=0;j<columns;j++){\n if(grid[i][j]==0 && !visited[i][j]){\n dfs(i,j,visited,grid);\n islands++;\n }\n }\n }\n\n return islands;\n }\n};\n``` | 3 | 0 | ['C++'] | 0 |
number-of-closed-islands | ✅Java||Full Explaination🔥||Comments||lBeginner Friendly🔥 | javafull-explainationcommentslbeginner-f-mx22 | Intuition\n Describe your first thoughts on how to solve this problem. \nFirst will make those land(0s) as water(1s) which are present in the boundary and simul | deepVashisth | NORMAL | 2023-04-06T11:28:22.866976+00:00 | 2023-04-06T11:39:08.432010+00:00 | 218 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFirst will make those land(0s) as water(1s) which are present in the boundary and simultanouelsy will make all land(0s) as water(1s) inside the boundary which are connected to boundary.\nThe reason why we are making all land(0s) as water(1s) which are present in the boundary because outside the boundary there are only water(1s) so no land exits.\nExample 1: \n```\n[1,1,1,1,1,1,1,0]\n[1,0,0,0,0,1,1,0]\n[1,0,1,0,1,1,1,0]\n[1,0,0,0,0,1,0,1]\n[1,1,1,1,1,1,1,0] \n```\nAfter converting land to water only for those which are at the boundary and inside\nAfter:\n```\n[1,1,1,1,1,1,1,1]\n[1,0,0,0,0,1,1,1]\n[1,0,1,0,1,1,1,1]\n[1,0,0,0,0,1,0,1]\n[1,1,1,1,1,1,1,1]\n```\nNow will apply DFS whenever will find a land in the matrix and recursively through DFS will traverse in all the four directions such as top, bottom, right, left untill be see that all near elements are 1. \n# Complexity\n- Time complexity: O(m*n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(m*n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n# Code\n```\nclass Solution {\n public int closedIsland(int[][] grid) {\n //we will first traverse only the boudaries of the matrix\n for(int i = 0 ; i < grid.length; i ++){\n for(int j = 0 ; j < grid[0].length; j ++){\n if(i == 0){\n boundary(grid,i,j);\n }\n if(j == 0){\n boundary(grid,i,j);\n }\n if(i == grid.length-1){\n boundary(grid,i,j);\n }\n if(j == grid[0].length-1){\n boundary(grid,i,j);\n }\n }\n }\n //we use count the store total land inside the matrix\n int count = 0;\n //now will traverse inside the matrix\n for(int i = 0 ; i < grid.length; i ++){\n for(int j = 0 ; j < grid[0].length; j ++){\n //if we found a land(0s) inside\n //we will make all land(0s) as water(1s) which are connected to that land\n //so that in future we just avoid counting it again as land\n //because land connected to one or many lands will be counted as 1 land \n if(grid[i][j] == 0){\n dfs(grid,i,j);\n count++;\n }\n }\n }\n return count;\n }\n public void boundary(int grid[][],int i,int j){\n //when we reach outside the boundary\n if(i < 0 || j < 0 || i >= grid.length || j >= grid[0].length){\n return ;\n }\n //if we found water(1s) then no need to traverse further\n if(grid[i][j] == 1){\n return ;\n }\n //will first mark the land as water and then move forward in all directions\n grid[i][j] = 1;\n boundary(grid,i-1,j);//top\n boundary(grid,i,j-1);//left\n boundary(grid,i+1,j);//bottom\n boundary(grid,i,j+1);//right\n }\n public void dfs(int grid[][],int i,int j){\n //when we reach outside the boundary\n if(i < 0 || j < 0 || i >= grid.length || j >= grid[0].length){\n return ;\n }\n //if we found water(1s) then no need to traverse further\n if(grid[i][j] == 1){\n return ;\n }\n //will first mark the land as water and then move forward in all directions\n grid[i][j] = 1;\n dfs(grid,i-1,j);//top\n dfs(grid,i,j-1);//left\n dfs(grid,i+1,j);//bottom\n dfs(grid,i,j+1);//right\n }\n}\n```\n**Please UpVote**\n**If you really found my solution helpful please upvote it, as it motivates me to post such kind of codes and help the coding community, if you have some queries or some improvements please feel free to comment and share your views.** | 3 | 0 | ['Matrix', 'Java'] | 2 |
number-of-closed-islands | Optimal Depth-First Search Solution for Counting Closed Islands in a 2D Grid | optimal-depth-first-search-solution-for-hkzb1 | \n\n# Approach\nIn this solution, we iterate over all the cells in the grid and check if it is an unvisited 0. If it is, we perform a depth-first search (DFS) o | priyanshu11_ | NORMAL | 2023-04-06T11:26:39.833434+00:00 | 2023-04-06T11:26:39.833465+00:00 | 73 | false | \n\n# Approach\nIn this solution, we iterate over all the cells in the grid and check if it is an unvisited 0. If it is, we perform a depth-first search (DFS) on the island to check if it is closed.\n\nThe DFS function dfs takes in the grid, the current cell\'s coordinates, and the dimensions of the grid. It returns a boolean value indicating whether the island is closed or not.\n\nIn the DFS function, we first check if we have reached the edge of the grid or water, in which case we return true or false respectively.\n\nOtherwise, we mark the current cell as visited and recursively call the DFS function on its neighboring cells. We keep track of whether all the neighboring cells are surrounded by water or not using four boolean variables.\n\nFinally, we return whether all the neighboring cells are surrounded by water. If they are, then the island is closed and we increment the count of closed islands.\n\n# Complexity\n- Time complexity:\nO(mn)\n\n- Space complexity:\nO(mn)\n\n# Code\n```\nclass Solution {\npublic:\n int closedIsland(vector<vector<int>>& grid) {\n int m = grid.size();\n int n = grid[0].size();\n int count = 0;\n \n for(int i = 0; i < m; i++) {\n for(int j = 0; j < n; j++) {\n // check for unvisited 0s\n if(grid[i][j] == 0) {\n // check if the island is closed\n if(dfs(grid, i, j, m, n)) {\n count++;\n }\n }\n }\n }\n \n return count;\n }\n \n bool dfs(vector<vector<int>>& grid, int i, int j, int m, int n) {\n // base cases\n if(i < 0 || i >= m || j < 0 || j >= n) {\n // reached the edge of the grid, island is not closed\n return false;\n }\n if(grid[i][j] == 1) {\n // reached water, island is not closed\n return true;\n }\n \n // mark the cell as visited\n grid[i][j] = 1;\n \n // dfs on neighboring cells\n bool left = dfs(grid, i, j-1, m, n);\n bool right = dfs(grid, i, j+1, m, n);\n bool up = dfs(grid, i-1, j, m, n);\n bool down = dfs(grid, i+1, j, m, n);\n \n // return whether all neighboring cells are surrounded by water\n return left && right && up && down;\n }\n};\n\n``` | 3 | 0 | ['Array', 'Depth-First Search', 'Matrix', 'C++', 'Java'] | 0 |
number-of-closed-islands | Python Elegant & Short | DFS | python-elegant-short-dfs-by-kyrylo-ktl-jrhp | Complexity\n- Time complexity: O(nm)\n- Space complexity: O(nm)\n\n# Code\n\nclass Solution:\n LAND = 0\n WATER = 1\n\n def closedIsland(self, grid: Li | Kyrylo-Ktl | NORMAL | 2023-04-06T07:42:17.337531+00:00 | 2023-04-06T07:42:34.020201+00:00 | 498 | false | # Complexity\n- Time complexity: $$O(n*m)$$\n- Space complexity: $$O(n*m)$$\n\n# Code\n```\nclass Solution:\n LAND = 0\n WATER = 1\n\n def closedIsland(self, grid: List[List[int]]) -> int:\n n, m = len(grid), len(grid[0])\n\n for row in range(n):\n self.water_island(row, 0, grid)\n self.water_island(row, m - 1, grid)\n\n for col in range(m):\n self.water_island( 0, col, grid)\n self.water_island(n - 1, col, grid)\n\n closed = 0\n for row in range(1, n - 1):\n for col in range(1, m - 1):\n if grid[row][col] == self.LAND:\n self.water_island(row, col, grid)\n closed += 1\n\n return closed\n\n @classmethod\n def water_island(cls, row: int, col: int, grid: List[List[int]]):\n if cls.in_bounds(row, col, grid) and grid[row][col] == cls.LAND:\n grid[row][col] = cls.WATER\n cls.water_island(row - 1, col, grid)\n cls.water_island(row + 1, col, grid)\n cls.water_island(row, col - 1, grid)\n cls.water_island(row, col + 1, grid)\n\n @staticmethod\n def in_bounds(row: int, col: int, grid: List[List[int]]) -> bool:\n return 0 <= row < len(grid) and 0 <= col < len(grid[0])\n\n``` | 3 | 0 | ['Depth-First Search', 'Python', 'Python3'] | 0 |
number-of-closed-islands | BFS SOLUTION || C++ SOLUTION || SAME AS NUMBER OF ISLANDS BUT WITH SOME EXTRA BOUNDARY CONDITIONS | bfs-solution-c-solution-same-as-number-o-42ck | \nSame as number of island problem but with some boundary conditions.\nUsed bfs for finding out the number of island.\n\n\nclass Solution {\npublic:\nbool take | _chintu_bhai | NORMAL | 2023-04-06T07:30:47.491923+00:00 | 2023-04-06T07:31:12.284635+00:00 | 375 | false | \nSame as number of island problem but with some boundary conditions.\nUsed bfs for finding out the number of island.\n\n```\nclass Solution {\npublic:\nbool take;\nvoid bfs(int i,int j,int trow,int tcol,vector<vector<int>>&vis,vector<vector<int>>& grid)\n{\n queue<pair<int,int>>q;\n q.push({i,j});\n while(!q.empty())\n {\n int x=q.front().first;\n int y=q.front().second;\n q.pop();\n vis[x][y]=1;\n int dx[]={-1,0,1,0};\n int dy[]={0,1,0,-1};\n for(int i=0;i<4;i++)\n {\n int nrow=x+dx[i];\n int ncol=y+dy[i];\n if(nrow<=trow&&ncol<=tcol&&nrow>=0&&ncol>=0&&vis[nrow][ncol]==0&&grid[nrow][ncol]==0)\n {\n vis[nrow][ncol]=1;\n if(nrow==0||nrow==trow||ncol==tcol||ncol==0)\n {\n take=false;\n }\n q.push({nrow,ncol});\n }\n }\n }\n}\n int closedIsland(vector<vector<int>>& grid) {\n int row=grid.size();\n int col=grid[0].size();\n int c=0;\n vector<vector<int>>vis(row,vector<int>(col,0));\n for(int i=1;i<row-1;i++)\n {\n for(int j=1;j<col-1;j++)\n {\n if(grid[i][j]==0&&vis[i][j]==0)\n {\n take=true;\n bfs(i,j,row-1,col-1,vis,grid);\n if(take)\n {\n c++;\n }\n }\n }\n }\n return c;\n }\n};\n```\nIF YOU FOUND THIS HELPFUL , PLEASE UPVOTE IT\uD83D\uDE4F\uD83D\uDE4F | 3 | 0 | ['Breadth-First Search', 'Graph', 'C++'] | 0 |
number-of-closed-islands | Java BFS solution | java-bfs-solution-by-darshan_behere-rwkd | Intuition\n Describe your first thoughts on how to solve this problem. \nFind all the island and if it touches border skip that island.\n\n# Approach\n Describe | Darshan_Behere | NORMAL | 2023-04-06T04:53:27.751608+00:00 | 2023-04-06T04:53:27.751653+00:00 | 229 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFind all the island and if it touches border skip that island.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. BFS to explore the grid\n2. If the grid[i][j] comes in the contact of border then flag=false\n3. If flag==true then count++\n\n# Complexity\n- Time complexity:O(m*n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(m*n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n static int[] dir = new int[]{1,0,-1,0,1};\n public int closedIsland(int[][] grid) {\n\n ArrayDeque<int[]> dq = new ArrayDeque<>();\n int count=0;\n for(int i=0;i<grid.length;i++){\n for(int j=0;j<grid[0].length;j++){\n if(grid[i][j]==0){\n dq.add(new int[]{i,j});\n boolean flag = true;\n while(!dq.isEmpty()){\n int[] t = dq.poll();\n if(t[0]==0 || t[0]==grid.length-1 || t[1]==0 || t[1]==grid[0].length-1)\n flag = false;\n grid[t[0]][t[1]]=3;\n for(int k=1;k<dir.length;k++){\n int a = t[0]+dir[k-1];\n int b = t[1]+dir[k];\n if(a<0 || a>=grid.length || b<0 || b>=grid[0].length || grid[a][b]>=1)\n continue;\n dq.add(new int[]{a,b});\n }\n }\n if(flag){\n count++;\n }\n }\n }\n }\n\n return count;\n }\n}\n``` | 3 | 0 | ['Java'] | 1 |
number-of-closed-islands | ✍ ✅ [PHP🚀 27ms Beats 100%][PHP][JavaScript 96.55%] Depth-First-Search Approach | php-27ms-beats-100phpjavascript-9655-dep-fhfy | \n# Approach\nThis approach uses depth-first-search to traverse through the grid and count the number of closed islands in the grid. \n\nWe check each cell of t | akunopaka | NORMAL | 2023-04-06T03:11:38.266089+00:00 | 2023-04-06T03:11:38.266115+00:00 | 256 | false | \n# Approach\nThis approach uses depth-first-search to traverse through the grid and count the number of closed islands in the grid. \n\nWe check each cell of the grid, if it is 0 (meaning land), then we perform a depth-first-search to check if it is a closed island or not. If it is a closed island, we increment the count of closed islands. \n\nTo check if the cell is a closed island, we perform a depth-first-search on it and check if all of its neighbors are 1 (meaning water). \n\nThe result is increased by 1 for each closed island found.\n\n# Complexity\n*Time complexity:* $$O(m * n)$$ - where m is the number of rows and n is the number of columns in the grid.\n*Space complexity:* $$O(m * n)$$ - since we use a recursive depth-first-search to traverse the grid.\n\n# Code\n\n```javascript []\nvar closedIsland = function (grid) {\n let result = 0;\n let rows = grid.length;\n let cols = grid[0].length;\n if (cols < 3 || rows < 3) return 0;\n let checkNeighbours = (i, j) => {\n if (i < 0 || i >= rows || j < 0 || j >= cols) {\n return false;\n }\n if (grid[i][j] === 1) {\n return true;\n }\n grid[i][j] = 1;\n let left = checkNeighbours(i, j - 1);\n let right = checkNeighbours(i, j + 1);\n let top = checkNeighbours(i - 1, j);\n let bottom = checkNeighbours(i + 1, j);\n return left && right && top && bottom;\n }\n\n for (let i = 1; i < rows - 1; i++) {\n for (let j = 1; j < cols - 1; j++) {\n if (grid[i][j] === 0) {\n result += checkNeighbours(i, j);\n }\n }\n }\n return result;\n};\n```\n```php []\nclass Solution\n{\n /**\n * @param Integer[][] $grid\n * @return Integer\n */\n function closedIsland(array $grid): int {\n $islandsCount = 0;\n $m = count($grid); // y\n $n = count($grid[0]); // x\n\n if ($m < 3 || $n < 3) return 0;\n\n for ($i = 1; $i < $m - 1; $i++) {\n for ($j = 1; $j < $n - 1; $j++) {\n if ($grid[$i][$j] === 0) {\n if ($this->checkNeighbours($grid, $i, $j)) {\n $islandsCount++;\n }\n }\n }\n }\n return $islandsCount;\n }\n\n function checkNeighbours(array &$grid, int $i, int $j): bool {\n if (!isset($grid[$i][$j])) return false;\n if ($grid[$i][$j] === 1) return true;\n\n $grid[$i][$j] = 1;\n\n $left = $this->checkNeighbours($grid, $i, $j - 1);\n $right = $this->checkNeighbours($grid, $i, $j + 1);\n $top = $this->checkNeighbours($grid, $i - 1, $j);\n $bottom = $this->checkNeighbours($grid, $i + 1, $j);\n\n return $left && $right && $top && $bottom;\n }\n}\n```\n\n##### Thanks for reading! If you have any questions or suggestions, please leave a comment below. I would love to hear your thoughts! \uD83D\uDE0A\n### **Please upvote if you found this post helpful! \uD83D\uDC4D** | 3 | 0 | ['Depth-First Search', 'PHP', 'JavaScript'] | 1 |
number-of-closed-islands | Easiest Solution | easiest-solution-by-code_ranvir25-gjid | Complexity\n- Time complexity:\nO(nm)\n\n- Space complexity:\nO(nm)\n\n# Code\n\nclass Solution {\n public int closedIsland(int[][] grid) {\n // Defin | cOde_Ranvir25 | NORMAL | 2023-04-06T02:52:02.541020+00:00 | 2023-04-06T02:52:02.541066+00:00 | 215 | false | # Complexity\n- Time complexity:\nO(n*m)\n\n- Space complexity:\nO(n*m)\n\n# Code\n```\nclass Solution {\n public int closedIsland(int[][] grid) {\n // Define the 4 directions to explore (up, down, left, right)\n int dirs[][]={{-1,0},{1,0},{0,-1},{0,1}};\n // Get the number of rows and columns in the grid\n int n=grid.length,m=grid[0].length;\n // Initialize a variable to count the number of closed islands\n int count=0;\n // Initialize a boolean array to mark visited cells\n boolean visited[][]=new boolean[n][m];\n // Create a queue to perform BFS\n Queue<int[]>q=new LinkedList();\n // Iterate through the grid\n for(int i=0;i<n;i++){\n for(int j=0;j<m;j++){\n // If the cell is land (0) and has not been visited yet\n if(grid[i][j]==0 && !visited[i][j]){\n // Add the cell to the queue and mark it as visited\n q.offer(new int[]{i,j});\n visited[i][j]=true;\n // Assume that the island is closed initially\n boolean closed=true;\n // Perform BFS to explore the island\n while(!q.isEmpty()){\n int pos[]=q.poll();\n int x=pos[0],y=pos[1];\n // Check if the cell is adjacent to the edge of the grid\n if(x==0||x==n-1||y==0||y==m-1){\n closed=false;\n }\n // Explore the neighboring cells\n for(int dir[]:dirs){\n int nx=x+dir[0],ny=y+dir[1];\n // If the neighboring cell is land (0) and has not been visited yet\n if(nx<n && nx>=0 && ny<m && ny>=0 && grid[nx][ny]==0 && !visited[nx][ny]){\n // Add the neighboring cell to the queue and mark it as visited\n q.offer(new int[]{nx,ny});\n visited[nx][ny]=true;\n }\n }\n }\n // If the island is closed, increment the count variable\n if(closed){\n count++;\n }\n }\n }\n }\n return count;\n }\n}\n\n```\n# Upvoting is much appreciated | 3 | 0 | ['Breadth-First Search', 'Queue', 'Java'] | 0 |
number-of-closed-islands | 𝐒𝐢𝐦𝐩𝐥𝐞 𝐃𝐅𝐒 𝐒𝐨𝐥𝐮𝐭𝐢𝐨𝐧✅✅ | simple-dfs-solution-by-deleted_user-av3d | \n# Code\n\nclass Solution {\npublic:\n void DFS(vector<vector<int>>& grid,int i,int j,int& val)\n {\n if(i<0 || i==grid.size() || j<0 || j==grid[0 | deleted_user | NORMAL | 2023-04-06T01:03:19.531009+00:00 | 2023-04-06T01:03:19.531041+00:00 | 262 | false | \n# Code\n```\nclass Solution {\npublic:\n void DFS(vector<vector<int>>& grid,int i,int j,int& val)\n {\n if(i<0 || i==grid.size() || j<0 || j==grid[0].size())\n {\n val=0;\n return;\n }\n if(grid[i][j]!=0)return ;\n grid[i][j]=1;\n DFS(grid,i+1,j,val);\n DFS(grid,i-1,j,val);\n DFS(grid,i,j-1,val);\n DFS(grid,i,j+1,val);\n }\n \n int closedIsland(vector<vector<int>>& grid) {\n int count=0;\n for(int i=0;i<grid.size();i++)\n {\n for(int j=0;j<grid[i].size();j++)\n {\n if(grid[i][j]==0) \n {\n int val=1;\n DFS(grid,i,j,val);\n count+=val;\n }\n }\n }\n return count;\n }\n};\n``` | 3 | 0 | ['C++'] | 0 |
number-of-closed-islands | Java | DFS | Clean code | Beats > 82% | java-dfs-clean-code-beats-82-by-judgemen-7pxj | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | judgementdey | NORMAL | 2023-04-06T00:43:57.486497+00:00 | 2023-04-06T00:45:43.432173+00:00 | 33 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $$O(m*n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(m*n)$$ on the stack\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n int m, n;\n int[][] dir = new int[][] {{0,1}, {0,-1}, {1,0}, {-1,0}};\n\n private boolean dfs(int[][] grid, int i, int j) {\n if (i < 0 || i >= m || j < 0 || j >= n)\n return false;\n \n if (grid[i][j] == 1)\n return true;\n\n grid[i][j] = 1;\n\n var res = true;\n for (var d : dir)\n res &= dfs(grid, i + d[0], j + d[1]);\n\n return res;\n }\n\n public int closedIsland(int[][] grid) {\n m = grid.length;\n n = grid[0].length;\n var cnt = 0;\n\n for (var i=0; i<m; i++)\n for (var j=0; j<n; j++)\n if (grid[i][j] == 0 && dfs(grid, i, j))\n cnt++;\n\n return cnt;\n }\n}\n```\nIf you like my solution, please upvote it! | 3 | 0 | ['Depth-First Search', 'Recursion', 'Matrix', 'Java'] | 0 |
number-of-closed-islands | C++ DFS traversal | c-dfs-traversal-by-khatung-jmtd | Intuition\n Describe your first thoughts on how to solve this problem. \nGraph Traversal.\n# Approach\n Describe your approach to solving the problem. \nIterate | khatung | NORMAL | 2023-02-17T06:38:29.137442+00:00 | 2023-04-06T09:19:22.183650+00:00 | 743 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nGraph Traversal.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nIterate the grid and have a counter of island. If reach a land cell, perform a DFS traversal from that cell. \nFor each traversal, everytime we find a land, we mark them as water (visited). \nIf we found a land that coordination in on the border of the grid, that means the current traversal didn\'t find a closed island. When we finish the traversal, if we found closed insland then we increment the count. Continue to iterate the grid to find other possible islands.\n# Complexity\n- Time complexity: $$O(n)$$ as we only travel each cell once. Every time we reach a land, we mark it as water and later iteration we will not check it again.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$ for recursive call, and for each call we don\'t allocate any extra memery space, just use a counter and a flag.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n bool isIsland;\n int closedIsland(vector<vector<int>>& grid) {\n isIsland = true;\n int islands = 0;\n for(int i = 0; i < grid.size(); i++)\n {\n for(int j = 0; j < grid[0].size(); j++)\n {\n //Found a possible land, do traversal and check isIsland\n if(grid[i][j] == 0)\n {\n findIsland(i,j,grid);\n if(isIsland) \n islands++; //the current traversal found island, increment count \n else \n isIsland = true;\n }\n }\n }\n return islands;\n }\n\n void findIsland(int i, int j, vector<vector<int>>& grid)\n { \n //out-of-border coordination: invalid \n if(!(i >= 0 && j >= 0 && i < grid.size() && j < grid[0].size()))\n {\n return;\n }\n \n //If we reach water we stop, else continue traversal\n if(grid[i][j] == 1) return; \n else grid[i][j] = 1;\n //If current land is at border, it\'s not closed islands, mark isIsland as false\n if(i == 0 || j == 0 || i == grid.size()-1 || j == grid[0].size()-1)\n isIsland = false;\n findIsland(i-1,j,grid);\n findIsland(i,j-1,grid);\n findIsland(i+1,j,grid);\n findIsland(i,j+1,grid);\n }\n};\n``` | 3 | 1 | ['C++'] | 2 |
number-of-closed-islands | Union Find | union-find-by-jiaqiong-tm26 | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | Jiaqiong | NORMAL | 2023-02-15T00:00:30.680845+00:00 | 2023-02-15T00:00:30.680876+00:00 | 132 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> parent, rank;\n vector<int> dir ={1,0,-1,0,1};\n int find(int x){\n return parent[x]==x?x:parent[x]=find(parent[x]);\n }\n void make_union(int x, int y){\n int px = find(x), py=find(y);\n if(px == py) return;\n if(rank[px]<rank[py]) parent[px] = py;\n else if(rank[px]>rank[py]) parent[py] = px;\n else{\n parent[py] = px;\n rank[px] +=1;\n }\n }\n int closedIsland(vector<vector<int>>& grid) {\n int m=grid.size(), n=grid[0].size();\n parent.resize(m*n+1);\n std::iota(parent.begin(), parent.end(), 0);\n rank.resize(m*n+1,1);\n\n for(int i=0; i<m; ++i){\n for(int j=0; j<n; ++j){\n if(grid[i][j]==1) continue;\n if(i==0||i==m-1||j==0||j==n-1) make_union(i*n+j, m*n);\n else{\n for(int k=0; k<4; ++k){\n int x = dir[k]+i;\n int y = dir[k+1]+j;\n if(x>=0&&x<m&&y>=0&&y<n&&grid[x][y]==0){\n make_union(i*n+j, x*n+y);\n }\n }\n }\n } \n }\n unordered_set<int>s;\n int root = find(m*n);\n for(int i=0; i<m; ++i){\n for(int j=0; j<n; ++j){\n if(grid[i][j]==1) continue;\n int p = find(i*n+j);\n if(p != root) s.insert(p);\n }\n }\n return s.size();\n }\n};\n``` | 3 | 0 | ['Union Find', 'C++'] | 0 |
number-of-closed-islands | C++ || DFS || Easy approach | c-dfs-easy-approach-by-mrigank_2003-4fhg | Here is my c++ code for this problem.\nDFS:-\n\'\'\'\n\n\tclass Solution {\n\tpublic:\n\t\tbool dfs(int x, int y, vector>& grid){\n\t\t\tif(x<0 || x>=grid.size( | mrigank_2003 | NORMAL | 2022-11-18T13:59:59.771094+00:00 | 2022-11-18T13:59:59.771128+00:00 | 1,246 | false | Here is my c++ code for this problem.\nDFS:-\n\'\'\'\n\n\tclass Solution {\n\tpublic:\n\t\tbool dfs(int x, int y, vector<vector<int>>& grid){\n\t\t\tif(x<0 || x>=grid.size() || y<0 || y>=grid[0].size()){return false;}\n\t\t\tif(grid[x][y]==1){return true;}\n\t\t\tgrid[x][y]=1;\n\t\t\tbool chk1=dfs(x-1, y, grid), chk2=dfs(x, y-1, grid), chk3=dfs(x+1, y, grid), chk4=dfs(x, y+1, grid);\n\t\t\treturn (chk1 && chk2 && chk3 && chk4);\n\t\t}\n\t\tint closedIsland(vector<vector<int>>& grid) {\n\t\t\tvector<vector<int>>v(grid.size(), vector<int>(grid[0].size(), 0));\n\t\t\tint cnt=0;\n\t\t\tfor(int i=0; i<grid.size(); i++){\n\t\t\t\tfor(int j=0; j<grid[0].size(); j++){\n\t\t\t\t\tif(grid[i][j]==0){\n\t\t\t\t\t\tif(dfs(i, j, grid)){cnt++;}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn cnt;\n\t\t}\n\t};\n\'\'\' | 3 | 0 | ['Depth-First Search', 'C'] | 1 |
number-of-closed-islands | C++ Well Explained BFS solution | c-well-explained-bfs-solution-by-singhal-yfia | \nclass Solution {\n //direction pair array\n pair<int, int> direction[4] = {{1,0}, {-1,0}, {0,1}, {0, -1}};\npublic:\n bool Bfs(int i, int j, vector<v | singhalPratham | NORMAL | 2022-11-01T20:06:19.817012+00:00 | 2022-11-01T20:06:19.817044+00:00 | 663 | false | ```\nclass Solution {\n //direction pair array\n pair<int, int> direction[4] = {{1,0}, {-1,0}, {0,1}, {0, -1}};\npublic:\n bool Bfs(int i, int j, vector<vector<int>>& grid, int n, int m){\n queue<pair<int, int>> q1;\n q1.push({i, j});\n bool res = true;\n while(!q1.empty()){\n pair<int, int> temp = q1.front();\n q1.pop();\n for(auto &a: direction){\n int x = temp.first + a.first;\n int y = temp.second + a.second;\n //edge case\n if(x < 0 || y < 0 || x >= n || y >= m || grid[x][y] == 1){\n continue;\n }\n // if the cell is at the corner row or corner column -> res = false;\n if(x == 0 || y == 0 || x == n-1 || y == m-1){\n res = false;\n }\n grid[x][y] = 1;\n q1.push({x, y});\n }\n }\n return res;\n }\n int closedIsland(vector<vector<int>>& grid) {\n int n = grid.size();\n int m = grid[0].size();\n int ans = 0;\n for(int i = 1; i < n-1; i++){\n for(int j = 1; j < m-1; j++){\n if(grid[i][j] == 0){\n bool temp = Bfs(i, j, grid, n, m);\n ans += temp;\n }\n }\n }\n return ans;\n }\n};\n``` | 3 | 0 | ['Breadth-First Search', 'Graph', 'C'] | 0 |
number-of-closed-islands | C++ | DFS | Comments Added | Easy approach | c-dfs-comments-added-easy-approach-by-sh-du80 | \nclass Solution {\npublic:\nint row;\nint col;\n void dfs(int i, int j, vector<vector<int>> &grid)\n {\n if(i < 0 || j < 0 || j >= col || i >= row | shreyanshxyz | NORMAL | 2022-07-15T19:52:00.360792+00:00 | 2022-07-15T19:52:00.360827+00:00 | 79 | false | ```\nclass Solution {\npublic:\nint row;\nint col;\n void dfs(int i, int j, vector<vector<int>> &grid)\n {\n if(i < 0 || j < 0 || j >= col || i >= row || grid[i][j] != 0) return;\n// (3) now if we find a piece of land connected to the border we change that 1 into 2, because its not of any use\n grid[i][j] = 2;\n \n// (4) this is a simple dfs call that checks the left-right-top-bottom cells of that piece and sees if that is also a 1, if it is then the same process gets conducted with it as well because it is connected to the cell touching the boundary.\n// this way we eliminate all the cells connected to the boundary\n dfs(i - 1, j, grid);\n dfs(i + 1, j, grid);\n dfs(i, j - 1, grid);\n dfs(i, j + 1, grid);\n }\n \n int closedIsland(vector<vector<int>>& grid) {\n if(grid.empty()) return 0;\n \n row = grid.size();\n col = grid[0].size();\n int ans = 0;\n \n// (1) Traverse top and bottom i for corner islands & set them to 1 since they are not closed off\n for (int i = 0; i < row; i++)\n {\n if (grid[i][0] == 0)\n {\n dfs(i, 0, grid);\n }\n if (grid[i][col - 1] == 0)\n {\n dfs(i, col - 1, grid);\n }\n }\n \n \n// (2) We check for the left column and right column to see if a piece of land exists with connections to the boundary\n// Since corners (0,0) and (n - 1, m - 1) where checked in previous cycle, skip them in this one\n for (int j = 1; j < col - 1; j++)\n {\n if (grid[0][j] == 0)\n {\n dfs(0, j, grid);\n }\n if (grid[row - 1][j] == 0)\n {\n dfs(row - 1, j, grid);\n }\n }\n \n// (5) Now we start iterating through our matrix, as soon as we find a 0, it wont be in the borders so its obviously closed, so we increment our answer by 1 for that piece of island and then iterate through it with the help of our dfs function created above. we do this for all the central/non border connected cells and we eventually get our answer.\n for(int i = 0; i < row; i++){\n for(int j = 0; j < col; j++){\n if(grid[i][j] == 0){\n solve(i, j, row, col, grid);\n ans++;\n }\n }\n }\n \n return ans;\n }\n};\n``` | 3 | 0 | ['Depth-First Search', 'C'] | 0 |
number-of-closed-islands | ✅ Python, Easy to understand DFS solution, 95.50% runtime | python-easy-to-understand-dfs-solution-9-7drp | \nclass Solution:\n def closedIsland(self, grid: List[List[int]]) -> int:\n result = 0\n \n def dfs(grid, r, c):\n if not 0 < | AntonBelski | NORMAL | 2022-06-28T15:18:31.717096+00:00 | 2022-06-28T15:18:54.050600+00:00 | 393 | false | ```\nclass Solution:\n def closedIsland(self, grid: List[List[int]]) -> int:\n result = 0\n \n def dfs(grid, r, c):\n if not 0 <= r < len(grid) or not 0 <= c < len(grid[0]):\n return False\n if grid[r][c] != 0:\n return True\n \n grid[r][c] = 2\n return all([dfs(grid, r - 1, c),\n dfs(grid, r + 1, c),\n dfs(grid, r, c - 1),\n dfs(grid, r, c + 1)])\n \n for r in range(len(grid)):\n for c in range(len(grid[0])):\n if grid[r][c] == 0 and dfs(grid, r, c):\n result += 1\n \n return result\n```\n\nTime Complexity - ```O(M * N)```\nSpace \u0421omplexity - ```O(M * N)``` (since our island can be like a snake, and the recursion depth will be equal to ```(m * n)/2```\n | 3 | 0 | ['Depth-First Search', 'Python3'] | 2 |
number-of-closed-islands | C++|| DFS|| Beginner Friendly || Commented Solution || Number of island approach | c-dfs-beginner-friendly-commented-soluti-r48j | class Solution {\npublic:\n \n //Function to submerge all island that are at boundary of grid\n void change (vector > &grid, int n, int m, int i, int j | ritik_pr3003 | NORMAL | 2022-03-27T05:37:55.304604+00:00 | 2022-03-27T05:37:55.304629+00:00 | 235 | false | class Solution {\npublic:\n \n //Function to submerge all island that are at boundary of grid\n void change (vector <vector <int>> &grid, int n, int m, int i, int j){\n if(i<0 || j<0 || i>=n || j>=m || grid[i][j]==1){\n return ;\n }\n grid[i][j]=1;\n change(grid,n,m,i+1,j);\n change(grid,n,m,i,j+1);\n change(grid,n,m,i-1,j);\n change(grid,n,m,i,j-1);\n }\n //Function to count number of island\n void dfs(vector <vector <int> >&grid, int n, int m, int i, int j){\n if(i<0 || j<0 || i>=n || j>=m || grid[i][j]==1){\n return ;\n }\n grid[i][j]=1;\n dfs(grid, n, m, i+1,j);\n dfs(grid, n, m, i,j+1);\n dfs(grid, n, m, i-1,j);\n dfs(grid, n, m, i,j-1);\n }\n \n \n int closedIsland(vector<vector<int>>& grid) {\n int ans=0;\n int n=grid.size();\n int m=grid[0].size();\n //Submerge all island that are at boundary of grid\n for(int i=0; i<n; i++){\n for(int j=0; j<m; j++){\n if(i==0 || j==0 || i==n-1 || j==m-1 ){\n if(grid[i][j]==0){\n change(grid,n,m,i,j);\n }\n }\n }\n }\n //Count number of island\n for(int i=0; i<n; i++){\n for(int j=0; j<m; j++){\n if(grid[i][j]==0){\n ans++;\n dfs(grid,n, m, i,j);\n }\n }\n }\n return ans;\n }\n}; | 3 | 0 | ['Depth-First Search', 'C', 'C++'] | 0 |
number-of-closed-islands | Easy dfs | easy-dfs-by-breaker250611-xv8k | \n//Simply traversed through the grid and return the min of dfs applying if it is on the side corners that will give you 0 and if not that will give you 1 and j | breaker250611 | NORMAL | 2022-03-23T09:29:27.670390+00:00 | 2022-03-23T09:30:02.175359+00:00 | 89 | false | ```\n//Simply traversed through the grid and return the min of dfs applying if it is on the side corners that will give you 0 and if not that will give you 1 and just added all them\nclass Solution {\npublic:\n int closedIsland(vector<vector<int>>& grid) {\n int count = 0 ;\n \n for(int i=0;i<grid.size();i++){\n for(int j = 0;j<grid[0].size();j++){\n if(grid[i][j]==0){\n count += dfs(grid,i,j);\n }\n }\n }\n return count;\n }\n int dfs(vector<vector<int>> &grid,int i , int j){\n if(i<0||j<0||i>=grid.size()||j>=grid[0].size()) return 0;\n if(grid[i][j]==1)return 1;\n grid[i][j]=1;\n \n int ans = min({dfs(grid,i+1,j),dfs(grid,i-1,j),dfs(grid,i,j+1),dfs(grid,i,j-1)});\n return ans;\n }\n};\n\n``` | 3 | 0 | [] | 1 |
number-of-closed-islands | Easy C++ solution || DFS || with well explained comments | easy-c-solution-dfs-with-well-explained-oii0l | ``` \nvoid dfs(vector>& grid,int i,int j){\n if(i<0||i>=grid.size()||j<0||j>=grid[0].size()||grid[i][j]==1) //checking boundary conditions\n | Harsh_Soni_0734 | NORMAL | 2022-03-04T05:50:57.413154+00:00 | 2022-03-04T05:56:57.760941+00:00 | 123 | false | ``` \nvoid dfs(vector<vector<int>>& grid,int i,int j){\n if(i<0||i>=grid.size()||j<0||j>=grid[0].size()||grid[i][j]==1) //checking boundary conditions\n return;\n grid[i][j]=1;\n dfs(grid,i+1,j); //traversing in downward direction\n dfs(grid,i-1,j); //traversing in upward direction\n dfs(grid,i,j+1); //traversing in rightward direction\n dfs(grid,i,j-1); //traversing in leftward direction\n\n }\n \n \n int closedIsland(vector<vector<int>>& grid) {\n int ans=0;\n int m=grid.size();\n int n=grid[0].size();\n \n for(int i=0;i<m;i++){ //filling all the land connected with left and right boundary of grid with water (1\'s)\n if(grid[i][0]==0)\n dfs(grid,i,0);\n if(grid[i][n-1]==0)\n dfs(grid,i,n-1);\n }\n \n for(int j=0;j<n;j++){ //filling all the land connected with top and bottom boundary of grid with water (1\'s)\n if(grid[0][j]==0)\n dfs(grid,0,j);\n if(grid[m-1][j]==0)\n dfs(grid,m-1,j);\n }\n \n for(int i=0;i<m;i++){ //count and flood fill the remaining island\n for(int j=0;j<n;j++){\n if(grid[i][j]==0)\n {\n dfs(grid,i,j);\n ans++; //increase the count for every island \n } \n }\n } \n return ans;\n }\n\t | 3 | 0 | ['Depth-First Search', 'Recursion'] | 0 |
number-of-closed-islands | Python 3 Solution | DFS | O(1) Space | python-3-solution-dfs-o1-space-by-1nnoce-9rtc | py\nclass Solution:\n def closedIsland(self, grid: List[List[int]]) -> int:\n n, m = len(grid), len(grid[0])\n def dfs(i, j):\n if i | 1nnOcent | NORMAL | 2022-03-03T11:02:11.384332+00:00 | 2022-03-03T11:02:11.384363+00:00 | 292 | false | ```py\nclass Solution:\n def closedIsland(self, grid: List[List[int]]) -> int:\n n, m = len(grid), len(grid[0])\n def dfs(i, j):\n if i == n or j == m or i < 0 or j < 0 or grid[i][j]:\n return\n \n grid[i][j] = 1\n dfs(i+1, j)\n dfs(i-1, j)\n dfs(i, j+1)\n dfs(i, j-1)\n \n res = 0\n for i in range(n):\n for j in range(m):\n if grid[i][j] == 0 and (i in (0, n-1) or j in (0, m-1)):\n dfs(i, j)\n \n for i in range(n):\n for j in range(m):\n if grid[i][j] == 0:\n dfs(i, j)\n res += 1\n \n return res\n``` | 3 | 0 | ['Depth-First Search', 'Python'] | 0 |
number-of-closed-islands | Java easy dfs | java-easy-dfs-by-ankitkumarmahato-d5y7 | \nclass Solution {\n private boolean solve(int row,int col,int[][] grid,boolean[][] vis){\n if(row<0 || row>=grid.length || col<0 || col>=grid[0].leng | ankitkumarmahato | NORMAL | 2022-02-15T18:23:16.913624+00:00 | 2022-02-15T18:23:16.913655+00:00 | 176 | false | ```\nclass Solution {\n private boolean solve(int row,int col,int[][] grid,boolean[][] vis){\n if(row<0 || row>=grid.length || col<0 || col>=grid[0].length)\n return false;\n if(grid[row][col]==1 || vis[row][col])\n return true;\n \n vis[row][col]=true;\n boolean up=solve(row-1,col,grid,vis);\n boolean down=solve(row+1,col,grid,vis);\n boolean left=solve(row,col-1,grid,vis);\n boolean right=solve(row,col+1,grid,vis);\n return up && down && left && right;\n }\n public int closedIsland(int[][] grid) {\n int n=grid.length,m=grid[0].length,count=0;\n boolean[][] vis=new boolean[n][m];\n for(int i=0;i<n;i++){\n for(int j=0;j<m;j++){\n if(grid[i][j]==0 && !vis[i][j]){\n if(solve(i,j,grid,vis))\n count++;\n }\n }\n }\n return count;\n }\n}\n``` | 3 | 0 | ['Java'] | 1 |
n-repeated-element-in-size-2n-array | [Java/C++/Python] O(1) Solution | javacpython-o1-solution-by-lee215-mhu6 | Solution 1\nUse array or set and return seen number at once.\nO(N) time, O(N) space\n\nJava, use array\n\n public int repeatedNTimes(int[] A) {\n int[ | lee215 | NORMAL | 2018-12-23T18:50:11.233107+00:00 | 2020-02-01T03:34:46.761858+00:00 | 25,113 | false | ### Solution 1\nUse array or set and return seen number at once.\n`O(N)` time, `O(N)` space\n\n**Java, use array**\n```\n public int repeatedNTimes(int[] A) {\n int[] count = new int[10000];\n for (int a : A)\n if (count[a]++ == 1)\n return a;\n return -1;\n }\n```\n**C++, use set**\n```\n int repeatedNTimes2(vector<int>& A) {\n unordered_set<int> seen;\n for (int a: A) {\n if (seen.count(a))\n return a;\n seen.insert(a);\n }\n }\n```\n<br>\n\n\n## Solution 2\nCheck if `A[i] == A[i - 1]` or `A[i] == A[i - 2]`\nIf so, we return `A[i]`\nIf not, it must be `[x, x, y, z]` or `[x, y, z, x]`.\nWe return `A[0]` for the cases that we miss.\n`O(N)` time `O(1)` space\n\n**C++**\n```\n int repeatedNTimes(vector<int>& A) {\n for (int i = 2; i < A.size(); ++i)\n if (A[i] == A[i - 1] || A[i] == A[i - 2])\n return A[i];\n return A[0];\n }\n```\n\n**Java**\n```\n public int repeatedNTimes(int[] A) {\n for (int i = 2; i < A.length; ++i)\n if (A[i] == A[i - 1] || A[i] == A[i - 2])\n return A[i];\n return A[0];\n }\n```\n<br>\n\n## Solution 3\nThis is a solution just for fun, not for interview.\nInstead of compare from left to right,\nwe can compare in random order.\n\nRandom pick two numbers.\nReturn if same.\n\n50% to get the right number.\nEach turn, 25% to get two right numbers.\nReturn the result in average 4 turns.\nTime complexity amortized `O(4)`, space `O(1)`\n\n\n**C++:**\n```\n int repeatedNTimes(vector<int>& A) {\n int i = 0, j = 0, n = A.size();\n while (i == j || A[i] != A[j])\n i = rand() % n, j = rand() % n;\n return A[i];\n }\n```\n\n**Java:**\n```\n public int repeatedNTimes(int[] A) {\n int i = 0, j = 0, n = A.length;\n while (i == j || A[i] != A[j]) {\n i = (int)(Math.random() * n);\n j = (int)(Math.random() * n);\n }\n return A[i];\n }\n```\n**Python:**\n```\n def repeatedNTimes(self, A):\n while 1:\n s = random.sample(A, 2)\n if s[0] == s[1]:\n return s[0]\n```\n | 214 | 26 | [] | 44 |
n-repeated-element-in-size-2n-array | C++ 2 lines O(4) | O (1) | c-2-lines-o4-o-1-by-votrubac-tv68 | The intuition here is that the repeated numbers have to appear either next to each other (A[i] == A[i + 1]), or alternated (A[i] == A[i + 2]).\n\nThe only excep | votrubac | NORMAL | 2018-12-23T04:01:53.958833+00:00 | 2018-12-23T04:01:53.958878+00:00 | 10,302 | false | The intuition here is that the repeated numbers have to appear either next to each other (```A[i] == A[i + 1]```), or alternated (```A[i] == A[i + 2]```).\n\nThe only exception is sequences like ```[2, 1, 3, 2]```. In this case, the result is the last number, so we just return it in the end. This solution has O(n) runtime.\n```\nint repeatedNTimes(vector<int>& A) {\n for (auto i = 0; i < A.size() - 2; ++i)\n if (A[i] == A[i + 1] || A[i] == A[i + 2]) return A[i];\n return A[A.size() - 1]; \n}\n```\nAnother interesting approach is to use randomization (courtesy of [@lee215 ](https://leetcode.com/lee215)). If you pick two numbers randomly, there is a 25% chance you bump into the repeated number. So, in average, we will find the answer in 4 attempts, thus O(4) runtime.\n```\nint repeatedNTimes(vector<int>& A, int i = 0, int j = 0) {\n while (A[i = rand() % A.size()] != A[j = rand() % A.size()] || i == j);\n return A[i];\n}\n``` | 139 | 5 | [] | 12 |
n-repeated-element-in-size-2n-array | Circular array O(n) time and O(1) Space | circular-array-on-time-and-o1-space-by-d-35cd | If a number is repeated N times in a list of size 2N, it is always possible for the repeated number to stay within a distance of 2.\nConsider this exaple where | destinynitsed | NORMAL | 2018-12-23T04:16:29.918477+00:00 | 2018-12-23T04:16:29.918547+00:00 | 3,352 | false | If a number is repeated N times in a list of size 2N, it is always possible for the repeated number to stay within a distance of 2.\nConsider this exaple where N = 4, Number **x** is repeated twice. All possible comibnations for x to fit in a list of size 4 are:\n[a,b,x,x]\n[x,a,b,x] (distance between both the x is still 1, consider it as a circular list)\n[x,a,x,b]\n[x,x,a,b]\n[a,x,b,x]\n[a,x,x,b]\n```python\nclass Solution:\n def repeatedNTimes(self, A):\n for i in range(len(A)):\n if A[i - 1] == A[i] or A[i - 2] == A[i]:\n return A[i]\n``` | 43 | 3 | [] | 6 |
n-repeated-element-in-size-2n-array | Python one-liner beats 100% | python-one-liner-beats-100-by-darktianti-r69n | \n def repeatedNTimes(self, A):\n """\n :type A: List[int]\n :rtype: int\n """\n return int((sum(A)-sum(set(A))) // (len(A | darktiantian | NORMAL | 2018-12-23T06:19:20.058786+00:00 | 2018-12-23T06:19:20.058849+00:00 | 5,336 | false | ```\n def repeatedNTimes(self, A):\n """\n :type A: List[int]\n :rtype: int\n """\n return int((sum(A)-sum(set(A))) // (len(A)//2-1))\n``` | 41 | 2 | [] | 13 |
n-repeated-element-in-size-2n-array | PYTHON 3 : SUPER EASY 99.52% FASTER | python-3-super-easy-9952-faster-by-rohit-be5b | 184 ms, faster than 99.52% USING LIST\n\nclass Solution:\n def repeatedNTimes(self, nums: List[int]) -> int:\n \n list1 = []\n for i in | rohitkhairnar | NORMAL | 2021-07-14T15:07:19.010505+00:00 | 2021-07-14T15:27:30.110490+00:00 | 2,398 | false | **184 ms, faster than 99.52%** USING LIST\n```\nclass Solution:\n def repeatedNTimes(self, nums: List[int]) -> int:\n \n list1 = []\n for i in nums :\n if i in list1 :\n return i\n else :\n list1.append(i)\n```\n**192 ms, faster than 95.77%** USING SET\n```\nclass Solution:\n def repeatedNTimes(self, nums: List[int]) -> int:\n \n set1 = set()\n for i in nums :\n if i in set1 :\n return i\n else :\n set1.add(i)\n```\n**208 ms, faster than 58.09%** USING COUNT\n```\nclass Solution:\n def repeatedNTimes(self, nums: List[int]) -> int:\n \n for i in nums :\n if nums.count(i) == len(nums)/2 :\n return i\n```\n**220 ms, faster than 36.92%** USING DICTIONARY\n```\nclass Solution:\n def repeatedNTimes(self, nums: List[int]) -> int:\n \n dic = {}\n for i in nums :\n if i in dic :\n dic[i] += 1\n if dic[i] == len(nums)/2 :\n return i\n else :\n dic[i] = 1\n```\n**Please upvote if it was helpful : )** | 22 | 0 | ['Ordered Set', 'Python', 'Python3'] | 1 |
n-repeated-element-in-size-2n-array | [2 methods] [1st using hashmap] [2nd using sorting][c++] | 2-methods-1st-using-hashmap-2nd-using-so-lakm | 1.Using hashmap TC:o(n)\n\n class Solution {\n public:\n int repeatedNTimes(vector& A) {\n unordered_map map;\n for(int i=0;i | rajat_gupta_ | NORMAL | 2020-08-25T17:36:57.178588+00:00 | 2020-10-03T13:51:11.363812+00:00 | 1,730 | false | **1.Using hashmap TC:o(n)**\n\n class Solution {\n public:\n int repeatedNTimes(vector<int>& A) {\n unordered_map<int,int> map;\n for(int i=0;i<A.size();i++){\n if(map[A[i]]>0)\n return A[i];\n map[A[i]]++;\n } \n return 0;\n }\n };\n\n**2.Using sorting TC:o(nlogn)**\n \n\tclass Solution {\n public:\n int repeatedNTimes(vector<int>& A) {\n sort(A.begin(), A.end());\n for(size_t i = 0; i < A.size()-1; i++){\n if(A[i] == A[i+1]) return A[i];\n }\n return 0;\n }\n };\n**Feel free to ask any question in the comment section.**\nI hope that you\'ve found the solution useful.\nIn that case, **please do upvote and encourage me** to on my quest to document all leetcode problems\uD83D\uDE03\nHappy Coding :)\n\n\t | 18 | 0 | ['C', 'Sorting', 'C++'] | 2 |
n-repeated-element-in-size-2n-array | python 3 easy to understand | python-3-easy-to-understand-by-akaghosti-yok1 | \tclass Solution:\n\t\tdef repeatedNTimes(self, A: List[int]) -> int:\n\t\t\tB = set(A)\n\t\t\treturn (sum(A) - sum(B)) // (len(A) - len(B)) | akaghosting | NORMAL | 2019-07-13T18:18:44.460952+00:00 | 2019-07-13T18:18:44.460995+00:00 | 1,943 | false | \tclass Solution:\n\t\tdef repeatedNTimes(self, A: List[int]) -> int:\n\t\t\tB = set(A)\n\t\t\treturn (sum(A) - sum(B)) // (len(A) - len(B)) | 16 | 0 | [] | 5 |
n-repeated-element-in-size-2n-array | 3 Different Approaches | 3-different-approaches-by-sahil20000706-a70a | Approach 1: Using Hash Map\nWe can use hash map to store the frequency of each element and then from hash map we can return the element with frequency == size/2 | sahil20000706 | NORMAL | 2021-09-14T05:15:10.659232+00:00 | 2022-03-14T10:22:56.608388+00:00 | 956 | false | ## **Approach 1: Using Hash Map**\nWe can use hash map to store the frequency of each element and then from hash map we can return the element with frequency == size/2.\n\nTime - O(n)\nSpace - O(n)\n\n\n**Code:-**\n\n```\nclass Solution {\npublic:\n int repeatedNTimes(vector<int>& nums) {\n unordered_map<int,int>m;\n for(auto i:nums)\n m[i]++;\n for(auto i:m){\n if(i.second == nums.size()/2)\n return i.first;\n }\n return -1;\n }\n};\n```\n\n## **Approach 2: Probability of finding repeated number**\n\nIf you pick any two numbers randomly from the given array, there is a 1/4 chance of getting the repeted number. So, in average, we will find the answer in 4 attempts.\n\nAverage Case Time - \u0398(4) or \u0398(1)\nWorst case ime - O(n) \nSpace - O(1)\n\n***Proof to 1/4 probability:**\nGiven that total elements of arr = 2n; \nA.T.Q ,number of repeated elements = n;\nand, number of non repeated elements = n;\nprobability = (n/2n) x (n/2n) = 1/4*\n\n**Code:-**\n\n```\nclass Solution {\npublic:\n int repeatedNTimes(vector<int>&nums) {\n int i = 0, j = 0;\n while(nums[i = rand() % nums.size()] != nums[j = rand() % nums.size()] || i == j);\n return nums[i];\n }\n};\n```\n\n## **Approach 3: Intuitive Approach (Pigeonhole principle)**\n\nOn carefully observing the sequences, we can come to general conclusion that the repeated numbers have to appear either next to each other or alternate next i.e.,\n(nums[i] == nums[i+1]) or (nums[i] == nums[i + 2]).\n\nThe only exception is sequence like [a, b, c, a]. So here, the result becomes the last number, so we just return it in the end.\n\nTime - O(n)\nSpace - O(1)\n\n**Code:-**\n\n```\nclass Solution {\npublic:\n int repeatedNTimes(vector<int>&nums) {\n for (int i = 0; i < nums.size() - 2; ++i)\n if (nums[i] == nums[i + 1] || nums[i] == nums[i + 2])\n return nums[i];\n return nums.back(); \n }\n};\n```\n\n**Please upvote if this helps.** | 14 | 0 | ['C', 'C++'] | 3 |
n-repeated-element-in-size-2n-array | JS - Faster than 97% - Using Sets | js-faster-than-97-using-sets-by-nilsonmo-9snl | \nvar repeatedNTimes = function(A) {\n let lookup = new Set();\n\n for (let n of A) {\n if (lookup.has(n)) return n;\n lookup.add(n);\n }\n\n return - | nilsonmolina | NORMAL | 2019-05-31T19:24:01.061169+00:00 | 2019-05-31T19:24:57.215189+00:00 | 1,450 | false | ```\nvar repeatedNTimes = function(A) {\n let lookup = new Set();\n\n for (let n of A) {\n if (lookup.has(n)) return n;\n lookup.add(n);\n }\n\n return -1;\n};\n``` | 12 | 0 | ['JavaScript'] | 5 |
n-repeated-element-in-size-2n-array | JAVA: 1 liner, O(n), 4ms, HashSet | java-1-liner-on-4ms-hashset-by-idkwho-t914 | \nclass Solution {\n public int repeatedNTimes(int[] A) {\n Set<Integer> store = new HashSet<>();\n\t\tfor(int a: A) if(store.add(a) == false) return | idkwho | NORMAL | 2019-02-10T23:18:20.400317+00:00 | 2019-02-10T23:18:20.400420+00:00 | 1,821 | false | ```\nclass Solution {\n public int repeatedNTimes(int[] A) {\n Set<Integer> store = new HashSet<>();\n\t\tfor(int a: A) if(store.add(a) == false) return a;\n return 0;\n }\n}\n``` | 12 | 3 | [] | 3 |
n-repeated-element-in-size-2n-array | Java 0MS Set | java-0ms-set-by-trevor-akshay-w4um | ```\nclass Solution {\n public int repeatedNTimes(int[] A) {\n Set set = new HashSet<>();\n for(int num : A) {\n if(set.contains(num | trevor-akshay | NORMAL | 2021-02-16T10:06:54.006234+00:00 | 2021-02-16T10:06:54.006278+00:00 | 1,163 | false | ```\nclass Solution {\n public int repeatedNTimes(int[] A) {\n Set<Integer> set = new HashSet<>();\n for(int num : A) {\n if(set.contains(num)) return num;\n else set.add(num);\n }\n return -1;\n }\n} | 11 | 0 | ['Ordered Set', 'Java'] | 1 |
n-repeated-element-in-size-2n-array | Python beats 100 % | python-beats-100-by-ashishbisht723-b14n | \nclass Solution:\n def repeatedNTimes(self, A: List[int]) -> int:\n """\n :type :A List[int]\n :rtype int\n """\n d = {}\ | ashishbisht723 | NORMAL | 2019-08-18T16:49:10.862595+00:00 | 2019-08-18T16:49:10.862625+00:00 | 1,000 | false | ```\nclass Solution:\n def repeatedNTimes(self, A: List[int]) -> int:\n """\n :type :A List[int]\n :rtype int\n """\n d = {}\n for num in A:\n if num in d.keys():\n return num\n else:\n d[num] = 1\n ``` | 11 | 0 | [] | 4 |
n-repeated-element-in-size-2n-array | C solution | c-solution-by-zhaoyaqiong-f7mo | \u57282N\u7684\u4F4D\u7F6E\u91CC\u4E00\u5171\u6709N+1\u4E2A\u4E0D\u540C\u7684\u5143\u7D20\uFF0C\u88AB\u67E5\u627E\u5143\u7D20\u51FA\u73B0N\u6B21\uFF0C\u6240\u4E | zhaoyaqiong | NORMAL | 2018-12-27T06:24:30.563577+00:00 | 2018-12-27T06:24:30.563639+00:00 | 1,152 | false | \u57282N\u7684\u4F4D\u7F6E\u91CC\u4E00\u5171\u6709N+1\u4E2A\u4E0D\u540C\u7684\u5143\u7D20\uFF0C\u88AB\u67E5\u627E\u5143\u7D20\u51FA\u73B0N\u6B21\uFF0C\u6240\u4EE5\u9664\u4E86\u88AB\u67E5\u627E\u5143\u7D20\uFF0C\u5176\u4ED6\u5143\u7D20\u5747\u53EA\u51FA\u73B0\u4E00\u6B21\u3002\u8003\u8651\u5143\u7D20\u7684\u968F\u673A\u5206\u5E03\uFF0C\u6700\u5DEE\u7684\u662F\u6CA1\u6709\u8FDE\u7EED\u7684\uFF0C\u88AB\u67E5\u627E\u5143\u7D20\u521A\u597D\u88AB\u4E00\u4E00\u9694\u5F00\uFF0C\u53E6\u5916\u4E00\u79CD\u60C5\u51B5\u662F\u88AB\u67E5\u627E\u5143\u7D20\u6709\u8FDE\u7EED\u3002\u5229\u7528\u4E0A\u9762\u4E24\u70B9\uFF0C\u5C31\u53EF\u4EE5\u5224\u65AD\u8FDE\u7EED\u662F\u5426\u76F8\u540C\uFF0C\u76F8\u9694\u4E00\u4E2A\u662F\u5426\u76F8\u540C\u627E\u5230\u7B54\u6848\u3002\u540C\u65F6\u9700\u8981\u8003\u86514\u4E2A\u5143\u7D20\u65F6\uFF0C\u88AB\u67E5\u627E\u5143\u7D20\u521A\u597D\u5728\u6700\u524D\u9762\u7684\u7279\u6B8A\u60C5\u51B5 \u3002\n```\n// \u7279\u6B8A\u60C5\u51B5 , a\u4E3A\u88AB\u67E5\u627E\u5143\u7D20\nA[] = {a, a, b, c};\n```\n```\nint repeatedNTimes(int *A, int ASize) {\n for (int i = 2; i < ASize; ++i) {\n if (A[i] == A[i-1] || A[i] == A[i-2] ) {\n return A[i];\n }\n }\n return A[0];\n}\n``` | 11 | 0 | [] | 4 |
n-repeated-element-in-size-2n-array | By sorting :) | by-sorting-by-theadarsh1m-xs9e | \n\n> # Code lelocode\nThe Adarsh 1M <-- Youtube\n\nclass Solution {\n public int repeatedNTimes(int[] nums) {\n Arrays.sort(nums);\n // int fl | TheAdarsh1M | NORMAL | 2024-05-06T15:14:26.657503+00:00 | 2024-05-06T15:14:26.657540+00:00 | 251 | false | \n\n> # Code lelo`code`\n**The Adarsh 1M <-- Youtube**\n```\nclass Solution {\n public int repeatedNTimes(int[] nums) {\n Arrays.sort(nums);\n // int flag = 0;\n for (int i = 1; i < nums.length; ++i){\n int temp = nums[i];\n int tempo = nums[i-1];\n if (temp == tempo)\n return temp;\n \n }\n return -1;\n\n \n }\n}\n``` | 6 | 0 | ['Java'] | 4 |
n-repeated-element-in-size-2n-array | 2 📌Fastest Java☕ solutions using HashMap & HashSet 1ms💯💯 | 2-fastest-java-solutions-using-hashmap-h-s3la | 1st approach using HashMap:-\n\nclass Solution {\n public int repeatedNTimes(int[] nums) \n {\n HashMap<Integer,Integer> hmap=new HashMap<>();\n | saurabh_173 | NORMAL | 2022-05-02T17:12:48.787090+00:00 | 2022-05-02T17:15:14.124582+00:00 | 579 | false | **1st approach using HashMap:-**\n```\nclass Solution {\n public int repeatedNTimes(int[] nums) \n {\n HashMap<Integer,Integer> hmap=new HashMap<>();\n for(int num:nums)\n {\n hmap.put(num,hmap.getOrDefault(num,0)+1);\n if(hmap.get(num)>1)\n return num;\n }\n return -1;\n }\n}\n```\n**2nd approach using HashSet:-**\n```\nclass Solution {\n public int repeatedNTimes(int[] nums) \n {\n HashSet<Integer> hset=new HashSet<>();\n for(int num:nums)\n {\n if(hset.contains(num))\n return num;\n hset.add(num);\n }\n return -1;\n }\n}\n```\n | 6 | 0 | ['Hash Table', 'Java'] | 0 |
n-repeated-element-in-size-2n-array | Python 3 The Simplest Code! | python-3-the-simplest-code-by-tot0-fc65 | \nclass Solution:\n def repeatedNTimes(self, A: List[int]) -> int:\n return mode(A)\n\n | tot0 | NORMAL | 2020-05-27T20:47:56.149934+00:00 | 2020-05-27T20:47:56.149987+00:00 | 583 | false | ```\nclass Solution:\n def repeatedNTimes(self, A: List[int]) -> int:\n return mode(A)\n```\n | 6 | 0 | [] | 1 |
n-repeated-element-in-size-2n-array | Python 1 liner using mode | python-1-liner-using-mode-by-lokeshsk1-88zj | \nclass Solution:\n def repeatedNTimes(self, A: List[int]) -> int:\n return mode(A)\n | lokeshsk1 | NORMAL | 2020-04-11T14:40:04.256468+00:00 | 2020-06-27T07:44:48.443584+00:00 | 565 | false | ```\nclass Solution:\n def repeatedNTimes(self, A: List[int]) -> int:\n return mode(A)\n``` | 6 | 1 | ['Python', 'Python3'] | 1 |
n-repeated-element-in-size-2n-array | 100/100 Solution zero additional memory | 100100-solution-zero-additional-memory-b-qrl4 | In an array of size 2N with N+1 unique elements, the maximum distance between the repeated numbers is 4, so only 4 numbers need to checked at once, and no need | cyberpirate92 | NORMAL | 2019-12-19T12:06:27.363434+00:00 | 2019-12-22T08:19:42.774783+00:00 | 564 | false | In an array of size `2N` with `N+1` unique elements, the maximum distance between the repeated numbers is `4`, so only `4` numbers need to checked at once, and no need for additional memory.\n\n```java\npublic int repeatedNTimes(int[] A) {\n\tfor (int i=0; i<=A.length-4; i++) {\n\t\tif (A[i] == A[i+1] || A[i] == A[i+2] || A[i] == A[i+3]) {\n\t\t\treturn A[i];\n\t\t}\n\t}\n\tif (A[A.length-3] == A[A.length-2] || A[A.length-3] == A[A.length-1]) {\n\t\treturn A[A.length-3];\n\t}\n\treturn A[A.length-2];\n}\n``` | 6 | 0 | ['Java'] | 3 |
n-repeated-element-in-size-2n-array | Improvement of 2nd official solution | improvement-of-2nd-official-solution-by-iedbv | From the official Approach 2\nThus, we only have to compare elements with their neighbors that are distance 1, 2, or 3 away.\nFor cases with where 2 * N > 4 the | jaltair | NORMAL | 2019-12-01T22:40:37.715424+00:00 | 2019-12-01T22:40:37.715473+00:00 | 933 | false | From the official Approach 2\n`Thus, we only have to compare elements with their neighbors that are distance 1, 2, or 3 away.`\nFor cases with where 2 * N > 4 there is no need to check neighbors that are 3 distance away. \n\n2 * N elements\nx is repeated N times\n\nFor 2 * N == 4 there is one corner case, where distance between x is 3\n[x, 1, 2, x]\n\nSuch case isn\'t possible for 2 * N > 4. Because the rest of elements will be \'squashed\', e.g. \n[x, 1, 2, x, 3, 4 ... \nthere must be at least 3, 4 before next x. But then right side will have 2N - 6 elements with N - 2 x\'es. Making N\' = N - 2\n2N - 6 => 2(N\' - 1)\nN - 2 => N\'\nwhich means we will need to squash at least 2 x\'es next to each other. \n\nOtherwise, if [x, 1, 2, x doesn\'t have 3, 4 afterwards distance to the third x is less than 3 and contradicts Approach 2 for 2 * N > 4 cases. \n\n```\n public int repeatedNTimes(int[] A) {\n if (A.length == 4 && A[0] == A[3]) {\n return A[0];\n }\n for (int k = 1; k <= 2; ++k) {\n for (int i = 0; i + k < A.length; ++i) {\n if (A[i] == A[i + k]) {\n return A[i];\n }\n }\n }\n return -1;\n }\n```\n\nPlease, prove me wrong if I\'m missing anything, | 6 | 0 | [] | 2 |
n-repeated-element-in-size-2n-array | Simple Python Solution | simple-python-solution-by-dodda_sai_sach-iak5 | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | Dodda_Sai_Sachin | NORMAL | 2024-02-21T18:35:43.973407+00:00 | 2024-02-21T18:35:43.973435+00:00 | 312 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def repeatedNTimes(self, nums: List[int]) -> int:\n seen=set()\n for i in nums:\n if i not in seen:\n seen.add(i)\n else:\n return i\n``` | 5 | 0 | ['Python3'] | 0 |
n-repeated-element-in-size-2n-array | 200 ms Solution beats 85 % in runtime only three lines Deadly simple ! | 200-ms-solution-beats-85-in-runtime-only-epf5 | PLease UPVOTE\n# Code\n\nclass Solution:\n def repeatedNTimes(self, nums: List[int]) -> int:\n freq=(max(nums)+1)*[0]\n for i in range(len(nums | ayan_101 | NORMAL | 2023-08-06T11:35:54.326218+00:00 | 2023-08-06T11:35:54.326252+00:00 | 394 | false | PLease UPVOTE\n# Code\n```\nclass Solution:\n def repeatedNTimes(self, nums: List[int]) -> int:\n freq=(max(nums)+1)*[0]\n for i in range(len(nums)):freq[nums[i]]+=1\n return freq.index(max(freq))\n``` | 5 | 0 | ['Python3'] | 1 |
n-repeated-element-in-size-2n-array | Simple Solution || 100% faster O(n/2) || JAVA | simple-solution-100-faster-on2-java-by-i-xf31 | Approach\nnums.length = 2 * n and exactly one element of nums is repeated n times. It means no one element except we searching cannot appear more than 1 time. I | im_obid | NORMAL | 2023-04-13T09:48:34.972562+00:00 | 2023-04-13T09:48:34.972601+00:00 | 1,010 | false | # Approach\n```nums.length = 2 * n``` and exactly one element of ```nums``` is repeated ```n``` times. It means no one element except we searching cannot appear more than 1 time. If any element of ```nums``` appears two or more times then it is the element that is repeated n times.\n \n\n---\n\n\nI used ```HashSet``` and its ```add()``` method. \n\n---\n\n```add()``` - Adds the specified element to this set if it is not already present and return ```true``` otherwise ```false```\n\n---\n**Please upvote if you find it useful**\n\n\n# Code\n```\nclass Solution {\n public int repeatedNTimes(int[] nums) {\n Set<Integer> set = new HashSet<>();\n for(int i = 0;i<nums.length;i++){\n if(!set.add(nums[i])){\n return nums[i];\n }\n }\n return 0;\n }\n}\n``` | 4 | 0 | ['Java'] | 2 |
n-repeated-element-in-size-2n-array | Java || 3 approaches || brute --> optimise -> 100% | java-3-approaches-brute-optimise-100-by-yg2ku | \n\n public int repeatedNTimes(int[] nums) {\n //Using sort ----> 6ms\n Arrays.sort(nums);\n int number = 0;\n int count = 1;\n | shivambhilarkar | NORMAL | 2021-06-24T04:51:34.666145+00:00 | 2021-06-24T04:51:34.666178+00:00 | 447 | false | ``\n\n public int repeatedNTimes(int[] nums) {\n //Using sort ----> 6ms\n Arrays.sort(nums);\n int number = 0;\n int count = 1;\n for(int i = 1; i< nums.length; i++){\n if(nums[i-1] == nums[i]){\n count++;\n }\n if(count == nums.length/2){\n return nums[i];\n }\n }\n return -1;\n \n //using HashMap ---------> 14ms\n \n HashMap<Integer, Integer> map = new HashMap<>();\n for(int i = 0; i< nums.length; i++){\n map.put(nums[i], map.getOrDefault(nums[i] , 0)+1);\n }\n \n for(int i : map.keySet()){\n if(map.get(i) == nums.length/2){\n return i;\n }\n }\n return -1;\n \n //using HashSet -----> 0ms\n HashSet<Integer> set = new HashSet<>();\n for(int num : nums){\n if(set.contains(num) == false){\n set.add(num);\n }else{\n return num;\n }\n \n }\n return -1;\n \n }\n}\n\n\n\n`` | 4 | 0 | ['Java'] | 0 |
n-repeated-element-in-size-2n-array | [Python Explained] Simple one-liner Counter | python-explained-simple-one-liner-counte-3r9h | Function Counter(nums) gives us the collection of elements along with the number of count\nHere\'s an example:\n\nnums = [2,1,2,5,3,2]\nCounter(nums)\n\nResult\ | akashadhikari | NORMAL | 2021-05-15T09:16:51.581050+00:00 | 2021-05-15T09:17:21.938539+00:00 | 147 | false | Function `Counter(nums)` gives us the collection of elements along with the number of count\nHere\'s an example:\n```\nnums = [2,1,2,5,3,2]\nCounter(nums)\n```\nResult\n`Counter({2: 3, 1: 1, 5: 1, 3: 1})` \n\nNow, `Counter(nums).most_common()` returns us the collection of tuples enclosed by a list\nResult\n`[(2, 3), (1, 1), (5, 1), (3, 1)]` \n\nAlso, `Counter(nums).most_common(1)` returns us only the **highest** element\nResult\n`[(2, 3)]` \nFinally. extract the number by mentioning the index `Counter(nums).most_common(1)[0][0]`\nResult\n`2`\n**Solution**\n```\nclass Solution(object):\n def repeatedNTimes(self, nums):\n return Counter(nums).most_common(1)[0][0]\n``` | 4 | 0 | ['Python', 'Python3'] | 1 |
n-repeated-element-in-size-2n-array | Java | Simple solution | 100% faster | java-simple-solution-100-faster-by-jeson-buib | The idea behind this implemenation is to return the "first duplicate element encountered"\ni.e Array will surely contains unique elements except the one to be | jesonshawn | NORMAL | 2020-11-22T07:01:03.766707+00:00 | 2020-11-22T08:08:17.026298+00:00 | 151 | false | The idea behind this implemenation is to return the "first duplicate element encountered"\ni.e Array will surely contains unique elements except the one to be returned.\n\nPS : Please upvote if u like this implementation or if u have any feedback, please feel free to drop a note\n\n```\nclass Solution {\n public int repeatedNTimes(int[] A) {\n \n Set<Integer> set = new HashSet<Integer>();\n \n for(int i : A) \n if(!set.add(i)) // Try inserting element in set : If duplicate found, set will return false and we return the value i\n return i;\n \n return 0;\n }\n}\n```\n\n\nWe can use couple of other solutions compromising the complexity.\n\n**Alternate 1**: \n\nPick two elements and calculate if their difference is zero (0).\n\tIf yes --> Return the element\n If no --> Continue/Repeat;\n\t\n**Alternate 2**:\n\t \nWe can also make use of Map<K,V> to store the elements and their counts , and return the one with highest count.\n\t \n\t \n\t \n | 4 | 0 | [] | 0 |
n-repeated-element-in-size-2n-array | Javascript O(n) | javascript-on-by-zeroabsolute-7hqb | \nvar repeatedNTimes = function(A) {\n const map = {};\n \n for (let i = 0; i < A.length; i++) {\n if (A[i] in map) {\n return A[i];\ | zeroabsolute | NORMAL | 2020-08-22T10:54:31.132648+00:00 | 2020-08-22T10:54:31.132693+00:00 | 372 | false | ```\nvar repeatedNTimes = function(A) {\n const map = {};\n \n for (let i = 0; i < A.length; i++) {\n if (A[i] in map) {\n return A[i];\n } else {\n map[A[i]] = 0;\n }\n }\n \n return 0;\n};\n``` | 4 | 0 | ['JavaScript'] | 0 |
n-repeated-element-in-size-2n-array | One line JavaScript beats 100% | one-line-javascript-beats-100-by-xeodou-uhol | \n/**\n * @param {number[]} A\n * @return {number}\n */\nvar repeatedNTimes = function(A) {\n return A.find((a, index, array) => array.indexOf(a) !== index)\n} | xeodou | NORMAL | 2019-04-13T16:54:13.652105+00:00 | 2019-04-13T16:54:13.652146+00:00 | 294 | false | ```\n/**\n * @param {number[]} A\n * @return {number}\n */\nvar repeatedNTimes = function(A) {\n return A.find((a, index, array) => array.indexOf(a) !== index)\n};\n``` | 4 | 0 | [] | 0 |
n-repeated-element-in-size-2n-array | c# 100% o(n) time o(1) space solution with explanation | c-100-on-time-o1-space-solution-with-exp-pebc | \npublic int RepeatedNTimes(int[] A)\n{\n\t// Since half of the array elements are the repeated number.\n\t// if A.Length != 4, we can always find two adjacent | gary10 | NORMAL | 2019-01-31T13:17:13.514110+00:00 | 2019-01-31T13:17:13.514180+00:00 | 388 | false | ```\npublic int RepeatedNTimes(int[] A)\n{\n\t// Since half of the array elements are the repeated number.\n\t// if A.Length != 4, we can always find two adjacent repeated\n\t// elements seperated by at most 2\n\tfor(int i = 0; i < A.Length - 2; i++)\n\t{\n\t\tif(A[i] == A[i + 1] || A[i] == A[i + 2])\n\t\t{\n\t\t\treturn A[i];\n\t\t}\n\t}\n\n\t// Special cases:\n\t// [x,a,b,x], "x" is seperated by 3\n\t// [a,b,x,x] or [x,a,b,c,x,x], the above loop can only reach "b" or "c"\n\t// The last element is always the repeated one no matther which case it is\n\treturn A[A.Length - 1];\n}\n``` | 4 | 0 | [] | 2 |
n-repeated-element-in-size-2n-array | Java Trivial solution with O(1) Space and O(N) time. | java-trivial-solution-with-o1-space-and-ggi3u | class Solution {\n public int repeatedNTimes(int[] A) {\n int a = -1;\n int b = -1;\n int c = -1;\n\n for(int i = 0; i < A.length | pjfry | NORMAL | 2019-01-29T06:46:56.459194+00:00 | 2019-01-29T06:46:56.459264+00:00 | 1,163 | false | ```class Solution {\n public int repeatedNTimes(int[] A) {\n int a = -1;\n int b = -1;\n int c = -1;\n\n for(int i = 0; i < A.length; i++){\n \tif(a == A[i]){\n \t\treturn a;\n \t}\n\n \tif(b == A[i]){\n \t\treturn b;\n \t}\n\n \tif(c == A[i]){\n \t\treturn c;\n \t}\n\n \ta = b;\n \tb = c;\n \tc = A[i];\n }\n\n return -1;\n }\n}\n``` | 4 | 0 | [] | 4 |
n-repeated-element-in-size-2n-array | c# 1 liner | c-1-liner-by-dimager2003-skf3 | \n\n public static int RepeatedNTimes(int[] A)\n {\n return (A.Sum() - A.Distinct().Sum()) / (A.Count() - A.Distinct().Count());\n }\n\ | dimager2003 | NORMAL | 2018-12-23T06:26:04.998201+00:00 | 2018-12-23T06:26:04.998250+00:00 | 293 | false | \n```\n public static int RepeatedNTimes(int[] A)\n {\n return (A.Sum() - A.Distinct().Sum()) / (A.Count() - A.Distinct().Count());\n }\n```\n\nthis 2 liner is faster though\n```\n public static int RepeatedNTimes(int[] A)\n {\n var distA = A.Distinct();\n return (A.Sum() - distA.Sum()) / (A.Count() - distA.Count());\n }\n``` | 4 | 0 | [] | 1 |
n-repeated-element-in-size-2n-array | 💢☠💫Easiest👾Faster✅💯 Lesser🧠 🎯 C++✅Python3🐍✅Java✅C✅Python🐍✅C#✅💥🔥💫Explained☠💥🔥 Beats 100 | easiestfaster-lesser-cpython3javacpython-q4o1 | \n\n# Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n\n Describe your first thoughts on how to solve this problem. \n- J | Edwards310 | NORMAL | 2024-12-06T08:01:57.666546+00:00 | 2024-12-06T08:01:57.666569+00:00 | 400 | false | \n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n\n<!-- Describe your first thoughts on how to solve this problem. -->\n- ***JavaScript Code -->*** https://leetcode.com/problems/n-repeated-element-in-size-2n-array/submissions/1471619711\n- ***C++ Code -->*** https://leetcode.com/problems/n-repeated-element-in-size-2n-array/submissions/1471555779\n- ***Python3 Code -->*** https://leetcode.com/problems/n-repeated-element-in-size-2n-array/submissions/1471577086\n- ***Java Code -->*** https://leetcode.com/problems/n-repeated-element-in-size-2n-array/submissions/1471558715\n- ***C Code -->*** https://leetcode.com/problems/n-repeated-element-in-size-2n-array/submissions/1471677828\n- ***Python Code -->*** https://leetcode.com/problems/n-repeated-element-in-size-2n-array/submissions/1471573335\n- ***C# Code -->*** https://leetcode.com/problems/n-repeated-element-in-size-2n-array/submissions/1471616089\n- ***Go Code -->*** https://leetcode.com/problems/n-repeated-element-in-size-2n-array/submissions/1471650419\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n O(N)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n O(1)\n# Code\n# Code\n\n | 3 | 0 | ['Array', 'Hash Table', 'C', 'Python', 'C++', 'Java', 'Go', 'Python3', 'JavaScript', 'C#'] | 1 |
n-repeated-element-in-size-2n-array | Simple C++ solution using. count function | simple-c-solution-using-count-function-b-j3c7 | Intuition\nIf count of the perticular element of the vector = vector size / 2 then return that element. \n\n# Complexity\n- Time complexity:\nO(n^2)\n\n- Space | kirtanmatalia | NORMAL | 2023-12-01T20:14:16.965656+00:00 | 2023-12-01T20:14:16.965684+00:00 | 423 | false | # Intuition\nIf count of the perticular element of the vector = vector size / 2 then return that element. \n\n# Complexity\n- Time complexity:\nO(n^2)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution {\npublic:\n int repeatedNTimes(vector<int>& nums) \n {\n int n = nums.size()/2;\n\n for(int i=0; i<nums.size(); i++)\n {\n int c = count(nums.begin(), nums.end(), nums[i]);\n\n if(c == n)\n {\n return nums[i];\n }\n\n }\n return -1;\n }\n};\n``` | 3 | 0 | ['C++'] | 1 |
n-repeated-element-in-size-2n-array | Best Java Solution || Beats 100% | best-java-solution-beats-100-by-ravikuma-q4qz | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | ravikumar50 | NORMAL | 2023-09-23T17:55:17.643784+00:00 | 2023-09-23T17:55:17.643803+00:00 | 421 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int repeatedNTimes(int[] arr) {\n HashSet<Integer> hp = new HashSet<>();\n\n for(var a : arr){\n if(hp.contains(a)) return a;\n else hp.add(a);\n }\n return -1;\n }\n}\n``` | 3 | 0 | ['Java'] | 0 |
n-repeated-element-in-size-2n-array | Python3: Two different approach, first run in O(nlogn) , the second O(n^2) | python3-two-different-approach-first-run-69av | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \nTwo approaches: \nFirst | ResilientWarrior | NORMAL | 2023-08-11T14:02:32.603834+00:00 | 2023-08-11T14:02:32.603851+00:00 | 22 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nTwo approaches: \nFirst Approach\n - the method of solving the problem is sorting nums and then using linear search comparing each values, if you come across to adjacent index with same value return the value at the index\n\nSecond Approach:\n - Here, we use the python\'s built in function, count(), count()- returns the frequence of the number, in our case all the numbers except one is uniqe, by using this fact if we came across a number with count value of greater than one, it means we have get the required number, so we return it.\n \n Thanks for your attention!!!\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nfirst runs in O(nlogn)\nseond runs in O(n^2)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nfirst O(1)\nseond O(n)\n# Code\n```\nclass Solution:\n def repeatedNTimes(self, nums: List[int]) -> int:\n #First Approach\n #both space (17.65mb beatas 89%) and time (193ms beats 86%) effiecent \n nums.sort() #sort nums\n for i in range(len(nums)-1): # use linear search to compare each elements\n if nums[i] == nums[i+1]:\n return nums[i]\n\n\n\n # Second Approch(the following is the second code block and has nothing to do with the first one)\n # time effiecent 184ms Beats 93%, space ineffiecent 17.91mb beats 14.11%\n for num in nums:\n if nums.count(num) > 1:\n return num\n``` | 3 | 0 | ['Python3'] | 1 |
n-repeated-element-in-size-2n-array | BEST SOLUTION!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! | best-solution-by-akg30akg-nc1f | Intuition\nCount the number of times elements are repeated.\n Describe your first thoughts on how to solve this problem. \n\n# Approach\nTake each element with | akg30akg | NORMAL | 2022-12-08T18:20:52.878629+00:00 | 2022-12-08T18:20:52.878660+00:00 | 1,364 | false | # Intuition\nCount the number of times elements are repeated.\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nTake each element with its count in the map data structure.\nCheck each element count,\nif its more than or equal to n/2, then return that element.\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int repeatedNTimes(vector<int>& nums) {\n int n = nums.size();\n map<int,int> mp;\n for(int i=0; i<n; i++) {\n mp[nums[i]]++;\n }\n for(auto it: mp) {\n if(it.second >= n/2)\n return it.first;\n }\n return -1;\n }\n};\n``` | 3 | 0 | ['Array', 'Hash Table', 'Math', 'Counting', 'C++'] | 2 |
n-repeated-element-in-size-2n-array | C++ Most easy and understanding solution , beginner friendly. | c-most-easy-and-understanding-solution-b-klm7 | If you find it helpfull then please consider it upvoting.\n\n\t\tsort(nums.begin(),nums.end());\n for(int i=1; i<nums.size(); i++)\n { if(nums[ | Akshay_Saini | NORMAL | 2022-10-29T09:31:06.106196+00:00 | 2022-10-29T09:32:32.166639+00:00 | 373 | false | ***If you find it helpfull then please consider it upvoting.***\n\n\t\tsort(nums.begin(),nums.end());\n for(int i=1; i<nums.size(); i++)\n { if(nums[i]==nums[i-1])\n return nums[i];\n }\n return -1; // This will disobey the constraints so it will be ignored. | 3 | 0 | ['C'] | 0 |
n-repeated-element-in-size-2n-array | N-Repeated Element in Size 2N Array | n-repeated-element-in-size-2n-array-by-a-qatd | int repeatedNTimes(vector& nums) {\n mapm;\n int n=nums.size();\n for(int i=0; i<n; i++){\n m[nums[i]]++;\n }\n fo | Ashish_49 | NORMAL | 2022-08-14T16:45:14.522956+00:00 | 2022-08-14T16:45:14.522986+00:00 | 25 | false | int repeatedNTimes(vector<int>& nums) {\n map<int, int>m;\n int n=nums.size();\n for(int i=0; i<n; i++){\n m[nums[i]]++;\n }\n for(auto x :m){\n if(x.second==n/2){\n return x.first;\n }\n }\n return -1;\n } | 3 | 0 | ['C'] | 0 |
n-repeated-element-in-size-2n-array | 99.55% runtime | O(1) space | Python | 9955-runtime-o1-space-python-by-dylwu-3flw | \nclass Solution:\n def repeatedNTimes(self, nums: List[int]) -> int:\n\t\t\n\t\t# keep track of the two previous numbers\n last2, last1 = nums[0], nu | dylwu | NORMAL | 2022-02-21T15:23:57.105399+00:00 | 2022-02-21T15:23:57.105449+00:00 | 330 | false | ```\nclass Solution:\n def repeatedNTimes(self, nums: List[int]) -> int:\n\t\t\n\t\t# keep track of the two previous numbers\n last2, last1 = nums[0], nums[1]\n \n\t\t# edge case: first and last are the same\n if nums[0] == nums[-1]:\n return nums[0]\n \n for i in range(2, len(nums)):\n\t\t # the number must be one of the 2 previous numbers, at some point\n if last1 == nums[i] or last2 == nums[i]:\n return nums[i]\n else: # reset the previous 2 numbers\n temp = last1\n last1 = nums[i]\n last2 = temp\n return -1\n``` | 3 | 0 | ['Python'] | 0 |
n-repeated-element-in-size-2n-array | A simple solution based on majority voting | a-simple-solution-based-on-majority-voti-w2ak | \nint repeatedNTimes(vector<int>& nums) {\n\tint currCount=0, currNum=0;\n\tfor(auto num: nums) {\n\t\tif(currCount==0) { currNum=num; }\n\t\tcurrCount = num==c | jaisw7 | NORMAL | 2021-12-20T01:35:29.910952+00:00 | 2021-12-20T01:35:58.117781+00:00 | 176 | false | ```\nint repeatedNTimes(vector<int>& nums) {\n\tint currCount=0, currNum=0;\n\tfor(auto num: nums) {\n\t\tif(currCount==0) { currNum=num; }\n\t\tcurrCount = num==currNum ? currCount+1 : currCount-1;\n\t\tif(currCount>1) { return currNum; }\n\t}\n\n\t// either of the last two elements can be repeated N times\n\tif(count(nums.begin(), nums.end(), nums.back())>1) { return nums.back(); } \n\treturn *(nums.rbegin()+1);\n}\n``` | 3 | 0 | ['C'] | 0 |
n-repeated-element-in-size-2n-array | [Python 3] Simple one-liner using zip() | Explained! | python-3-simple-one-liner-using-zip-expl-rr07 | If you found this explanation and solution helpful, please upvote!!\n\n-------\n\nLet\'s take an example:\n\nnums = [1,2,3,3]\n\n1) Create a new sorted list (k | TP0604 | NORMAL | 2021-10-06T09:03:55.819084+00:00 | 2021-10-06T12:12:43.240163+00:00 | 574 | false | If you found this explanation and solution helpful, please **upvote**!!\n\n-------\n\nLet\'s take an example:\n```\nnums = [1,2,3,3]\n```\n1) Create a new sorted list (`k = sorted(nums)`) or modify in-place (`nums.sort()`).\n2) Zip `k` and `k[1:]` to produce combinations as follows:\n\n ```\n k = [1, 2, 3, 3]\n ^ ^ ^ \n k[1:] = [2, 3, 3]\n \n #[(1, 2), (2, 3), (3, 3)]\n ```\n3) Iterate through `zip(k, k[1:])` and check whether `i == j`. Here, `i` = 3, `j` = 3, hence, `i == j`.\n4) Return the element inside the resulting list.\n\n----------\n\nSolution:\n```\nclass Solution(object):\n def findDuplicate(self, nums):\n k = sorted(nums); return [i for i, j in zip(k, k[1:]) if i == j][0]\n\t\t\n\t\t#Alternative\n\t\tnums.sort(); return [i for i, j in zip(nums, nums[1:]) if i == j][0]\n```\n\n--------\nSimilar problem: [287. Find the Duplicate Number](https://leetcode.com/problems/find-the-duplicate-number) | 3 | 0 | ['Python', 'Python3'] | 0 |
n-repeated-element-in-size-2n-array | ⭐ Easy C++ Solution ⭐ | easy-c-solution-by-divyaj101-eb0g | \nclass Solution {\npublic:\n int repeatedNTimes(vector<int>& A) {\n unordered_set<int> seen;\n for (int a: A) {\n if (seen.count(a) | divyaj101 | NORMAL | 2021-06-30T13:28:05.668176+00:00 | 2021-06-30T13:31:43.685248+00:00 | 90 | false | ```\nclass Solution {\npublic:\n int repeatedNTimes(vector<int>& A) {\n unordered_set<int> seen;\n for (int a: A) {\n if (seen.count(a))\n return a;\n seen.insert(a);\n }\n return -1;\n }\n};\n``` | 3 | 0 | ['C'] | 0 |
n-repeated-element-in-size-2n-array | C++ - Using Iterative Way and Map | c-using-iterative-way-and-map-by-jay0411-523f | 1. Simple for loop\n\nclass Solution {\npublic:\n int repeatedNTimes(vector<int>& nums) \n {\n int n = nums.size()/2;\n int arr[10000];\n | jay0411 | NORMAL | 2021-05-14T02:19:22.601555+00:00 | 2021-05-14T02:20:00.322374+00:00 | 185 | false | **1. Simple for loop**\n```\nclass Solution {\npublic:\n int repeatedNTimes(vector<int>& nums) \n {\n int n = nums.size()/2;\n int arr[10000];\n memset(arr, 0, sizeof(arr));\n for(int x : nums)\n arr[x]++;\n for(int i=0; i<10000; i++)\n {\n if(arr[i] == n)\n return i;\n } \n return -1;\n }\n};\n```\n**2. Using map**\n```\nclass Solution {\npublic:\n int repeatedNTimes(vector<int>& nums) \n {\n int n = nums.size()/2;\n unordered_map<int, int> mp; \n for(int x : nums)\n mp[x]++;\n for(auto x : mp)\n {\n if(x.second == n)\n return x.first;\n }\n return -1;\n }\n};\n```\n\n***************** Upvote if you like this solution ***************** | 3 | 0 | ['C', 'Iterator'] | 1 |
n-repeated-element-in-size-2n-array | Easy Solution with Set in Java | easy-solution-with-set-in-java-by-nitesh-5lp9 | Why Set, Notice that here all the repeated elements are only repeated, rest all are unique.\nFor Input: [1,2,3,3], Only 3 is repeated 2 times, rest are unique.\ | Nitesh_09 | NORMAL | 2021-04-10T17:16:30.728105+00:00 | 2021-04-10T17:16:30.728143+00:00 | 76 | false | Why Set, Notice that here all the repeated elements are only repeated, rest all are unique.\nFor Input: [1,2,3,3], Only 3 is repeated 2 times, rest are unique.\nFor Input: [2,1,2,5,3,2] only 2 are repeated 3 times, rest are Unique.\nFor Input: [5,1,5,2,5,3,5,4], Only 5 are repeated 4 times.\n\nSo Just need to check if any of the element is repeated more than 1, that would be the answer.\nHence Set is the best approach for this. As Element insertion is in O(1) time and would take only unique element \nfor the insertion. So if insertion is failed, means that is the repeated number as a solution . See below implementation.\n\n``\n\n\tclass Solution {\n\t\tpublic int repeatedNTimes(int[] A) {\n\t\t\tSet<Integer> set = new HashSet<>();\n\t\t\tfor(int i:A)\n\t\t\t\tif(!set.add(i))\n\t\t\t\t\treturn i;\n\t\t\treturn -1;\n\t\t}\n\t}\n\t\n``\n | 3 | 0 | [] | 0 |
n-repeated-element-in-size-2n-array | C++ Super Simple, Short and Easy Solution | c-super-simple-short-and-easy-solution-b-boma | \nclass Solution {\npublic:\n int repeatedNTimes(vector<int>& A) {\n set<int> s;\n for (auto a : A) {\n // If the number was seen al | yehudisk | NORMAL | 2020-12-20T12:15:57.039823+00:00 | 2020-12-20T12:15:57.039859+00:00 | 225 | false | ```\nclass Solution {\npublic:\n int repeatedNTimes(vector<int>& A) {\n set<int> s;\n for (auto a : A) {\n // If the number was seen already, we know this is the result.\n if (s.find(a) != s.end())\n return a;\n s.insert(a);\n }\n return 0;\n }\n};\n```\n**Like it? please upvote...** | 3 | 0 | ['C'] | 0 |
n-repeated-element-in-size-2n-array | C++ solution using map | c-solution-using-map-by-asif10h-uwar | \nclass Solution {\npublic:\n int repeatedNTimes(vector<int>& A) {\n map<int, int> mp;\n map<int, int> :: iterator it;\n for(auto i : A) | asif10h | NORMAL | 2020-06-20T18:29:40.136179+00:00 | 2020-06-20T18:29:40.136227+00:00 | 351 | false | ```\nclass Solution {\npublic:\n int repeatedNTimes(vector<int>& A) {\n map<int, int> mp;\n map<int, int> :: iterator it;\n for(auto i : A){\n mp[i]++;\n }\n int max = 0; \n int ans;\n for(auto it = mp.begin(); it != mp.end(); it++){\n if(it->second > max){\n max = it->second;\n ans = it->first;\n }\n }\n return ans;\n }\n};\n``` | 3 | 0 | ['C', 'C++'] | 3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.