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
surrounded-regions
[Python] DFS - Clean & Concise
python-dfs-clean-concise-by-hiepit-ajvi
\u2714\uFE0F Solution 1: DFS\npython\nclass Solution:\n def solve(self, board: List[List[str]]) -> None:\n m, n = len(board), len(board[0])\n v
hiepit
NORMAL
2021-09-28T15:32:52.148795+00:00
2024-04-05T22:33:58.284285+00:00
227
false
**\u2714\uFE0F Solution 1: DFS**\n```python\nclass Solution:\n def solve(self, board: List[List[str]]) -> None:\n m, n = len(board), len(board[0])\n visited = [[False] * n for _ in range(m)]\n DIR = [0, 1, 0, -1, 0]\n\n def dfs(r, c, shouldMarkO = False):\n if r < 0 or r == m or c < 0 or c == n or visited[r][c] or board[r][c] == "X":\n return\n\n visited[r][c] = True\n if shouldMarkO:\n board[r][c] = "X"\n for d in range(4):\n dfs(r + DIR[d],c + DIR[d+1], shouldMarkO)\n \n for c in range(n):\n dfs(0, c)\n dfs(m-1, c)\n\n for r in range(m):\n dfs(r, 0)\n dfs(r, n - 1)\n\n for r in range(m):\n for c in range(n):\n dfs(r, c, True)\n```\n**Complexity**\n- Time: `O(M*N)`, where `M <= 200` is number of rows, `N <= 200` is number of columns in the board.\n- Space: `O(M*N)`
10
0
['Depth-First Search']
1
surrounded-regions
Python beats 98% easy to understand DFS solution
python-beats-98-easy-to-understand-dfs-s-f9kw
Use "N" to mark all "O"s linked to boundary "O"s.\n\nclass Solution(object):\n def solve(self, board):\n """\n :type board: List[List[str]]\n
xuan__yu
NORMAL
2018-11-21T02:45:59.417125+00:00
2018-11-21T02:45:59.417163+00:00
834
false
Use "N" to mark all "O"s linked to boundary "O"s.\n```\nclass Solution(object):\n def solve(self, board):\n """\n :type board: List[List[str]]\n :rtype: void Do not return anything, modify board in-place instead.\n """\n if not board: return\n m, n = len(board), len(board[0])\n \n def fillN(i, j):\n if 0<=i<m and 0<=j<n and board[i][j] == "O":\n board[i][j] = "N"\n fillN(i+1, j)\n fillN(i-1, j)\n fillN(i, j+1)\n fillN(i, j-1)\n \n for i in range(m):\n if board[i][0] == "O": fillN(i,0)\n if board[i][n-1] == "O": fillN(i,n-1) \n for j in range(n):\n if board[0][j] == "O": fillN(0,j)\n if board[m-1][j] == "O": fillN(m-1,j)\n \n for i in range(m):\n for j in range(n):\n if board[i][j] != "N": board[i][j] = "X"\n else: board[i][j] = "O"\n```
10
0
[]
2
surrounded-regions
[20-ms C++][recommend for beginners]clean C++ implementation with detailed explanation
20-ms-crecommend-for-beginnersclean-c-im-vhqe
As far as I am concerned, after knowing about the BFS, it is all about details to use deque to do the BFS.\n\nthe idea is simple and the implementation is conci
rainbowsecret
NORMAL
2016-01-26T06:55:51+00:00
2016-01-26T06:55:51+00:00
954
false
As far as I am concerned, after knowing about the BFS, it is all about details to use deque to do the BFS.\n\nthe idea is simple and the implementation is concise \n\n\n class Solution {\n public:\n void solve(vector<vector<char>>& board) {\n if(board.size()<=1 || board[0].size()<=1) return;\n \n int m=board.size(), n=board[0].size();\n deque<pair<int, int>> q;\n for(int i=0; i<n; i++){\n if(board[0][i]=='O') q.push_back(make_pair(0, i));\n if(board[m-1][i]=='O') q.push_back(make_pair(m-1, i));\n }\n for(int i=1; i<m-1; i++){\n if(board[i][0]=='O') q.push_back(make_pair(i, 0));\n if(board[i][n-1]=='O') q.push_back(make_pair(i, n-1));\n }\n \n while(!q.empty()){\n pair<int, int> temp=q.front();\n q.pop_front();\n board[temp.first][temp.second]='N';\n \n if(temp.first-1>=0 && board[temp.first-1][temp.second]=='O'){\n q.push_back(make_pair(temp.first-1, temp.second));\n }\n if(temp.first+1<m && board[temp.first+1][temp.second]=='O'){\n q.push_back(make_pair(temp.first+1, temp.second));\n }\n \n if(temp.second-1>=0 && board[temp.first][temp.second-1]=='O'){\n q.push_back(make_pair(temp.first, temp.second-1));\n }\n if(temp.second+1<n && board[temp.first][temp.second+1]=='O'){\n q.push_back(make_pair(temp.first, temp.second+1));\n }\n }\n \n for(int i=0; i<m; i++){\n for(int j=0; j<n; j++){\n if(board[i][j]=='N') board[i][j]='O';\n else if(board[i][j]=='O') board[i][j]='X';\n }\n }\n \n return;\n }
10
0
[]
0
surrounded-regions
Java || 1 ms || faster than 99.93%
java-1-ms-faster-than-9993-by-shafiqul-rt0b
\n public void solve(char[][] board) {\n int m = board.length;\n int n = board[0].length;\n\n // traverse 1st and last col\n for
shafiqul
NORMAL
2022-10-16T01:33:02.038414+00:00
2022-10-16T01:33:02.038452+00:00
1,196
false
```\n public void solve(char[][] board) {\n int m = board.length;\n int n = board[0].length;\n\n // traverse 1st and last col\n for (int i = 0; i < m; i++){\n dfs(board, i, 0);\n dfs(board, i, n - 1);\n }\n\n // traverse 1st and last row\n for (int j = 0; j < n; j++){\n dfs(board, 0, j);\n dfs(board, m - 1, j);\n }\n\n for (int i = 0; i < m; i++){\n for (int j = 0; j < n; j++){\n if (board[i][j] == \'O\'){\n board[i][j] = \'X\';\n }\n if (board[i][j] == \'*\'){\n board[i][j] = \'O\';\n }\n }\n }\n }\n\n public void dfs(char[][] board, int i, int j){\n if (i < 0 || j < 0 || i >= board.length || j >= board[i].length){\n return;\n }\n\n if (board[i][j] == \'X\' || board[i][j] == \'*\'){\n return;\n }\n\n board[i][j] = \'*\';\n dfs(board, i + 1, j);\n dfs(board, i - 1, j);\n dfs(board, i, j + 1);\n dfs(board, i, j - 1);\n }\n```
9
0
['Depth-First Search', 'Java']
2
surrounded-regions
Javascript - Runtime - Faster than 95.54% - dfs
javascript-runtime-faster-than-9554-dfs-bncsw
Runtime - Faster than 95.54%\nMemory usage - Used less memory than 85.40%\n\n\nvar solve = function(board) {\n for(let i = 0; i < board.length; i++) {\n
ShashwatBangar
NORMAL
2021-10-30T07:10:08.785047+00:00
2021-10-30T07:11:00.216280+00:00
1,347
false
Runtime - Faster than 95.54%\nMemory usage - Used less memory than 85.40%\n\n```\nvar solve = function(board) {\n for(let i = 0; i < board.length; i++) {\n for(let j = 0; j < board[0].length; j++) {\n if(board[i][j] === \'O\' && (i === 0 || j === 0 || i === board.length - 1 || j === board[0].length - 1)) dfs(i, j);\n }\n }\n\n for(let i = 0; i < board.length; i++) {\n for(let j = 0; j < board[0].length; j++) {\n if(board[i][j] === \'Visited\') {\n board[i][j] = \'O\';\n } else {\n board[i][j] = \'X\';\n }\n } \n }\n \n function dfs(i, j) {\n if(i < 0 || i >= board.length || j < 0 || j >= board[i].length || board[i][j] === \'Visited\' || board[i][j] === \'X\') return\n \n board[i][j] = \'Visited\';\n dfs(i + 1, j);\n dfs(i - 1, j);\n dfs(i, j + 1);\n dfs(i, j - 1);\n \n return;\n }\n};\n```
9
1
['Depth-First Search', 'JavaScript']
0
surrounded-regions
Simple & Easy Java Solution Using DFS (1ms, 99% Beats)
simple-easy-java-solution-using-dfs-1ms-ciymz
class Solution {\n public void solve(char[][] board) {\n \n if(board.length==0)\n return;\n \n // this for loop handle
pankaj846
NORMAL
2020-08-26T10:08:33.493089+00:00
2020-08-26T10:08:33.493125+00:00
1,164
false
class Solution {\n public void solve(char[][] board) {\n \n if(board.length==0)\n return;\n \n // this for loop handles all boundary condition in 1st & last row.\n for(int i=0; i<board[0].length ;i++){\n if(board[0][i]==\'O\')\n DFS(board, 0, i);\n if(board[board.length-1][i]==\'O\')\n DFS(board, board.length-1, i);\n \n }\n \n // this for loop handles all boundary condition in 1st & last col.\n for(int i=0; i<board.length ;i++){\n if(board[i][0]==\'O\')\n DFS(board, i, 0);\n if(board[i][board[0].length-1]==\'O\')\n DFS(board, i, board[0].length-1);\n \n }\n \n for(int i=0; i<board.length; i++){\n for(int j=0; j<board[0].length; j++){\n \n if(board[i][j]==\'O\')\n board[i][j]=\'X\';\n \n if(board[i][j]==\'#\')\n board[i][j]=\'O\';\n }\n }\n }\n \n private void DFS(char[][]board, int i, int j){\n \n if(i<0 || j<0 || i>=board.length || j>=board[0].length || board[i][j]!=\'O\')\n return;\n \n board[i][j]= \'#\';\n \n DFS(board, i+1, j);\n DFS(board, i-1, j);\n DFS(board, i, j-1);\n DFS(board, i, j+1);\n }\n }\n
9
0
['Depth-First Search', 'Java']
2
surrounded-regions
Python recursion
python-recursion-by-gsan-6ku7
First mark the not surrounded ones as \'\'. These will be assigned to O. The rest become X\n\n\nclass Solution:\n def mark_border(self, i, j, board):\n
gsan
NORMAL
2020-06-17T07:29:41.315943+00:00
2020-06-17T07:29:41.315993+00:00
663
false
First mark the `not surrounded` ones as `\'\'`. These will be assigned to `O`. The rest become `X`\n\n```\nclass Solution:\n def mark_border(self, i, j, board):\n if i==-1 or i==len(board):\n return\n if j==-1 or j==len(board[0]):\n return\n if board[i][j]==\'O\':\n board[i][j]=\'\'\n self.mark_border(i-1, j, board)\n self.mark_border(i+1, j, board)\n self.mark_border(i, j-1, board)\n self.mark_border(i, j+1, board)\n \n \n def solve(self, board):\n if not board or not board[0]:\n return []\n \n M, N = len(board), len(board[0])\n for i in range(M):\n self.mark_border(i, 0, board)\n self.mark_border(i, N-1, board)\n for j in range(N):\n self.mark_border(0, j, board)\n self.mark_border(M-1, j, board)\n \n for i in range(M):\n for j in range(N):\n if board[i][j]==\'\':\n board[i][j]=\'O\'\n elif board[i][j]==\'O\':\n board[i][j]=\'X\'\n```
9
0
[]
0
surrounded-regions
Efficient Java Solution using recursion
efficient-java-solution-using-recursion-2uujm
public class Solution {\n public void solve(char[][] board) {\n if(board==null || board.length<=1 ||board[0].length<=1)\n retur
chasethebug
NORMAL
2015-11-29T09:52:57+00:00
2015-11-29T09:52:57+00:00
1,934
false
public class Solution {\n public void solve(char[][] board) {\n if(board==null || board.length<=1 ||board[0].length<=1)\n return;\n int rows = board.length;\n int cols = board[0].length;\n for(int i=0; i<rows; i++){\n if(board[i][0]=='O') helper(board,i,0);\n if(board[i][cols-1]=='O') helper(board,i, cols-1);\n }\n for(int i=1; i<cols-1; i++){\n if(board[0][i]=='O') helper(board,0,i);\n if(board[rows-1][i]=='O') helper(board,rows-1,i);\n }\n \n for(int i=0; i<rows; i++){\n for(int j=0; j<cols; j++){\n if(board[i][j]=='I') board[i][j]='O';\n else if(board[i][j]=='O') board[i][j]='X';\n }\n }\n }\n public void helper(char[][] board, int r, int c){\n board[r][c] = 'I';\n if(r-1>0 && board[r-1][c]=='O'){helper(board, r-1,c);}\n if(r+1<board.length-1 && board[r+1][c]=='O'){helper(board, r+1,c);}\n if(c+1<board[0].length-1 && board[r][c+1]=='O'){helper(board, r,c+1);}\n if(c-1>0 && board[r][c-1]=='O'){helper(board, r,c-1);}\n }\n }
9
0
[]
1
surrounded-regions
5ms Simple DFS Java Solution
5ms-simple-dfs-java-solution-by-arjunsun-0eil
This problem can be dealt with in a very simple way. A 'O' will not be surrounded by all sides only if it is linked (directly or through another 'O') to a 'O' t
arjunsunbuffaloedu
NORMAL
2016-11-11T20:56:33.696000+00:00
2018-10-01T23:44:42.964668+00:00
1,260
false
This problem can be dealt with in a very simple way. A 'O' will not be surrounded by all sides only if it is linked (directly or through another 'O') to a 'O' that is on the boundary row or column.\n\nThis means that if all 4 boundaries have only 'X' then all the characters can be switched to 'X' \n\nFor example if your region is defined like this\n\nXXXX\nXOOX\nXOOX\nXXXX then we can convert all the 'O' to'X's .\n\nSolution: Run through the boundaries and perform dfs when you come across a 'O' . Switch all adjoining 'O' to another character. (I have chosen to switch them to 'Y'). This way all th e'O's that are not surrounded completely by 'X' are switched to 'Y's .\n\nAfter simply run through the matrix again and switch all 'Y' to 'O' and all 'O' to 'X'.\n\n\n```\npublic class Solution {\n \n public void solve(char[][] board) {\n \n if(board==null || board.length==0) return;\n \n int row = board.length;\n int col = board[0].length;\n \n //check first and last col\n for(int i=0;i<row;i++){\n \n if(board[i][0]=='O') getEmAll(board,i,1);\n if(board[i][col-1]=='O') getEmAll(board,i,col-2);\n }\n \n //check first and last row\n for(int i=0;i<col;i++){\n \n if(board[0][i]=='O') getEmAll(board,1,i);\n if(board[row-1][i]=='O') getEmAll(board,row-2,i);\n }\n \n\n //Switch all 'O's to 'X's and 'Y's to 'O's\n for(int i=1;i<row-1;i++)\n {\n for(int j=1;j<col-1;j++)\n if(board[i][j]=='Y') board[i][j]='O';\n else if(board[i][j]=='O') board[i][j]='X';\n }\n\t}\n\t \n\tpublic void getEmAll(char[][] board, int row, int col){\n\t \n\t if(row>=board.length-1 || row<=0 || col>=board[0].length-1 || col<=0) return;\n\t \n\t if(board[row][col]=='X' || board[row][col]=='Y') return;\n\t if(board[row][col]=='O') board[row][col]='Y';\n\t \n\t getEmAll(board,row+1,col);\n\t getEmAll(board,row,col+1);\n\t getEmAll(board,row-1,col);\n\t getEmAll(board,row,col-1);\n\t \n\t} \n\t \n}\n```
9
0
[]
2
surrounded-regions
Why this code has runtime error?
why-this-code-has-runtime-error-by-clubm-saju
Hi,\n\nThe first version of my submission has runtime error, and I debugged it on local machine, it seems to be stack overflow. But if I add the if with comment
clubmaster
NORMAL
2015-11-08T13:33:51+00:00
2015-11-08T13:33:51+00:00
1,953
false
Hi,\n\nThe first version of my submission has runtime error, and I debugged it on local machine, it seems to be stack overflow. But if I add the if with comment "modified version", then it can pass. I don't understand. Is the case kind of corner? Or the test case is not large enough to make the modified version fail?\n\n class Solution {\n public:\n void solve(vector<vector<char>>& board) {\n int rows=board.size();\n if(rows<=2) return;\n int columns=board.front().size();\n if(columns<=2) return;\n int i=0, j=0;\n for(; j<columns-1; ++j){\n populate(board, i, j, rows, columns);\n }\n for(; i<rows-1; ++i){\n populate(board, i, j, rows, columns);\n }\n for(; j>0; --j){\n populate(board, i, j, rows, columns);\n }\n for(; i>0; --i){\n populate(board, i, j, rows, columns);\n }\n for(i=0; i<rows; ++i){\n for(j=0; j<columns; ++j){\n if(board[i][j]=='Z') board[i][j]='O';\n else if(board[i][j]=='O') board[i][j]='X';\n }\n }\n }\n void populate(vector<vector<char>>& board, int i, int j, int rows, int columns){\n if(i<0 || i>=rows || j<0 || j>=columns) return;\n if(board[i][j]=='O'){\n board[i][j]='Z';\n populate(board, i+1, j, rows, columns);\n populate(board, i-1, j, rows, columns);\n populate(board, i, j+1, rows, columns);\n if(j>1) // modified version\n populate(board, i, j-1, rows, columns);\n }\n }};
9
0
[]
3
surrounded-regions
DFS Approach | 100% Runtime | Easy to Understand
dfs-approach-100-runtime-easy-to-underst-22pn
Basically, all the boundary \'O\'s need not to be changed.\nUse DFS to visit the boundary \'O\', turn it into \'V\' and explore the node.\nIn this way, we chang
niro11
NORMAL
2023-01-01T12:01:59.548277+00:00
2023-01-01T12:01:59.548318+00:00
1,187
false
Basically, all the boundary \'O\'s need not to be changed.\nUse DFS to visit the boundary \'O\', turn it into \'V\' and explore the node.\nIn this way, we change the remaining \'O\'s to \'X\'s.\nConvert the \'V\'s to \'O\'s.\n\n# Code\n```\nclass Solution {\n public void solve(char[][] board) {\n int rows = board.length;\n int cols = board[0].length;\n for(int i=0; i<rows; i++){\n for(int j=0; j<cols; j++){\n if(i*j==0 || i==rows-1 || j==cols-1){ \n //We check for Boundary \'O\'s and turn them into \'V\'.\n //These are valid \'O\'s and need not to be changed to \'X\'s.\n if(board[i][j] == \'O\'){\n dfs(board,i,j);\n }\n }\n }\n }\n//Iterate over the whole grid, change remaining \'O\'s to \'X\'s.\n//Change \'V\'s to \'O\'s\n for(int i=0; i<rows; i++){\n for(int j=0; j<cols; j++){\n if(board[i][j] == \'O\'){\n board[i][j] = \'X\';\n }\n else if(board[i][j] == \'V\'){\n board[i][j] = \'O\';\n }\n }\n }\n }\n\n//Main DFS Function to convert all the boundary \'O\'s to \'V\'s\n\n private void dfs(char[][] board, int i, int j){\n if(i<0 || j<0 || i>=board.length || j>=board[0].length || board[i][j] != \'O\'){\n return;\n }\n board[i][j] = \'V\';\n dfs(board,i+1,j);\n dfs(board,i-1,j);\n dfs(board,i,j+1);\n dfs(board,i,j-1);\n }\n\n}\n```
8
0
['Java']
1
surrounded-regions
✅ [Solution] Swift: Surrounded Regions (+ test cases)
solution-swift-surrounded-regions-test-c-r52w
swift\nclass Solution {\n func solve(_ board: inout [[Character]]) {\n for r in board.indices {\n for c in board[r].indices where board[r][
AsahiOcean
NORMAL
2022-01-03T05:47:37.258364+00:00
2022-01-03T05:47:37.258416+00:00
960
false
```swift\nclass Solution {\n func solve(_ board: inout [[Character]]) {\n for r in board.indices {\n for c in board[r].indices where board[r][c] == "O" {\n var curr = board\n if dfs(&curr, r, c) { board = curr }\n }\n }\n }\n \n // valid region board\n private func dfs(_ board: inout [[Character]], _ r: Int, _ c: Int) -> Bool {\n if r < 0 || r >= board.count || c < 0 || c >= board[r].count { return false }\n if board[r][c] != "O" { return true }\n \n board[r][c] = "X"\n \n for (dx, dy) in [(1,0), (-1,0), (0,1), (0,-1)] {\n let nr = r + dx, nc = c + dy\n if !dfs(&board, nr, nc) { return false }\n }\n return true\n }\n}\n```\n\n---\n\n<p>\n<details>\n<summary>\n<img src="https://git.io/JDblm" height="24">\n<b>TEST CASES</b>\n</summary>\n\n<p><pre>\n<b>Result:</b> Executed 2 tests, with 0 failures (0 unexpected) in 0.010 (0.012) seconds\n</pre></p>\n\n```swift\nimport XCTest\n\nclass Tests: XCTestCase {\n \n private let solution = Solution()\n \n /// Surrounded regions should not be on the border, which means that any \'O\' on the\n /// border of the board are not flipped to \'X\'. Any \'O\' that is not on the border and it is not\n /// connected to an \'O\' on the border will be flipped to \'X\'. Two cells are connected if they are\n /// adjacent cells connected horizontally or vertically.\n func test0() {\n var board: [[Character]] = [["X","X","X","X"],\n ["X","O","O","X"],\n ["X","X","O","X"],\n ["X","O","X","X"]]\n solution.solve(&board)\n XCTAssertEqual(board, [["X","X","X","X"],\n ["X","X","X","X"],\n ["X","X","X","X"],\n ["X","O","X","X"]])\n }\n \n func test1() {\n var board: [[Character]] = [["X"]]\n solution.solve(&board)\n XCTAssertEqual(board, [["X"]])\n }\n}\n\nTests.defaultTestSuite.run()\n```\n\n</details>\n</p>
8
0
['Depth-First Search', 'Swift']
1
surrounded-regions
Not Best but Intuitive solution
not-best-but-intuitive-solution-by-rieme-7vo4
Okay, so this is my first ever post ever, any feedback is appreciated. Thanks for reading in advance.\n\nNow, my intuition is simple as you will also realise fr
riemeltm
NORMAL
2021-11-01T12:01:03.642440+00:00
2021-11-01T12:01:03.642486+00:00
113
false
Okay, so this is my first ever post ever, any feedback is appreciated. Thanks for reading in advance.\n\nNow, my intuition is simple as you will also realise from the following steps:\n\n**Note:** Observe that, any component of "O" that will not be converted to "X" wil have atleast one cell that will lie on the boundary.\n\n1. I will traverse in the boundary of the board and check for cells with "O".\n\n2. For every cell with value as "O" in the boundary, I will mark the full component (component here is a cluster of "O") of that cell as bad component (By making it unreachable as you will see from the code).\n\n3. Then, I will do a simple DFS and convert all the "O" to "X" which are not in a bad component.\n\nHere goes the code for my approach:\n\n```\nclass Solution {\npublic:\n \n int dx[4] = {0, 0, 1, -1};\n int dy[4] = {1, -1, 0, 0};\n \n bool is_valid(vector<vector<char>>& board, int x, int y, int n, int m, vector<vector<bool>>& vis){\n \n if(x>=0 and x<n and y >= 0 and y < m and board[x][y] == \'O\' and !vis[x][y])\n return true;\n \n return false;\n }\n \n void fill_comp(int x, int y, vector<vector<char>>& board, vector<vector<bool>>& vis){\n vis[x][y] = true;\n board[x][y] = \'X\';\n \n int n = board.size();\n int m = board[0].size();\n \n for(int i{}; i<4; ++i){\n int xx = x+dx[i];\n int yy = y+dy[i];\n \n if(is_valid(board, xx, yy, n, m, vis)){\n \n fill_comp(xx, yy, board, vis);\n }\n }\n }\n \n void mark_bad(vector<vector<bool>>&vis, vector<vector<char>>& board, int x, int y){\n \n vis[x][y] = true; //marking bad means already making it visited so that it won\'t get visited while doing main dfs\n int n = board.size();\n int m = board[0].size();\n \n for(int i{}; i<4; ++i){\n int xx = x + dx[i];\n int yy = y + dy[i];\n \n if(is_valid(board, xx, yy, n, m, vis)){\n \n mark_bad(vis, board, xx, yy);\n }\n }\n \n }\n \n void solve(vector<vector<char>>& board) {\n \n int n = board.size();\n int m = board[0].size();\n vector<vector<bool>>vis(n, vector<bool>(m, 0));\n \n\t\t// Traversing the boundary and marking bad components\n for(int i{}; i<n; ++i){\n if(board[i][0] == \'O\' and !vis[i][0]){\n mark_bad(vis, board, i, 0);\n }\n \n if(board[i][m-1] == \'O\' and !vis[i][m-1]){\n mark_bad(vis, board, i, m-1);\n }\n }\n \n for(int j{}; j<m; ++j){\n \n if(board[0][j]==\'O\' and !vis[0][j]){\n mark_bad(vis, board, 0, j);\n }\n if(board[n-1][j] == \'O\' and !vis[n-1][j]){\n mark_bad(vis, board, n-1, j);\n }\n }\n \n\t\t//main dfs fill_comp that will fill good components of "O" with "X"\n for(int i{}; i<n; ++i){\n for(int j{}; j<m; ++j){\n \n if(board[i][j] == \'O\' and !vis[i][j]){\n \n fill_comp(i, j, board, vis);\n }\n }\n }\n }\n};\n```
8
0
[]
2
surrounded-regions
C++ Simple and Easy-to-Understand Clean DFS Solution
c-simple-and-easy-to-understand-clean-df-2o7j
\nclass Solution {\npublic:\n void DFS(vector<vector<char>>& board, int x, int y, char c) {\n if (x < 0 || x >= board.size() || y < 0 || y >= board[0]
yehudisk
NORMAL
2021-07-13T07:46:11.676908+00:00
2021-07-13T07:46:11.676952+00:00
298
false
```\nclass Solution {\npublic:\n void DFS(vector<vector<char>>& board, int x, int y, char c) {\n if (x < 0 || x >= board.size() || y < 0 || y >= board[0].size() || board[x][y] != \'O\') return;\n \n board[x][y] = c;\n \n DFS(board, x + 1, y, c);\n DFS(board, x - 1, y, c);\n DFS(board, x, y + 1, c);\n DFS(board, x, y - 1, c);\n }\n \n void solve(vector<vector<char>>& board) {\n int n = board.size(), m = board[0].size();\n \n // Change the \'O\'s connected to border to \'!\'\n for (int i = 0; i < n; i++) {\n if (board[i][0] == \'O\') DFS(board, i, 0, \'!\');\n if (board[i][m-1] == \'O\') DFS(board, i, m-1, \'!\');\n }\n \n for (int i = 0; i < m; i++) {\n if (board[0][i] == \'O\') DFS(board, 0, i, \'!\');\n if (board[n-1][i] == \'O\') DFS(board, n-1, i, \'!\');\n }\n \n // Change all remaining \'O\'s to \'x\'\n for (int i = 1; i < n-1; i++) {\n for (int j = 1; j < m-1; j++) {\n if (board[i][j] == \'O\') board[i][j] = \'X\';\n }\n }\n \n // Change back \'!\' to \'O\'\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < m; j++) {\n if (board[i][j] == \'!\') board[i][j] = \'O\';\n }\n }\n }\n};\n```\n**Like it? please upvote!**
8
0
['C']
0
surrounded-regions
Java clean code
java-clean-code-by-user6227l-wa31
\nclass Solution {\n public void solve(char[][] board) {\n if(board.length == 0)\n return;\n for(int i=0;i<board.length;i++){\n
user6227l
NORMAL
2021-01-30T05:44:41.758843+00:00
2021-01-30T05:44:41.758890+00:00
558
false
```\nclass Solution {\n public void solve(char[][] board) {\n if(board.length == 0)\n return;\n for(int i=0;i<board.length;i++){\n for(int j=0;j<board[0].length;j++){\n if(i==0 || j==0 || i==board.length-1 || j==board[0].length-1){\n dfs(i,j,board);\n }\n }\n }\n\n for(int i=0;i<board.length;i++){\n for(int j=0;j<board[0].length;j++){\n if(board[i][j]==\'-\'){\n board[i][j]=\'O\';\n }\n else{\n board[i][j]=\'X\'; \n }\n }\n }\n\n }\n\n private void dfs(int i, int j, char[][] board) {\n if(i<0 || j<0 || i>board.length-1 || j>board[0].length-1 || board[i][j]!=\'O\'){\n return;\n }\n board[i][j]=\'-\';\n\n dfs(i+1,j,board);\n dfs(i-1,j,board);\n dfs(i,j+1,board);\n dfs(i,j-1,board);\n\n }\n}\n```
8
2
['Depth-First Search', 'Java']
0
surrounded-regions
C# DFS
c-dfs-by-bacon-2k6w
\npublic class Solution {\n public void Solve(char[][] board) {\n var n = board.Length;\n\n if (n == 0) return;\n var m = board[0].Lengt
bacon
NORMAL
2019-05-06T01:47:19.981894+00:00
2019-05-06T01:47:19.981959+00:00
540
false
```\npublic class Solution {\n public void Solve(char[][] board) {\n var n = board.Length;\n\n if (n == 0) return;\n var m = board[0].Length;\n\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) && board[i][j] == \'O\') {\n DFS(board, i, j);\n }\n }\n }\n\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < m; j++) {\n if (board[i][j] == \'O\') {\n board[i][j] = \'X\';\n }\n }\n }\n\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < m; j++) {\n if (board[i][j] == \'C\') {\n board[i][j] = \'O\';\n }\n }\n }\n }\n\n private void DFS(char[][] board, int x, int y) {\n var n = board.Length;\n var m = board[0].Length;\n\n if (x >= n || x < 0 || y >= m || y < 0) {\n return;\n }\n\n if (board[x][y] == \'C\' || board[x][y] == \'X\') return;\n\n board[x][y] = \'C\';\n var directions = new (int, int)[] { (0, 1), (0, -1), (1, 0), (-1, 0) };\n\n foreach (var direction in directions) {\n var nextX = x + direction.Item1;\n var nextY = y + direction.Item2;\n\n DFS(board, nextX, nextY);\n }\n\n }\n}\n```
8
0
[]
0
surrounded-regions
Java 6ms DFS solution, easy to understand and relatively short
java-6ms-dfs-solution-easy-to-understand-7d7c
Idea is simple: the only 'O's that will NOT change to 'X's are those at the edges and those horizontally or vertically connected to the 'O's at the edges. So, f
davidsunsbk
NORMAL
2016-03-29T21:33:05+00:00
2016-03-29T21:33:05+00:00
2,577
false
Idea is simple: the only 'O's that will NOT change to 'X's are those at the edges and those horizontally or vertically connected to the 'O's at the edges. So, first find out all the 'O's at the edges, mark them as 'M', and keep checking their surrounding 'O's and mark them as 'M'. Then loop the board again, change 'O's to 'X's and change those who was marked as 'M's to 'O's. Done.\n\n public class Solution {\n public void solve(char[][] board) {\n for (int i = 0; i < board.length; i++) {\n for (int j = 0; j < board[i].length; j++) {\n if ((i == 0 || i == board.length-1 || j == 0 || j == board[i].length-1) && (board[i][j] == 'O')) {\n board[i][j] = 'M';\n connected(i, j, board);\n }\n }\n }\n for (int i = 0; i < board.length; i++) {\n for (int j = 0; j < board[i].length; j++) {\n if (board[i][j] == 'O') {\n board[i][j] = 'X';\n }\n else if (board[i][j] == 'M') {\n board[i][j] = 'O';\n } \n }\n }\n }\n \n public void connected(int i, int j, char[][] board) {\n if (i-1 > 0 && board[i-1][j] == 'O') {\n board[i-1][j] = 'M';\n connected(i-1, j, board);\n }\n if (i+1 < board.length-1 && board[i+1][j] == 'O') {\n board[i+1][j] = 'M';\n connected(i+1, j, board);\n }\n if (j-1 > 0 && board[i][j-1] == 'O') {\n board[i][j-1] = 'M';\n connected(i, j-1, board);\n }\n if (j+1 < board[i].length-1 && board[i][j+1] == 'O') {\n board[i][j+1] = 'M';\n connected(i, j+1, board);\n }\n }\n }
8
1
['Depth-First Search']
8
surrounded-regions
Simple DFS solution || JAVA || Beats 100%
simple-dfs-solution-java-beats-100-by-sa-ds6b
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
saad_hussain_
NORMAL
2024-05-12T19:46:53.236919+00:00
2024-05-12T19:46:53.236948+00:00
1,249
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 int row = 0;\n int col = 0;\n \n public void solve(char[][] board) {\n row = board.length;\n col = board[0].length;\n \n // Mark \'O\' cells on the borders and initiate DFS from them\n for (int i = 0; i < row; i++) {\n if (board[i][0] == \'O\') {\n dfs(board, i, 0);\n }\n if (board[i][col - 1] == \'O\') {\n dfs(board, i, col - 1);\n }\n }\n for (int j = 0; j < col; j++) {\n if (board[0][j] == \'O\') {\n dfs(board, 0, j);\n }\n if (board[row - 1][j] == \'O\') {\n dfs(board, row - 1, j);\n }\n }\n \n // Convert remaining \'O\' cells to \'X\', and revert marked cells back to \'O\'\n for (int i = 0; i < row; i++) {\n for (int j = 0; j < col; j++) {\n if (board[i][j] == \'O\') {\n board[i][j] = \'X\';\n } else if (board[i][j] == \'1\') {\n board[i][j] = \'O\';\n }\n }\n }\n }\n \n private void dfs(char[][] board, int i, int j) {\n // Out of bounds check\n if (i < 0 || i >= row || j < 0 || j >= col || board[i][j] != \'O\') {\n return;\n }\n // Mark current \'O\' cell as visited\n board[i][j] = \'1\';\n \n // DFS in all four directions\n dfs(board, i, j - 1); // left\n dfs(board, i - 1, j); // up\n dfs(board, i, j + 1); // right\n dfs(board, i + 1, j); // down\n }\n}\n\n```
7
0
['Java']
1
surrounded-regions
Python || 97.64% Faster || BFS || DFS || Two Approaches
python-9764-faster-bfs-dfs-two-approache-d0p4
BFS Approach:\n\ndef solve(self, board: List[List[str]]) -> None:\n """\n Do not return anything, modify board in-place instead.\n """\n
pulkit_uppal
NORMAL
2023-03-19T11:49:18.095414+00:00
2023-03-19T11:50:14.759248+00:00
1,360
false
**BFS Approach:**\n```\ndef solve(self, board: List[List[str]]) -> None:\n """\n Do not return anything, modify board in-place instead.\n """\n m=len(board)\n n=len(board[0])\n q=deque()\n for i in range(m):\n for j in range(n):\n if i==0 or i==m-1 or j==0 or j==n-1:\n if board[i][j]==\'O\':\n board[i][j]=\'Y\'\n q.append((i,j)) \n while q:\n a,b=q.popleft()\n for r,c in [(a-1,b),(a+1,b),(a,b-1),(a,b+1)]:\n if 0<=r<m and 0<=c<n and board[r][c]==\'O\':\n board[r][c]="Y"\n q.append((r,c))\n for i in range(m):\n for j in range(n):\n if board[i][j]==\'O\':\n board[i][j]=\'X\'\n elif board[i][j]==\'Y\':\n board[i][j]=\'O\'\n```\n**DFS Approach:**\n```\ndef solve(self, board: List[List[str]]) -> None:\n """\n Do not return anything, modify board in-place instead.\n """\n def dfs(sv):\n a,b=sv[0],sv[1]\n board[a][b]=\'Y\'\n for r,c in [(a-1,b),(a+1,b),(a,b-1),(a,b+1)]:\n if 0<=r<m and 0<=c<n and board[r][c]==\'O\':\n board[r][c]="Y"\n dfs((r,c))\n m=len(board)\n n=len(board[0])\n for i in range(m):\n for j in range(n):\n if i==0 or i==m-1 or j==0 or j==n-1:\n if board[i][j]==\'O\':\n dfs((i,j))\n for i in range(m):\n for j in range(n):\n if board[i][j]==\'O\':\n board[i][j]=\'X\'\n elif board[i][j]==\'Y\':\n board[i][j]=\'O\'\n```\n\n**An upvote will be encouraging**
7
0
['Depth-First Search', 'Breadth-First Search', 'Graph', 'Python', 'Python3']
0
surrounded-regions
Default code compile error
default-code-compile-error-by-suitier-y4s9
When I submit c++ default code, it gives compile error.\nIs there anyone in the same situation?\n\n- Code\n\nclass Solution {\npublic:\n void solve(vector<ve
suitier
NORMAL
2020-04-28T22:50:49.787533+00:00
2020-04-29T00:07:29.344219+00:00
227
false
When I submit c++ default code, it gives compile error.\nIs there anyone in the same situation?\n\n- Code\n```\nclass Solution {\npublic:\n void solve(vector<vector<char>>& board) {\n\n }\n};\n```\n\n- Error message\n```\nCompile Error:\n\nLine 30: Char 17: fatal error: no matching member function for call to \'resize\'\n param_1.resize();\n ~~~~~~~~^~~~~~\n/usr/bin/../lib/gcc/x86_64-linux-gnu/8/../../../../include/c++/8/bits/stl_vector.h:824:7: note: candidate function not viable: requires single argument \'__new_size\', but no arguments were provided\n resize(size_type __new_size)\n ^\n/usr/bin/../lib/gcc/x86_64-linux-gnu/8/../../../../include/c++/8/bits/stl_vector.h:844:7: note: candidate function not viable: requires 2 arguments, but 0 were provided\n resize(size_type __new_size, const value_type& __x)\n ^\n1 error generated.\n```
7
0
[]
5
surrounded-regions
Java - Union Find
java-union-find-by-wilsoncursino-kyaz
\nclass Solution {\n \n // Union Find \n // Intuition: \n // - We need to separate \'O\' in the borders from the other \'O\'\n // - S
wilsoncursino
NORMAL
2020-04-11T21:18:38.311630+00:00
2020-04-11T21:18:38.311691+00:00
267
false
```\nclass Solution {\n \n // Union Find \n // Intuition: \n // - We need to separate \'O\' in the borders from the other \'O\'\n // - So, if a node \'O\' is on the border connect it to the virtual node.\n // - All the others \'O\' connect to their \'O\' neighbors. (eventually, if they are tied to a border \'O\', they will connect)\n // - After that, traverse the board, flipping the \'O\' *** NOT *** connected to the virtual.\n \n public void solve(char[][] board) {\n if(board == null || board.length == 0) return;\n int row = board.length;\n int col = board[0].length;\n UnionFind uf = new UnionFind(row, col);\n for(int i=0; i<row; i++){\n for(int j=0; j<col; j++){\n \n //Is boarder? Is \'O\'? ... connect to the virtual.\n if((i == 0 || j == 0 || i == row - 1 || j == col - 1) && (board[i][j] == \'O\')){\n uf.union(uf.virtualNode, index(col, i, j)); //connect to virtual\n continue;\n } \n \n //not border, but \'O\'\n if(board[i][j] == \'O\') {\n int id = index(col, i, j);\n // connect the neighbors\n if(i + 1 < row && board[i + 1][j] == \'O\') uf.union(id, index(col, i + 1, j));\n if(i - 1 >= 0 && board[i - 1][j] == \'O\') uf.union(id, index(col, i - 1, j));\n if(j + 1 < col && board[i][j + 1] == \'O\') uf.union(id, index(col, i, j + 1));\n if(j - 1 >= 0 && board[i][j - 1] == \'O\') uf.union(id, index(col, i, j - 1));\n }\n }\n }\n \n for(int i=0; i<row; i++)\n for(int j=0; j<col; j++)\n if(board[i][j] == \'O\' && !uf.connected(index(col, i, j), uf.virtualNode)) \n board[i][j] = \'X\';\n }\n \n class UnionFind{\n int[] parent;\n int[] size;\n int virtualNode;\n \n UnionFind(int N, int M){\n virtualNode = N * M;\n parent = new int[N * M + 1]; //extra for the virtual Node\n size = new int[N * M + 1]; \n for(int i=0; i< N * M +1; i++){\n parent[i] = i;\n size[i] = 1;\n }\n }\n \n int find(int i){\n while(i != parent[i]){\n parent[i] = parent[parent[i]]; // compress\n i = parent[i];\n }\n return i;\n }\n boolean connected(int p, int q){\n return find(p) == find(q);\n }\n void union(int p, int q){\n int rootP = find(p);\n int rootQ = find(q);\n if(rootP == rootQ) return; //the same parent\n \n if(size[rootP] < size[rootQ]){\n parent[rootP] = rootQ;\n size[rootQ] += size[rootP];\n }else{\n parent[rootQ] = rootP;\n size[rootP] += size[rootQ];\n }\n }\n }\n int index(int col, int i, int j){\n return i * col + j;\n }\n}\n```
7
0
[]
2
surrounded-regions
Java | DFS, Union-Find, Union-Find Rank
java-dfs-union-find-union-find-rank-by-a-v71v
```\n/\n * Approach1 Logical Thinking We aim to set all O\'s which doesn\'t locate at\n * borders or connect to O at borders to X. We mark all O\'s at borders a
aurbatao
NORMAL
2020-03-22T20:04:31.445385+00:00
2020-03-22T20:07:31.665716+00:00
640
false
```\n/*\n * Approach1 Logical Thinking We aim to set all O\'s which doesn\'t locate at\n * borders or connect to O at borders to X. We mark all O\'s at borders and apply\n * DFS at each O at boarders to mark all O\'s connected to it. The un-marked O\'s\n * ought to be set X.\n * \n * Trick We search for invalid candidates (and exclude them) rather than search\n * for valid candidates.\n */\nboolean[][] visited;\n\npublic void solve(char[][] board) {\n\n\tif (board == null || board.length == 0 || board[0].length == 0) {\n\t\treturn;\n\t}\n\n\tint rows = board.length, cols = board[0].length;\n\tvisited = new boolean[rows][cols];\n\n\t// check first and last column\n\tfor (int i = 0; i < rows; i++) {\n\n\t\tif (board[i][0] == \'O\' && !visited[i][0]) {\n\t\t\tdetectConnected(i, 0, board);\n\t\t}\n\n\t\tif (board[i][cols - 1] == \'O\' && !visited[i][cols - 1]) {\n\t\t\tdetectConnected(i, cols - 1, board);\n\t\t}\n\t}\n\n\t// check first and last row\n\tfor (int j = 0; j < cols; j++) {\n\n\t\tif (board[0][j] == \'O\' && !visited[0][j]) {\n\t\t\tdetectConnected(0, j, board);\n\t\t}\n\n\t\tif (board[rows - 1][j] == \'O\' && !visited[rows - 1][j]) {\n\t\t\tdetectConnected(rows - 1, j, board);\n\t\t}\n\t}\n\n\tfor (int i = 0; i < rows; i++) {\n\t\tfor (int j = 0; j < cols; j++) {\n\t\t\tif (board[i][j] == \'O\' && !visited[i][j]) {\n\t\t\t\tboard[i][j] = \'X\';\n\t\t\t}\n\t\t}\n\t}\n}\n\n// function to set all nodes to visited true, if they are connected to \'O\' on\n// the border\nprivate void detectConnected(int x, int y, char[][] board) {\n\n\tif (x < 0 || x >= board.length || y < 0 || y >= board[0].length || visited[x][y] || board[x][y] != \'O\') {\n\t\treturn;\n\t}\n\n\tvisited[x][y] = true;\n\n\tdetectConnected(x + 1, y, board);\n\tdetectConnected(x, y + 1, board);\n\tdetectConnected(x - 1, y, board);\n\tdetectConnected(x, y - 1, board);\n}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t/**********************\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t * Approach2: Union-Find\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t ********************/\n/*\n * Approach2: https://leetcode.com/problems/surrounded-regions/discuss/167165/Java-Union-Find-with-Explanations\n * We aim to find all \'O\'s such that it is on the\n * border or it is connected to an \'O\' on the border. If we regard \'O\' mentioned\n * above as a node (or an element), the problem becomes to find the connected\n * components (or disjoint sets) connected to borders. So-called borders should\n * also be represented as an element, so elements connected to it can be merged\n * with it into a set. That\'s the usage of dummyBorder.\n * \n * \t\tfor O in board\n\t\t\tif O is on border\n\t\t\t\tunion(dummyBorder, O)\n\t\t\telse\n\t\t\t\tfor neighbour of O\n\t\t\t\t\tif (neighbour is \'O\') \n\t\t\t\t\t\tunion(neighbour, O)\n\n\t\tfor each cell\n\t\t\tif cell is \'O\' && (find(cel) != find(dummyBorder))\n\t\t\t\tflip\n */\nprivate static int[][] directions = { { 0, 1 }, { 0, -1 }, { 1, 0 }, { -1, 0 } };\n\npublic void solveApproach2(char[][] board) {\n\n\tif (board == null || board.length == 0) {\n\t\treturn;\n\t}\n\n\tUnionFindRank disjointSets = new UnionFindRank(board);\n\tint rows = board.length, cols = board[0].length;\n\tint dummyBorder = rows * cols;\n\n\tfor (int x = 0; x < rows; x++) {\n\t\tfor (int y = 0; y < cols; y++) {\n\t\t\tif (board[x][y] == \'O\') {\n\t\t\t\tint borderO = x * cols + y;\n\t\t\t\tif (x == 0 || x == rows - 1 || y == 0 || y == cols - 1) {\n\t\t\t\t\tdisjointSets.union(dummyBorder, borderO);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tfor (int[] dir : directions) {\n\t\t\t\t\tint nx = x + dir[0];\n\t\t\t\t\tint ny = y + dir[1];\n\t\t\t\t\tif (nx >= 0 && ny >= 0 && nx < rows && ny < cols && board[nx][ny] == \'O\') {\n\t\t\t\t\t\tint neighbor = nx * cols + ny;\n\t\t\t\t\t\tdisjointSets.union(borderO, neighbor);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tfor (int x = 0; x < rows; x++) {\n\t\tfor (int y = 0; y < cols; y++) {\n\t\t\tif (board[x][y] == \'O\' && disjointSets.find(x * cols + y) != disjointSets.find(dummyBorder)) {\n\t\t\t\tboard[x][y] = \'X\';\n\t\t\t}\n\t\t}\n\t}\n\n}\n\n// based on Quick Union\nclass UnionFind {\n\n\tint[] parents;\n\n\tpublic UnionFind(char[][] board) {\n\n\t\tint rows = board.length, cols = board[0].length;\n\t\tparents = new int[rows * cols + 1];\n\n\t\tfor (int x = 0; x < rows; x++) {\n\t\t\tfor (int y = 0; y < cols; y++) {\n\t\t\t\tif (board[x][y] == \'O\') {\n\t\t\t\t\tint id = x * cols + y;\n\t\t\t\t\tparents[id] = id;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tparents[rows * cols] = rows * cols;\n\t}\n\n\tpublic int find(int x) {\n\n\t\tif (x != parents[x])\n\t\t\tx = find(parents[x]);\n\t\treturn parents[x];\n\t}\n\n\tpublic void union(int x, int y) {\n\n\t\tint rootX = find(x);\n\t\tint rootY = find(y);\n\t\tif (rootX != rootY) {\n\t\t\tparents[rootX] = rootY;\n\t\t}\n\t}\n}\n\n// A more optimised approach: based on Quick Union Ranking\nclass UnionFindRank {\n\tint[] parents;\n\tint[] ranks;\n\n\tpublic UnionFindRank(char[][] board) {\n\t\tint rows = board.length, cols = board[0].length;\n\t\tint n = rows * cols + 1;\n\t\tparents = new int[n];\n\t\tranks = new int[n];\n\t\tfor (int i = 0; i < n; i++)\n\t\t\tparents[i] = i;\n\t}\n\n\tprivate int find(int x) {\n\t\tif (x != parents[x])\n\t\t\tx = find(parents[x]);\n\t\treturn parents[x];\n\t}\n\n\tprivate void union(int x, int y) {\n\t\tint px = find(x);\n\t\tint py = find(y);\n\t\tif (px != py) {\n\t\t\tif (ranks[px] > ranks[py]) {\n\t\t\t\tparents[py] = px;\n\t\t\t\tranks[px]++;\n\t\t\t} else {\n\t\t\t\tparents[px] = py;\n\t\t\t\tranks[py]++;\n\t\t\t}\n\t\t}\n\t}\n}
7
0
[]
1
surrounded-regions
Python straight forward solution
python-straight-forward-solution-by-giri-izta
Inspired from [caikehe's][1] solution. Start from the edge and mark all the 'O' that are accessible from the 'O' in the edge using BFS. The marked 'O' should st
girikuncoro
NORMAL
2016-01-06T08:26:49+00:00
2016-01-06T08:26:49+00:00
1,559
false
Inspired from [caikehe's][1] solution. Start from the edge and mark all the 'O' that are accessible from the 'O' in the edge using BFS. The marked 'O' should stay 'O', and the 'untouchable' 'O' would be converted to 'X'\n\n def solve(board):\n queue = []\n for r in range(len(board)):\n for c in range(len(board[0])):\n if (r in [0, len(board)-1] or c in [0, len(board[0])-1]) and board[r][c] == 'O':\n queue.append((r,c))\n while queue:\n r,c = queue.pop(0)\n if 0<=r<len(board) and 0<=c<len(board[0]) and board[r][c] == 'O':\n board[r][c] = 'V'\n queue.append((r-1,c))\n queue.append((r+1,c))\n queue.append((r,c-1))\n queue.append((r,c+1))\n \n for r in range(len(board)):\n for c in range(len(board[0])):\n if board[r][c] == 'V':\n board[r][c] = 'O'\n elif board[r][c] == 'O':\n board[r][c] = 'X'\n \n\n\n [1]: https://leetcode.com/discuss/57174/python-short-bfs-solution
7
0
['Python']
0
surrounded-regions
BFS-based solution in Java
bfs-based-solution-in-java-by-mach7-on16
/*\n dfs, bfs, union-find\u90fd\u53ef\u4ee5\u505a, \u57fa\u672c\u601d\u8def\u662f\n \u4ece\u5728\u56db\u4e2a\u8fb9\u7684\u5404\u4e2a'O'\u5f00\u59c
mach7
NORMAL
2016-02-26T10:11:29+00:00
2016-02-26T10:11:29+00:00
1,130
false
/*\n dfs, bfs, union-find\u90fd\u53ef\u4ee5\u505a, \u57fa\u672c\u601d\u8def\u662f\n \u4ece\u5728\u56db\u4e2a\u8fb9\u7684\u5404\u4e2a'O'\u5f00\u59cb\u641c\u7d22, \u8fde\u5728\u4e00\u8d77\u7684'O'\u5c31\u662f\u4e0d\u80fd\u88ab\u5305\u56f4\u7684, \u5176\u4f59\u7684\u70b9\u90fd\u5e94\u8be5\u8bbe\u4e3a'X'.\n \n \u5982\u679c\u9009\u62e9bfs, \u53ef\u4ee5\u628a\u6240\u6709\u8fb9\u4e0a\u7684\u6240\u6709'O'\u4e00\u8d77\u5165\u961f, \u540c\u65f6\u8fdb\u884cbfs\n */\n public class Solution {\n public void solve(char[][] board) {\n if (board == null || board.length == 0 || board[0].length == 0) return;\n int height = board.length, width = board[0].length;\n Deque<int[]> queue = new ArrayDeque<>(); // int[2] as [row, col]\n for (int i = 0; i < width; ++i) {\n if (board[0][i] == 'O') {\n queue.addLast(new int[] {0, i});\n board[0][i] = 'V'; // mark as visited\n }\n if (board[height - 1][i] == 'O') {\n queue.addLast(new int[] {height - 1, i});\n board[height - 1][i] = 'V';\n }\n }\n for (int i = 1; i < height - 1; ++i) {\n if (board[i][0] == 'O') {\n queue.addLast(new int[] {i, 0});\n board[i][0] = 'V';\n }\n if (board[i][width - 1] == 'O') {\n queue.addLast(new int[] {i, width - 1});\n board[i][width - 1] = 'V';\n }\n }\n while (!queue.isEmpty()) {\n int[] cur = queue.removeFirst();\n if (cur[0] - 1 >= 0 && board[cur[0] - 1][cur[1]] == 'O') { // up\n queue.addLast(new int[] {cur[0] - 1, cur[1]});\n board[cur[0] - 1][cur[1]] = 'V';\n }\n if (cur[0] + 1 < height && board[cur[0] + 1][cur[1]] == 'O') { // down\n queue.addLast(new int[] {cur[0] + 1, cur[1]});\n board[cur[0] + 1][cur[1]] = 'V';\n }\n if (cur[1] - 1 >= 0 && board[cur[0]][cur[1] - 1] == 'O') { // left\n queue.addLast(new int[] {cur[0], cur[1] - 1});\n board[cur[0]][cur[1] - 1] = 'V';\n }\n if (cur[1] + 1 < width && board[cur[0]][cur[1] + 1] == 'O') { // right\n queue.addLast(new int[] {cur[0], cur[1] + 1});\n board[cur[0]][cur[1] + 1] = 'V';\n }\n }\n for (int i = 0; i < height; ++i) {\n for (int j = 0; j < width; ++j) {\n if (board[i][j] == 'O') board[i][j] = 'X';\n else if (board[i][j] == 'V') board[i][j] = 'O';\n }\n }\n }\n }
7
1
[]
0
surrounded-regions
Surrounded Regions [C++][Easy]
surrounded-regions-ceasy-by-moveeeax-95rm
IntuitionThe problem asks to capture all the surrounded regions (i.e., 'O's that are surrounded by 'X's) in a 2D grid and replace them with 'X'. The cells that
moveeeax
NORMAL
2025-02-03T02:35:06.794130+00:00
2025-02-03T02:35:06.794130+00:00
886
false
# Intuition The problem asks to capture all the surrounded regions (i.e., 'O's that are surrounded by 'X's) in a 2D grid and replace them with 'X'. The cells that are connected to the boundary or the outer regions should not be surrounded, so these 'O's should remain unchanged. Our goal is to identify all the 'O's that are connected to the boundary and mark them as not surrounded. We can then replace all other 'O's (the surrounded ones) with 'X'. # Approach 1. **Boundary check**: The 'O's on the boundary (top, bottom, left, right) or those connected to the boundary should not be flipped to 'X'. Hence, we start by performing a DFS (Depth-First Search) on all boundary cells (top row, bottom row, left column, right column) to mark all 'O's that are connected to the boundary as 'E' (escaped). These are not surrounded by 'X'. 2. **DFS search**: For each 'O' that we encounter on the boundary or its connected components, we will mark them as 'E' to denote that they are escaped. The DFS will spread in all four directions (up, down, left, right) and mark any adjacent 'O's that are connected to the boundary. 3. **Update board**: After marking all escaped 'O's, we will iterate over the board: - Change all remaining 'O's to 'X' (these are surrounded). - Change all 'E's back to 'O' (restored escaped regions). # Complexity - **Time complexity**: The DFS will visit each cell of the board at most once. Therefore, the time complexity is \(O(m \times n)\), where \(m\) is the number of rows and \(n\) is the number of columns. - **Space complexity**: The space complexity is \(O(m \times n)\) in the worst case due to the recursion stack used by the DFS. # Code ```cpp class Solution { public: void solve(vector<vector<char>>& board) { if (board.empty() || board[0].empty()) return; int m = board.size(), n = board[0].size(); function<void(int, int)> dfs = [&](int i, int j) { if (i < 0 || i >= m || j < 0 || j >= n || board[i][j] != 'O') return; board[i][j] = 'E'; dfs(i - 1, j); dfs(i + 1, j); dfs(i, j - 1); dfs(i, j + 1); }; for (int i = 0; i < m; i++) { dfs(i, 0); dfs(i, n - 1); } for (int j = 0; j < n; j++) { dfs(0, j); dfs(m - 1, j); } for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (board[i][j] == 'O') board[i][j] = 'X'; if (board[i][j] == 'E') board[i][j] = 'O'; } } } }; ```
6
0
['C++']
0
surrounded-regions
simple DFS solution without extra space
simple-dfs-solution-without-extra-space-ap0w3
IntuitionAs the problem states, all the cells ('O') that are connected to the edges cannot be surrounded by 'X'. Therefore, we will visit all four edges and che
vipin_rana8
NORMAL
2025-01-06T10:17:26.659801+00:00
2025-01-06T10:17:26.659801+00:00
975
false
# Intuition As the problem states, all the cells ('O') that are connected to the edges cannot be surrounded by 'X'. Therefore, we will visit all four edges and check the connected regions to any 'O' on the edge. # Approach I will follow the DFS approach to visit every 'O' cell connected to the edges and mark them as visited by setting board[r][c] = 'V'. Once all connected cells have been visited, we will update all remaining 'O' cells to 'X' and convert all 'V' cells back to 'O'. # Complexity - Time complexity: O(n.m) <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: O(recursion stack space) <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```java [] class Solution { public void solve(char[][] board) { int n = board.length; int m = board[0].length; for(int r = 0; r < n; r++){ if(board[r][0] == 'O'){ dfs(board, r, 0); } if(board[r][m - 1] == 'O'){ dfs(board, r, m - 1); } } for(int c = 0; c < m; c++){ if(board[0][c] == 'O'){ dfs(board, 0, c); } if(board[n - 1][c] == 'O'){ dfs(board, n - 1, c); } } for(int i = 0; i < n; i++){ for(int j = 0; j < m; j++){ if(board[i][j] == 'O'){ board[i][j] = 'X'; }else if(board[i][j] == 'V'){ board[i][j] = 'O'; } } } } private void dfs(char[][] board, int i, int j){ if(0 <= i && i < board.length && 0 <= j && j < board[0].length && board[i][j] == 'O' && board[i][j] != 'V'){ board[i][j] = 'V'; dfs(board, i + 1, j); dfs(board, i - 1, j); dfs(board, i, j + 1); dfs(board, i, j - 1); } } } ```
6
0
['Depth-First Search', 'Java']
1
surrounded-regions
83.1 (Approach 1) | ( O(m * n) )✅ | Python & C++(Step by step explanation)✅
831-approach-1-om-n-python-cstep-by-step-uzlv
Intuition\nThe problem requires capturing surrounded regions on a board, where surrounded regions are defined as regions that are not connected to the border. W
monster0Freason
NORMAL
2024-02-13T20:36:28.666522+00:00
2024-02-13T20:36:28.666541+00:00
894
false
# Intuition\nThe problem requires capturing surrounded regions on a board, where surrounded regions are defined as regions that are not connected to the border. We need to capture (convert to \'X\') surrounded regions while leaving unsurrounded regions intact.\n\n# Approach\n![image.png](https://assets.leetcode.com/users/images/9013c600-88f6-47ae-b3e7-faff02592f49_1707856499.8874838.png)\n\n\n1. **DFS to Capture Surrounded Regions**: We start by traversing the border of the board. Whenever we encounter an \'O\' cell on the border, we recursively explore its neighboring cells using Depth-First Search (DFS) and mark them as temporary (\'T\') to signify that they are not surrounded by \'X\'. This step captures unsurrounded regions connected to the border.\n2. **Convert Surrounded Regions to \'X\'**: Next, we traverse the entire board and convert all remaining \'O\' cells to \'X\', as they are the surrounded regions.\n3. **Restore Captured Regions**: Finally, we restore the captured regions marked as \'T\' back to \'O\', completing the process.\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 board. We visit each cell of the board once during the DFS traversal.\n- Space complexity: \\(O(1)\\) (excluding input and output space), as we are modifying the given board in-place without using any additional data structures.\n\n# Code(Python)\n```python\nclass Solution:\n def solve(self, board: List[List[str]]) -> None:\n rows, cols = len(board), len(board[0])\n\n def capture(r, c):\n # Base case: If indices are out of bounds or the cell is not \'O\', return\n if r < 0 or c < 0 or r == rows or c == cols or board[r][c] != "O":\n return\n # Mark the cell as temporary \'T\'\n board[r][c] = "T"\n # Recursive DFS to capture neighboring \'O\' cells\n capture(r + 1, c)\n capture(r - 1, c)\n capture(r, c + 1)\n capture(r, c - 1)\n\n # Step 1: Capture unsurrounded regions (O -> T)\n for r in range(rows):\n for c in range(cols):\n if board[r][c] == "O" and (r in [0, rows - 1] or c in [0, cols - 1]):\n capture(r, c)\n\n # Step 2: Capture surrounded regions (O -> X)\n for r in range(rows):\n for c in range(cols):\n if board[r][c] == "O":\n board[r][c] = "X"\n\n # Step 3: Uncapture unsurrounded regions (T -> O)\n for r in range(rows):\n for c in range(cols):\n if board[r][c] == "T":\n board[r][c] = "O"\n```\n\n# Code(C++)\n```c++\nclass Solution {\npublic:\n void solve(vector<vector<char>>& board) {\n int m = board.size();\n int n = board[0].size();\n \n // Step 1: Mark escaped cells along the border\n for (int i = 0; i < m; i++) {\n dfs(board, i, 0, m, n); // left border\n dfs(board, i, n - 1, m, n); // right border\n }\n \n for (int j = 0; j < n; j++) {\n dfs(board, 0, j, m, n); // top border\n dfs(board, m - 1, j, m, n); // bottom border\n }\n \n // Step 2: Flip cells to correct final states\n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n if (board[i][j] == \'O\') {\n board[i][j] = \'X\'; // surrounded region\n }\n if (board[i][j] == \'E\') {\n board[i][j] = \'O\'; // restore escaped region\n }\n }\n }\n }\nprivate:\n // Depth-First Search (DFS) to mark escaped regions\n void dfs(vector<vector<char>>& board, int i, int j, int m, int n) {\n if (i < 0 || i >= m || j < 0 || j >= n || board[i][j] != \'O\') {\n return; // base case: out of bounds or cell is not \'O\'\n }\n \n board[i][j] = \'E\'; // mark as escaped\n \n // Explore neighboring cells recursively\n dfs(board, i - 1, j, m, n); // up\n dfs(board, i + 1, j, m, n); // down\n dfs(board, i, j - 1, m, n); // left\n dfs(board, i, j + 1, m, n); // right\n }\n};\n```\n\n\n# Please upvote the solution if you understood it.\n![1_3vhNKl1AW3wdbkTshO9ryQ.jpg](https://assets.leetcode.com/users/images/0161dd3b-ad9f-4cf6-8c43-49c2e670cc21_1699210823.334661.jpeg)\n
6
0
['Depth-First Search', 'Graph', 'Matrix', 'C++', 'Python3']
2
surrounded-regions
Java Solution for Surrounded Regions Problem
java-solution-for-surrounded-regions-pro-hm2b
Intuition\n Describe your first thoughts on how to solve this problem. \nThe problem is to find all the "surrounded regions" in a 2D board. A surrounded region
Aman_Raj_Sinha
NORMAL
2023-05-01T04:44:15.954991+00:00
2023-05-01T04:44:15.956409+00:00
834
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem is to find all the "surrounded regions" in a 2D board. A surrounded region is defined as a region of \'O\'s (capital letter O) that is surrounded by \'X\'s (capital letter X) in all directions (left, right, top, bottom). The goal is to replace all such surrounded regions with \'X\'s.\n\nThe\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nFirst, it checks if the input board is null or empty. If it is, the function returns.\nNext, it iterates over the left and right borders of the board, looking for \'O\'s. If it finds an \'O\', it calls the "merge" function, passing in the row and column indices of the \'O\' as arguments. The "merge" function is a recursive function that marks all the connected \'O\'s with a special character, \'#\' (hash symbol).\nThen, the solution iterates over the top and bottom borders of the board, looking for \'O\'s. If it finds an \'O\', it calls the "merge" function again, passing in the row and column indices of the \'O\' as arguments.\nAfter all the border \'O\'s have been merged, the solution iterates over the entire board, replacing \'O\'s with \'X\'s and \'#\'s with \'O\'s.\nFinally, the modified board is returned.\n\nThe "merge" function works recursively as follows:\n\nFirst, it checks if the given row and column indices are valid (i.e., not out of bounds). If they are not valid, the function returns.\nNext, it checks if the current cell is an \'O\'. If it is not, the function returns.\nIf the current cell is an \'O\', the function marks it with \'#\' and then recursively calls itself for all four adjacent cells (up, down, left, right).\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(mn), where m and n are the dimensions of the input board. This is because the code iterates over every cell in the board once, performs a constant amount of work (comparing the cell value to \'O\' or \'#\'), and recursively calls the merge method on up to four neighboring cells. Since each cell is visited at most once, the time complexity is proportional to the number of cells in the board.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(mn), because the merge method performs a depth-first search of the board, potentially storing up to m*n recursive calls on the call stack. Additionally, the code modifies the input board in-place by changing \'O\' cells to \'#\' cells and later changing \'#\' cells back to \'O\' cells. However, these modifications do not increase the space complexity beyond the original input size.\n\n# Code\n```\nclass Solution {\n public void solve(char[][] board) {\n if(board == null || board.length==0)\n return;\n int m = board.length;\n int n = board[0].length;\n //merge O\u2019s on left & right boarder\n for(int i=0;i<m;i++)\n {\n if(board[i][0] == \'O\')\n {\n merge(board, i, 0);\n }\n if(board[i][n-1] == \'O\')\n {\n merge(board, i,n-1);\n }\n }\n //merge O\u2019s on top & bottom boarder\n for(int j=0; j<n; j++)\n {\n if(board[0][j] == \'O\')\n {\n merge(board, 0,j);\n }\n if(board[m-1][j] == \'O\')\n {\n merge(board, m-1,j);\n }\n }\n //process the board\n for(int i=0;i<m;i++)\n {\n for(int j=0; j<n; j++)\n {\n if(board[i][j] == \'O\')\n {\n board[i][j] = \'X\';\n }\n else if(board[i][j] == \'#\')\n {\n board[i][j] = \'O\';\n }\n }\n }\n }\n public void merge(char[][] board, int i, int j){\n if(i<0 || i>=board.length || j<0 || j>=board[0].length)\n return;\n if(board[i][j] != \'O\')\n return;\n board[i][j] = \'#\';\n merge(board, i-1, j);\n merge(board, i+1, j);\n merge(board, i, j-1);\n merge(board, i, j+1);\n }\n}\n```
6
0
['Java']
0
surrounded-regions
Surrounded Regions, Explained | DFS in Python
surrounded-regions-explained-dfs-in-pyth-x7mu
Intuition\nIn order to solve this problem, we first need to distinguish between two types of "O" cells within the matrix: those that are connected 4-directional
BeefCode
NORMAL
2023-03-04T02:36:58.517185+00:00
2023-05-03T21:12:38.443030+00:00
899
false
# Intuition\nIn order to solve this problem, we first need to distinguish between two types of `"O"` cells within the matrix: those that are connected 4-directionally to `"O"` cells touching the border, and those that aren\'t. In other words, all `"O"` cells along the bounds of the matrix are **safe**, where "safe" means we don\'t need to overwrite them with `"X"`. For all other `"O"` cells within the matrix, they can only be considered **safe** if they are reachable 4-directionally from one of the border `"O"` cells. Once we\'ve established a way of discerning between safe and unsafe `"O"` cells, all that\'s left to do is flip all unsafe `"O"` cells to `"X"`. \n\nTo find and mark cells as safe, we can use a hashset and depth-first search, starting from all `"O"` cells we find along the border. We use a hashset for its $$O(1)$$ check for existence, and depth-first search to find all properly connected cells and mark them as safe. \n\n# Algorithm\n1. Initialize a hashset `seen` to contain the `(row, col)` of all safe cells.\n2. Traverse the border cells of the matrix and depth-first search all cells containing `"O"`. For each `(row, col)` we visit through DFS, we add it to `seen`.\n3. Finally, traverse the inner cells of the matrix and flip all unsafe `"O"` cells to `"X"`.\n\n# Implementation\n<iframe src="https://leetcode.com/playground/ZHzqBsFP/shared" frameBorder="0" width="800" height="600"></iframe>\n\n# Complexity\n- Time complexity: $$O(n)$$, where $$n$$ is the number of cells in the board. In the worst case, all cells are `"O"` and we must traverse and process the entire matrix.\n- Space complexity: $$O(n)$$, where $$n$$ is the number of cells in the board. In the worst case, we allocate space for $$n$$ elements in our set as well as a maximum depth of $$n$$ recursive calls in the function call stack.\n\n---\n\n> *Upvote \uD83D\uDC4D if this helped at all. Cheers!*
6
0
['Depth-First Search', 'Graph', 'Matrix', 'Python', 'Python3']
1
surrounded-regions
130: Solution with step by step explanation
130-solution-with-step-by-step-explanati-ygvs
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\nThe algorithm works as follows:\n\n1. We first handle the edge cases by c
Marlen09
NORMAL
2023-02-18T07:02:08.144407+00:00
2023-02-18T07:02:08.144453+00:00
1,525
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nThe algorithm works as follows:\n\n1. We first handle the edge cases by checking if the board is empty. If it is, we return without doing anything.\n\n2. We define a helper function dfs that performs a depth-first search to mark all O\'s that are connected to the current O at the coordinates (i, j). We mark each visited cell with the character \'#\'. The function takes two arguments i and j that represent the row and column indices of the current cell.\n\n3. We then iterate over all the edges of the board and mark all the O\'s on the edges as visited. We start with the left and right edges by iterating over all the rows and then move on to the top and bottom edges by iterating over all the columns.\n\n4. We then iterate over all the cells of the board and flip all unvisited O\'s to X\'s and all marked O\'s back to O\'s.\n\n5. The time complexity of this algorithm is O(mn), where m and n are the number of rows and columns in the board.\n\n6. This algorithm is fast and efficient as it only visits each cell once and performs a constant amount of work for each cell.\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 solve(self, board: List[List[str]]) -> None:\n """\n Do not return anything, modify board in-place instead.\n """\n if not board:\n return # empty board\n m, n = len(board), len(board[0])\n \n def dfs(i: int, j: int) -> None:\n """\n Depth-first search function to mark all O\'s connected to the current O (i, j).\n """\n if i < 0 or i >= m or j < 0 or j >= n or board[i][j] != \'O\':\n return\n \n board[i][j] = \'#\' # mark as visited\n \n # recursively mark all adjacent O\'s\n dfs(i+1, j)\n dfs(i-1, j)\n dfs(i, j+1)\n dfs(i, j-1)\n \n # mark all O\'s on the edges\n for i in range(m):\n dfs(i, 0)\n dfs(i, n-1)\n \n for j in range(n):\n dfs(0, j)\n dfs(m-1, j)\n \n # flip unvisited O\'s to X\'s and marked O\'s back to O\'s\n for i in range(m):\n for j in range(n):\n if board[i][j] == \'O\':\n board[i][j] = \'X\'\n elif board[i][j] == \'#\':\n board[i][j] = \'O\'\n\n```
6
0
['Array', 'Depth-First Search', 'Breadth-First Search', 'Python', 'Python3']
1
surrounded-regions
Fastest Solution (100% - 0ms) with Explanation for beginners.
fastest-solution-100-0ms-with-explanatio-ebku
Intuition\nDFS\n\n# Approach\n1. Apply DFS from border of the grid so that all the element which do not have any path leading to broder of the gird will be unaf
shashwat1712
NORMAL
2023-02-06T10:03:47.027446+00:00
2023-02-07T08:21:52.558837+00:00
1,585
false
# Intuition\nDFS\n\n# Approach\n1. Apply DFS from border of the grid so that all the element which do not have any path leading to broder of the gird will be unaffected. \n2. Change value of the traversed path to anything for example \'p\'.\n3. After completion of DFS change all the value in grid from \'O\' to \'X\'\n4. Change Remaining \'p\' from grid to \'O\' \n5. Our answer ready\n\n# Complexity\n- Time complexity:\nO(grid.length*grid[0].length)\n\n- Space complexity:\nO(grid.length*grid[0].length)\n\n# Code\n```\nclass Solution {\n public void solve(char[][] grid) {\n for(int i=0;i<grid.length;i++){\n if(grid[i][0]!=\'X\')\n DFS(i,0,grid);\n if(grid[i][grid[0].length-1]!=\'X\')\n DFS(i,grid[0].length-1,grid);\n }\n for(int i=0;i<grid[0].length-1;i++){\n if(grid[0][i]!=\'X\')\n DFS(0,i,grid);\n if(grid[grid.length-1][i]!=\'X\')\n DFS(grid.length-1,i,grid);\n }\n swap(grid,\'O\',\'X\');\n swap(grid,\'p\',\'O\'); \n }\n\n void swap(char[][] grid,char p, char q){\n for(int i=0;i<grid.length;i++)\n for(int j=0;j<grid[0].length;j++)\n if(grid[i][j]==p) grid[i][j]=q;\n }\n\n void DFS(int i,int j, char[][] grid){\n if(!(i>=0 && j>=0 && i<grid.length && j<grid[0].length && grid[i][j]==\'O\')) return ;\n grid[i][j]=\'p\';\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```
6
0
['Depth-First Search', 'Graph', 'Java']
0
surrounded-regions
✅Accepted | | ✅Easy solution || ✅Short & Simple || ✅Best Method
accepted-easy-solution-short-simple-best-1xou
\n# Code\n\nclass Solution {\npublic:\n void solve(vector<vector<char>>& board) {\n queue<pair<int, int>> q;\n int m=board.size();\n int
sanjaydwk8
NORMAL
2023-01-23T13:51:04.569944+00:00
2023-01-23T13:51:04.569990+00:00
2,541
false
\n# Code\n```\nclass Solution {\npublic:\n void solve(vector<vector<char>>& board) {\n queue<pair<int, int>> q;\n int m=board.size();\n int n=board[0].size();\n for(int i=0;i<m;i++)\n {\n for(int j=0;j<n;j++)\n if(i==0 || j==0 || i==m-1 || j==n-1)\n if(board[i][j]==\'O\')\n {\n q.push({i, j});\n board[i][j]=\'a\';\n }\n }\n int v[5]={-1, 0, 1, 0, -1};\n while(!q.empty())\n {\n auto p=q.front();\n q.pop();\n for(int i=0;i<4;i++)\n {\n int r=p.first+v[i];\n int c=p.second+v[i+1];\n if(r>0 && r<m && c>0 && c<n && board[r][c]==\'O\')\n {\n q.push({r, c});\n board[r][c]=\'a\';\n }\n }\n }\n for(int i=0;i<m;i++)\n {\n for(int j=0;j<n;j++)\n {\n if(board[i][j]==\'a\')\n board[i][j]=\'O\';\n else if(board[i][j]==\'O\')\n board[i][j]=\'X\';\n }\n }\n }\n};\n```\nPlease **UPVOTE** if it helps \u2764\uFE0F\uD83D\uDE0A\nThank You and Happy To Help You!!
6
0
['C++']
1
surrounded-regions
Check for the 'O' which lie on the perimeter cells of the board || C++
check-for-the-o-which-lie-on-the-perimet-4xze
At first, I thought that was a very hard question as we need to check all cells that surround a particular group of \'O\'s. But, it turned out to be a rather si
pranjal_gaur
NORMAL
2022-07-07T15:50:40.928322+00:00
2022-07-07T15:51:17.480187+00:00
319
false
At first, I thought that was a very hard question as we need to check all cells that surround a particular group of \'O\'s. But, it turned out to be a rather simple question.\nI solved this problem in 2 iterataions of the board. In the first iteration, all you need to do is to traverse the board and look for the O\'s which lie on the boundary of the board. Then, call DFS for these cells and mark all the O\'s connected to these O\'s as visited.\nThen, in the second iteration of the matrix, just look for those O\'s which are not marked visited and changeg them to \'X\'.\n\n**Time Complexity** - O(n * m)\n**Space Complexity** - O(n * m)\n\n```\n\tint mvx[4] = {0,0,-1,1};\n int mvy[4] = {-1,1,0,0};\n \n bool isSafe(int i, int j, int n, int m) {\n if(i<0 || i>=n || j<0 || j>=m) return false;\n return true;\n }\n \n void dfs(vector<vector<char>>& board, vector<vector<int>>& vis, int i, int j, int n, int m) {\n vis[i][j] = 1;\n \n for(int x=0;x<4;x++) {\n int ni = i + mvx[x];\n int nj = j + mvy[x];\n \n if(isSafe(ni, nj, n, m) && board[ni][nj]==\'O\' && vis[ni][nj]==0)\n dfs(board, vis, ni, nj, n, m);\n }\n }\n void solve(vector<vector<char>>& board) {\n int n = board.size(), m = board[0].size();\n vector<vector<int>> vis(n, vector<int> (m, 0));\n \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(board[i][j]==\'O\' && !vis[i][j]) dfs(board, vis, i, j, n, m);\n }\n }\n }\n \n for(int i=0;i<n;i++) {\n for(int j=0;j<m;j++) {\n if(board[i][j]==\'O\' && !vis[i][j]) board[i][j] = \'X\';\n }\n }\n }
6
0
['Depth-First Search', 'C']
0
surrounded-regions
Simple C++ DFS Solution with Explanations and Comments
simple-c-dfs-solution-with-explanations-g5c4a
Steps to Solve :\n 1. Move over the boundary of board, and find O\'s \n 2. Every time we find an O, perform DFS from it\'s position\n 3. In DFS c
rishabh_devbanshi
NORMAL
2021-11-01T14:36:43.991602+00:00
2021-11-01T14:40:23.683988+00:00
257
false
Steps to Solve :\n 1. Move over the boundary of board, and find O\'s \n 2. Every time we find an O, perform DFS from it\'s position\n 3. In DFS convert all \'O\' to \'#\' (why?? so that we can differentiate which \'O\' can be flipped and which cannot be) \n 4. After all DFSs have been performed, board contains three elements,#,O and X\n 5. \'O\' are left over elements which are not connected to any boundary O, so flip them to \'X\'\n 6. \'#\' are elements which cannot be flipped to \'X\', so flip them back to \'O\'\n\n```\nvoid dfs(vector<vector<char>> &board,int row,int col)\n {\n\t//to check if the current position is inside the board and is an \'O\'\n if(row<0 || row>=board.size() || col<0 || col>=board[0].size() || board[row][col] != \'O\') return;\n\t\t// if current is an \'O\' , we change it to \'T\' to mark\n\t\t//it as member of non-surrounded region\n board[row][col] = \'T\';\n\t\t\n\t\t//recursive call to dfs for up,down,left and right\n dfs(board,row+1,col);\n dfs(board,row-1,col);\n dfs(board,row,col+1);\n dfs(board,row,col-1);\n }\n void solve(vector<vector<char>>& board) {\n int n = board.size() , m = board[0].size();\n\t\t\n\t\t//checking on left and right\n for(int i=0;i<board.size();i++)\n {\n if(board[i][0] == \'O\') dfs(board,i,0);\n if(board[i][m-1] == \'O\') dfs(board,i,m-1);\n }\n \n\t\t//checking on up and down\n for(int i=0;i<board[0].size();i++)\n {\n if(board[0][i] == \'O\') dfs(board,0,i);\n if(board[n-1][i] == \'O\') dfs(board,n-1,i);\n }\n \n\t\t\n\t\t//changing every \'T\' to \'O\' and every \'O\' to \'X\'\n for(int i=0;i<n;i++)\n {\n for(int j=0;j<m;j++)\n {\n if(board[i][j] == \'T\') board[i][j] = \'O\';\n else if(board[i][j] == \'O\') board[i][j] = \'X\';\n }\n }\n \n \n }\n```
6
0
['Backtracking', 'Depth-First Search', 'Recursion', 'C']
2
surrounded-regions
📌📌 Question Explanation is very Bad || Well-Explained Question and Solution || Easy 🐍
question-explanation-is-very-bad-well-ex-q86h
Question : \nMeaning of Question is to convert all "O" in matrix to "X" which are not connected to any "O" at the border of matrix. \nApproach:\n Pick all O\'s
abhi9Rai
NORMAL
2021-11-01T06:23:00.530182+00:00
2021-11-01T06:23:00.530209+00:00
380
false
## Question : \n**Meaning of Question is to convert all "O" in matrix to "X" which are not connected to any "O" at the border of matrix.** \n**Approach:**\n* Pick all O\'s from boundary (Top/Bottom row, Leftmost/Rightmost column)\n* Make all connected O\'s to some intermediate value (* in my case).\n* Now remaining all O\'s are surrounded by X (otherwise they should have been converted to * ).\n* Convert remaining all O to X.\n* Revert all intermediate values. ( * to O).\n\n\n**Implementation :**\n\'\'\'\n\n\tclass Solution:\n\t\tdef solve(self, board: List[List[str]]) -> None:\n\t\t\t"""\n\t\t\tDo not return anything, modify board in-place instead.\n\t\t\t"""\n\t\t\tm,n = len(board),len(board[0])\n\t\t\tdef dfs(i,j):\n\t\t\t\tif i<0 or i>=m or j<0 or j>=n or board[i][j]!="O":\n\t\t\t\t\treturn\n\n\t\t\t\tboard[i][j] = "*"\n\t\t\t\tdfs(i+1,j)\n\t\t\t\tdfs(i-1,j)\n\t\t\t\tdfs(i,j+1)\n\t\t\t\tdfs(i,j-1)\n\t\t\t\treturn\n\n\t\t\tfor i in range(m):\n\t\t\t\tdfs(i,0)\n\t\t\t\tdfs(i,n-1)\n\n\t\t\tfor j in range(n):\n\t\t\t\tdfs(0,j)\n\t\t\t\tdfs(m-1,j)\n\n\t\t\tfor i in range(m):\n\t\t\t\tfor j in range(n):\n\t\t\t\t\tif board[i][j] == "*":\n\t\t\t\t\t\tboard[i][j] = "O"\n\t\t\t\t\telif board[i][j] == "O":\n\t\t\t\t\t\tboard[i][j] = "X"\n\t\t\treturn
6
0
['Depth-First Search', 'Python', 'Python3']
0
surrounded-regions
Simple Python BFS solution beats 90%
simple-python-bfs-solution-beats-90-by-c-3xxo
The key of this problem is to realize that the only way for a "O" cell to escape is through the boundaries. Instead of starting from each "O" cell we can expand
charlesl0129
NORMAL
2021-08-23T02:43:16.256640+00:00
2021-08-23T02:43:42.990883+00:00
451
false
The key of this problem is to realize that the only way for a "O" cell to escape is through the boundaries. Instead of starting from each "O" cell we can expand "O" cells at the four boundaries using BFS and see which cell is reachable form the boundaries (or in other words which cells can reach/escape the boundary).\n\nThe algorithm is as follows:\n1. Add "O" cells at the four boundaries to the queue\n2. Run BFS, see which cells are reachable\n3. Scan through the board, flip cells not reachable from the boundaries.\n```Python\nfrom collections import deque\nclass Solution:\n def solve(self, board: List[List[str]]) -> None:\n """\n Do not return anything, modify board in-place instead.\n """\n m, n = len(board), len(board[0])\n visited = [[False]*n for _ in range(m)]\n queue = deque([])\n \n # add starting "O" coordinates at the boundary to the queue\n for i in range(m):\n if board[i][0] == "O":\n queue.append((i, 0))\n visited[i][0] = True\n if board[i][n-1] == "O":\n queue.append((i, n-1))\n visited[i][n-1] = True\n for i in range(n):\n if board[0][i] == "O":\n queue.append((0, i))\n visited[0][i] = True\n if board[m-1][i] == "O":\n queue.append((m-1, i))\n visited[m-1][i] = True\n \n # standard BFS, see where we can reach from the boundaries\n connections = [(-1, 0), (1, 0), (0, -1), (0, 1)]\n while queue:\n cur_i, cur_j = queue.popleft()\n for d_i, d_j in connections:\n new_i, new_j = cur_i+d_i, cur_j+d_j\n if 0 <= new_i < m and 0 <= new_j < n and board[new_i][new_j] == "O" and not visited[new_i][new_j]:\n visited[new_i][new_j] = True\n queue.append((new_i, new_j))\n \n # go through the rest of the board, flip any cell not reachable from the boundary\n for i in range(1, m-1):\n for j in range(1, n-1):\n if board[i][j] == "O" and not visited[i][j]:\n board[i][j] = "X"\n```
6
0
['Breadth-First Search', 'Python', 'Python3']
0
surrounded-regions
Simple understandable dfs solution C++
simple-understandable-dfs-solution-c-by-qwdt5
\nclass Solution {\npublic:\n void dfs(vector<vector<char>>&board,int i,int j,int m,int n){\n if(i<0||i==m||j<0||j==n||board[i][j]==\'X\'||board[i][j]
gaurav2k20
NORMAL
2021-07-22T20:21:09.700505+00:00
2021-12-24T05:36:20.826376+00:00
116
false
```\nclass Solution {\npublic:\n void dfs(vector<vector<char>>&board,int i,int j,int m,int n){\n if(i<0||i==m||j<0||j==n||board[i][j]==\'X\'||board[i][j]==\'$\'){\n return ;\n }\n board[i][j]=\'$\';\n dfs(board,i-1,j,m,n);\n dfs(board,i,j-1,m,n);\n dfs(board,i+1,j,m,n);\n dfs(board,i,j+1,m,n);\n }\n void solve(vector<vector<char>>& board) {\n int m=board.size();\n int n=board[0].size();\n for(int i=0;i<board.size();i++){\n for(int j=0;j<board[i].size();j++){\n if((i==0||i==m-1||j==0||j==n-1) and board[i][j]==\'O\'){\n dfs(board,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(board[i][j]==\'$\'){\n board[i][j]=\'O\';\n }\n else if(board[i][j]==\'O\'){\n board[i][j]=\'X\';\n }\n \n }\n }\n }\n};\n\n```
6
0
['Depth-First Search']
0
surrounded-regions
C++ || Simple BFS to understand || Faster than 99.45%
c-simple-bfs-to-understand-faster-than-9-xzkn
Main logic is that to be totally surrounded by X they must be on four sides.\nSo if there is a O on the outer edge then it can never be surrounded , and all the
Kilua__
NORMAL
2021-03-14T17:44:28.848345+00:00
2021-03-14T17:44:28.848384+00:00
368
false
Main logic is that to be totally surrounded by X they must be on four sides.\nSo if there is a O on the outer edge then it can never be surrounded , and all the O\'s attached to it are also cannot be surrounded!! \n\nSo we start storing all the boundary O\'s and start securing O\'s in BFS manner.\n\nTo Optimise the memory all the unsorrounded O\'s are labelled as \'.\' \n\n```\nclass Solution {\npublic:\n void solve(vector<vector<char>>& board) {\n queue<pair<int,int>> q;\n int m=board.size(),n=board[0].size();\n\t\t\n\t\t//Getting boundary O\'s\n for(int i=0;i<m;i++)\n {\n if(board[i][0]==\'O\') board[i][0]=\'.\',q.push({i,0});\n if(board[i][n-1]==\'O\') board[i][n-1]=\'.\',q.push({i,n-1});\n }\n for(int i=1;i<n-1;i++)\n {\n if(board[0][i]==\'O\') board[0][i]=\'.\',q.push({0,i});\n if(board[m-1][i]==\'O\') board[m-1][i]=\'.\',q.push({m-1,i});\n }\n\t\t\n\t\t//BFS\n while(q.size())\n {\n int sz=q.size();\n while(sz--)\n {\n auto p=q.front();q.pop();\n int r=p.first,c=p.second;\n if(r+1<m) if(board[r+1][c]==\'O\') board[r+1][c]=\'.\',q.push({r+1,c});\n if(r-1>=0) if(board[r-1][c]==\'O\') board[r-1][c]=\'.\',q.push({r-1,c});\n if(c+1<n) if(board[r][c+1]==\'O\') board[r][c+1]=\'.\',q.push({r,c+1});\n if(c-1>=0) if(board[r][c-1]==\'O\') board[r][c-1]=\'.\',q.push({r,c-1}); \n }\n }\n\t\t//all the unsorrounded O\'s are re-entered\n for(int i=0;i<m;i++)\n for(int j=0;j<n;j++)\n board[i][j]=board[i][j]==\'.\'?\'O\':\'X\';\n }\n};
6
0
['Breadth-First Search', 'C']
2
surrounded-regions
Easy to understand Python Solution (beats 98% of runtimes, 50% of memory)
easy-to-understand-python-solution-beats-jgsk
\nclass Solution:\n def solve(self, board: List[List[str]]) -> None:\n """\n Do not return anything, modify board in-place instead.\n ""
user3971c
NORMAL
2020-06-17T20:31:58.508369+00:00
2020-06-17T20:31:58.508412+00:00
746
false
```\nclass Solution:\n def solve(self, board: List[List[str]]) -> None:\n """\n Do not return anything, modify board in-place instead.\n """\n #check for edge cases\n if not board:\n return\n if len(board[0]) == 1 or len(board) == 1:\n return\n \n #dfs helper function\n def dfs(x, y):\n if board[y][x] == "O":\n board[y][x] = "a"\n if x < len(board[0]) - 1:\n dfs(x + 1, y)\n if x > 0:\n dfs(x-1, y)\n if y < len(board) - 1:\n dfs(x, y + 1)\n if y > 0:\n dfs(x, y-1)\n \n #dfs all border "O"s and make them into any random letter (using "a" in the dfs function)\n for index, value in enumerate(board):\n dfs(0, index)\n dfs(len(board[0]) - 1, index)\n for index, value in enumerate(board[0]):\n dfs(index, 0)\n dfs(index, len(board) - 1)\n \n #go through the entire board changing "a"s to "O" and all remaining "O"s to "X"\n for y in range(len(board)):\n for x in range(len(board[0])):\n if board[y][x] == "a":\n board[y][x] = "O"\n elif board[y][x] == "O":\n board[y][x] = "X"\n```
6
0
['Python', 'Python3']
0
surrounded-regions
Union Find algorithm
union-find-algorithm-by-harris_ceod-95e8
The problem asks us to flip inner "O"s, which does not connect to any border "O"s. If we connect adjacent "O"s and join them in the same set(i.e. union adjacent
harris_ceod
NORMAL
2019-05-07T10:21:02.895699+00:00
2019-05-07T10:21:02.895766+00:00
520
false
The problem asks us to flip inner `"O"`s, which does not connect to any border `"O"`s. If we connect adjacent `"O"`s and join them in the same set(i.e. **union** adjacent `"O"`s), we can **find** if a `"O"` is in the same set with any border `"O"`. This solution can be splited into three steps:\n```\nX X X X\nO O X X\nX X O X\nX O X X\n1. Initialize disjoint set: Each element belongs to a single set\n0 1 2 3\n4 5 6 7\n8 9 10 11\n12 13 14 15\n\n2. Traver the board, if the element is \'O\', union it with its neighbors. \n\tHere we change the 5th number to 4, indicates they belongs to the same set.\n\tSince there are no elements can connect to its neighbors, we go to the 3rd step directly.\n0 1 2 3\n4 4 6 7\n8 9 10 11\n12 13 14 15\n\n3. Record border "O" \'s set.\n\tborder sets in this case: 4,13\n\tcheck each inner \'O\', if not connect to any elements in border sets, flip it. \n\tIn this case, we checked the 5th and 10th element in board and fliped the 10th element.\n\tX X X X\n\tO O X X\n\tX X \'X\' X\n\tX O X X\n\n```\nA very naive union find realization.\n```\nclass DisjointSet{\n private:\n int* parent;\n public:\n DisjointSet(int size){\n parent = new int[size];\n for(int i = 0; i < size; i++)\n parent[i] = i;\n }\n ~DisjointSet(){\n delete [] parent;\n }\n void Union(int p, int q){\n int pRoot = Find(p);\n int qRoot = Find(q);\n parent[pRoot] = qRoot;\n }\n int Find(int p){\n while(parent[p] != p)\n p = parent[p];\n return p;\n }\n};\n\nclass Solution {\npublic:\n void solve(vector<vector<char>>& board) {\n int rows = board.size();\n if(rows == 0) return ;\n int cols = board[0].size();\n if(rows == 1 || cols == 1)return;\n DisjointSet ds(rows * cols);\n\t\t// #1 Union adjacents \'O\'s\n for(int i = 1 ; i < rows - 1; i++){\n for(int j = 1; j < cols -1; j++){\n if(board[i][j] == \'O\')\n {\n int curPos = i * cols + j;\n if(board[i-1][j] == \'O\')\n ds.Union(curPos, (i - 1) * cols + j);\n if(board[i+1][j] == \'O\')\n ds.Union(curPos, (i + 1) * cols + j);\n if(board[i][j - 1] == \'O\')\n ds.Union(curPos, curPos - 1);\n if(board[i][j + 1] == \'O\')\n ds.Union(curPos, curPos + 1);\n }\n }\n }\n\t\t// #2 Record border "O" \'s set\n set<int> borderSetRoot;\n for(int i = 0 ; i < rows; i+=rows-1)\n for(int j = 0; j < cols; j++)\n if(board[i][j] == \'O\')\n {\n \n borderSetRoot.insert(ds.Find( i * cols + j));\n }\n for(int i = 1 ; i < rows - 1; i++)\n for(int j = 0; j < cols; j+=cols-1)\n if(board[i][j] == \'O\')\n {\n \n borderSetRoot.insert(ds.Find( i * cols + j));\n }\n \n // #3 Flip "O"s not in border set\n for(int i = 1 ; i < rows - 1; i++){\n for(int j = 1; j < cols -1; j++){\n if(board[i][j] == \'O\')\n {\n int curPos = i * cols + j; \n if(borderSetRoot.find(ds.Find(curPos)) == borderSetRoot.end())\n board[i][j] = \'X\';\n }\n }\n }\n \n }\n};\n```
6
0
[]
3
surrounded-regions
JavaScript Solution
javascript-solution-by-jay-shi-h563
\n/**\n * @param {character[][]} board\n * @return {void} Do not return anything, modify board in-place instead.\n */\nvar solve = function(board) {\n if (boar
jay-shi
NORMAL
2019-01-11T02:18:15.345284+00:00
2019-01-11T02:18:15.345360+00:00
378
false
```\n/**\n * @param {character[][]} board\n * @return {void} Do not return anything, modify board in-place instead.\n */\nvar solve = function(board) {\n if (board === null || board.length === 0 || board[0].length === 0) return;\n for (let i = 0; i< board.length; i++) {\n for (let j = 0; j < board[0].length; j++) {\n if (i === 0 || j === 0 || i === board.length - 1 || j === board[0].length -1) {\n dfs(board, i, j);\n }\n }\n }\n \n for (let i = 0; i< board.length; i++) {\n for (let j = 0; j < board[0].length; j++) {\n if (board[i][j] === \'T\') {\n board[i][j] = \'O\';\n } else if (board[i][j] === \'O\') {\n board[i][j] = \'X\';\n }\n }\n }\n};\n\nfunction dfs(board, row, col) {\n if (row < 0 || col < 0 || row >= board.length || col >= board[0].length) return;\n if (board[row][col] === \'O\') {\n board[row][col] = \'T\';\n dfs(board, row + 1, col);\n dfs(board, row - 1, col);\n dfs(board, row, col - 1);\n dfs(board, row, col + 1);\n }\n}\n```
6
0
[]
0
surrounded-regions
It's important to master all 3 methods: DFS, BFS, Union Find
its-important-to-master-all-3-methods-df-ljwj
\nclass Solution_DFS:\n def solve(self, board):\n """\n :type board: List[List[str]]\n :rtype: void Do not return anything, modify board
joeleetcode2018
NORMAL
2018-09-18T01:19:37.269416+00:00
2018-10-10T06:47:52.574671+00:00
925
false
```\nclass Solution_DFS:\n def solve(self, board):\n """\n :type board: List[List[str]]\n :rtype: void Do not return anything, modify board in-place instead.\n """\n alive,v = set(),set()\n for r in range(len(board)):\n for c in range(len(board[r])):\n if r==0 or r==len(board)-1 or c==0 or c==len(board[0])-1:\n self.traverse(board,r,c,alive) \n for r in range(len(board)):\n for c in range(len(board[r])):\n if board[r][c]==\'O\' and (r,c) not in alive:\n board[r][c] = \'X\'\n \n def traverse(self,board,r,c,alive): \n if (r,c) in alive or r<0 or r>len(board)-1 or c<0 or c>len(board[0])-1 or board[r][c] != \'O\' : \n return\n else: \n alive.add((r,c)) \n self.traverse(board,r+1,c,alive)\n self.traverse(board,r,c+1,alive)\n self.traverse(board,r-1,c,alive)\n self.traverse(board,r,c-1,alive)\n\nclass Solution_UF:\n def solve(self, board):\n parents={}\n for r in range(len(board)):\n for c in range(len(board[r])):\n if r==0 or r==len(board)-1 or c==0 or c==len(board[0])-1:\n self.traverse(board,parents,r,c,-1,-1)\n\n for r in range(len(board)):\n for c in range(len(board[r])):\n if board[r][c]==\'O\' and parents.get((r,c)) != (-1,-1):\n board[r][c] = \'X\'\n \n def traverse(self,board,parents,r,c,pr,pc): \n if (r,c) in parents or r<0 or r>len(board)-1 or c<0 or c>len(board[0])-1 or board[r][c] != \'O\' : \n return\n else: \n parentCurr=self.find((r,c),parents)\n parentPrev=self.find((pr,pc),parents)\n if parentCurr != parentPrev:\n parents[parentCurr] = parentPrev\n self.traverse(board,parents,r+1,c,r,c)\n self.traverse(board,parents,r-1,c,r,c)\n self.traverse(board,parents,r,c+1,r,c)\n self.traverse(board,parents,r,c-1,r,c)\n\n def find(self,node,parents):\n if node not in parents:\n parents[node] = node\n return node\n if parents[node]!=node:\n parents[node]=self.find(parents[node],parents)\n return parents[node]\n \nclass Solution_BFS:\n #Iterative BFS\n #Temporarily turn \'reachable O cells form border\' into \'#\', then any \'#\' is restored to \'O\', and any \'O\' is changed to \'X\'.\n def solve(self,board):\n for r in range(len(board)):\n for c in range(len(board[r])):\n if r==0 or r==len(board)-1 or c==0 or c==len(board[0])-1:\n self.traverse(board,r,c)\n\n for r in range(len(board)):\n for c in range(len(board[r])):\n if board[r][c]==\'O\':\n board[r][c] = \'X\'\n elif board[r][c]==\'#\':\n board[r][c] = \'O\'\n\n def traverse(self,board,r,c):\n q=collections.deque()\n if board[r][c]==\'O\':\n q.append((r,c))\n while q:\n c = q.popleft()\n r,c=c[0],c[1]\n if r>=0 and r<len(board) and c>=0 and c<len(board[0]) and board[r][c]==\'O\':\n board[r][c]=\'#\'\n q.append((r+1,c))\n q.append((r-1,c))\n q.append((r,c+1))\n q.append((r,c-1))\n```
6
0
[]
2
surrounded-regions
Java, concise Union Find
java-concise-union-find-by-kevincongcc-t0r4
I have tried my best to make my code clean and readable. ``` public class Solution { private int m, n; private class UnionFind{ private int[] parent;
kevincongcc
NORMAL
2018-03-05T06:55:25.736738+00:00
2018-10-10T01:25:58.408823+00:00
745
false
I have tried my best to make my code clean and readable. ``` public class Solution { private int m, n; private class UnionFind{ private int[] parent; private int[] rank; public UnionFind(int n){ parent = new int[n]; rank = new int[n]; for(int i = 0;i < n;i++) parent[i] = i; } public int find(int n){ while(n != parent[n]){ parent[n] = parent[parent[n]]; n = parent[n]; } return n; } public void union(int i, int j){ int rooti = find(i); int rootj = find(j); if(rooti == rootj) return; if(rank[rootj] < rank[rooti]){ parent[rootj] = rooti; }else{ parent[rooti] = rootj; if(rank[rooti] == rank[rootj]) rank[rootj]++; } } } public void solve(char[][] board) { if(board == null || board.length == 0 || board[0].length == 0) return; m = board.length; n = board[0].length; int dummyNode = m * n; UnionFind unionFind = new UnionFind(dummyNode + 1); for(int i = 0; i < m;i++){ for(int j = 0;j < n;j++){ if(board[i][j] == 'O'){ if(i == 0 || j == 0 || i == m - 1 || j == n - 1){ unionFind.union(i * n + j, dummyNode); }else{ if(j - 1 >= 0 && board[i][j - 1] == 'O') unionFind.union(getNode(i, j), getNode(i, j - 1)); if(i - 1 >= 0 && board[i - 1][j] == 'O') unionFind.union(getNode(i, j), getNode(i - 1, j)); if(i + 1 < m && board[i + 1][j] == 'O') unionFind.union(getNode(i, j), getNode(i + 1, j)); if(j + 1 < n && board[i][j + 1] == 'O') unionFind.union(getNode(i, j), getNode(i, j + 1)); } } } } for(int i = 0;i < m;i++){ for(int j = 0;j < n;j++){ if(board[i][j] == 'O'){ if(unionFind.find(getNode(i, j)) == unionFind.find(dummyNode)) board[i][j] = 'O'; else board[i][j] = 'X'; } } } } public int getNode(int i, int j){ return i * n + j; } } ```
6
0
[]
5
surrounded-regions
Accepted 14ms DFS c++ solution and 16ms BFS c++ solution.
accepted-14ms-dfs-c-solution-and-16ms-bf-1vr7
Please pay special attention to the comment in the solutions\uff01\n\nDFS, 14ms:\n\n class Solution {\n public:\n void solve(std::vector > &board)
prime_tang
NORMAL
2015-05-17T07:18:23+00:00
2015-05-17T07:18:23+00:00
2,768
false
**Please pay special attention to the comment in the solutions\uff01**\n\nDFS, 14ms:\n\n class Solution {\n public:\n void solve(std::vector<std::vector<char> > &board) {\n if (board.empty())\n return;\n rows = static_cast<int>(board.size());\n cols = static_cast<int>(board[0].size());\n if (rows < 3 || cols < 3)\n return;\n for (int col = 0; col < cols; ++col) {\n if (board[0][col] == 'O')\n solveDFS(board, 0, col);\n if (board[rows - 1][col] == 'O')\n solveDFS(board, rows - 1, col);\n }\n for (int row = 1; row < rows - 1; ++row) {\n if (board[row][0] == 'O')\n solveDFS(board, row, 0);\n if (board[row][cols - 1] == 'O')\n solveDFS(board, row, cols - 1);\n }\n for (int row = 0; row < rows; ++row)\n for (int col = 0; col < cols; ++col) {\n if (board[row][col] == 'O')\n board[row][col] = 'X';\n else if (board[row][col] == 'N')\n board[row][col] = 'O';\n }\n }\n private:\n int rows;\n int cols;\n void solveDFS(std::vector<std::vector<char> > &board, int i, int j) {\n board[i][j] = 'N';\n // no need to consider the peripheral border, so the condition\n // is i > 1, i < rows - 2, not i > 0, i < rows - 1.\n //\n // if use i > 0, i < rows - 1, DFS solution will get a Runtime Error, confusing!\n if (i > 1 && board[i - 1][j] == 'O')\n solveDFS(board, i - 1, j);\n if (i < rows - 2 && board[i + 1][j] == 'O')\n solveDFS(board, i + 1, j);\n if (j > 1 && board[i][j - 1] == 'O')\n solveDFS(board, i, j - 1);\n if (j < cols - 2 && board[i][j + 1] == 'O')\n solveDFS(board, i, j + 1);\n }\n };\n\nBFS, 16ms:\n\n class Solution {\n public:\n void solve(std::vector<std::vector<char> > &board) {\n if (board.empty())\n return;\n rows = static_cast<int>(board.size());\n cols = static_cast<int>(board[0].size());\n if (rows < 3 || cols < 3)\n return;\n for (int col = 0; col < cols; ++col) {\n if (board[0][col] == 'O')\n solveBFS(board, 0, col);\n if (board[rows - 1][col] == 'O')\n solveBFS(board, rows - 1, col);\n }\n for (int row = 1; row < rows - 1; ++row) {\n if (board[row][0] == 'O')\n solveBFS(board, row, 0);\n if (board[row][cols - 1] == 'O')\n solveBFS(board, row, cols - 1);\n }\n for (int row = 0; row < rows; ++row)\n for (int col = 0; col < cols; ++col) {\n if (board[row][col] == 'O')\n board[row][col] = 'X';\n else if (board[row][col] == 'N')\n board[row][col] = 'O';\n }\n }\n private:\n int rows, cols;\n void solveBFS(std::vector<std::vector<char> > &board, int i, int j) {\n board[i][j] = 'N';\n \t\tstd::queue<std::pair<int, int> > que;\n que.push(std::make_pair(i, j));\n while (!que.empty()) {\n \t\t\tint row = que.front().first, col = que.front().second;\n que.pop();\n // no need to consider the peripheral border, so the condition\n // is i > 1, i < rows - 2, not i > 0, i < rows - 1.\n //\n // if use i > 0, i < rows - 1, BFS solution will be accepted too.\n if (row > 1 && board[row - 1][col] == 'O') {\n board[row - 1][col] = 'N';\n que.push(std::make_pair(row - 1, col));\n }\n if (row < rows - 2 && board[row + 1][col] == 'O') {\n board[row + 1][col] = 'N';\n que.push(std::make_pair(row + 1, col));\n }\n if (col > 1 && board[row][col - 1] == 'O') {\n board[row][col - 1] = 'N';\n que.push(std::make_pair(row, col - 1));\n }\n if (col < cols - 2 && board[row][col + 1] == 'O') {\n board[row][col + 1] = 'N';\n que.push(std::make_pair(row, col + 1));\n }\n }\n }\n };
6
0
['Depth-First Search', 'Breadth-First Search']
3
surrounded-regions
Very easy to understand | Well explained | Beats 100.00%
very-easy-to-understand-well-explained-b-012f
IntuitionThe problem involves capturing regions of 'O' surrounded by 'X' on a 2D board. The main idea is that only the 'O' regions connected to the borders rema
ayush_pratap27
NORMAL
2025-01-16T11:28:39.887152+00:00
2025-01-16T11:28:39.887152+00:00
2,349
false
![Screenshot 2025-01-16 at 4.42.13 PM.png](https://assets.leetcode.com/users/images/c7dad670-7c56-4eb6-9014-32341e404825_1737026386.0916784.png) # Intuition <!-- Describe your first thoughts on how to solve this problem. --> The problem involves capturing regions of 'O' surrounded by 'X' on a 2D board. The main idea is that only the 'O' regions connected to the borders remain 'O', while the rest are flipped to 'X'. This insight drives the solution to focus on identifying border-connected 'O'. # Approach <!-- Describe your approach to solving the problem. --> 1. Use Depth First Search (DFS) to traverse and mark all 'O' connected to the borders of the matrix as visited. 2. Iterate over the first and last rows and columns of the board to find 'O' and perform DFS starting from those cells. 3. After marking, traverse the entire board: - Change unvisited 'O' to 'X'. - Leave visited 'O' unchanged. This ensures that all regions of 'O' surrounded by 'X' are flipped while preserving the ones connected to the border. # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> $$O(n×m)$$ as each cell is visited at most once during DFS, where n is the number of rows and m is the number of columns. - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> $$O(n×m)$$ as a visited matrix of size n×m is used, and the recursion stack for DFS has a maximum depth proportional to the size of the board in the worst case. # Code ```java [] class Solution { private void dfs(int row, int col, boolean[][] vis, char[][] board) { // Mark the current cell as visited vis[row][col] = true; int n = board.length; int m = board[0].length; // Directions for traversing: down, up, left, right int[] delRow = {1, -1, 0, 0}; int[] delCol = {0, 0, -1, 1}; // Explore neighbors for (int i = 0; i < 4; i++) { int nrow = row + delRow[i]; int ncol = col + delCol[i]; // Check bounds, visitation, and if it's an 'O' if (nrow >= 0 && nrow < n && ncol >= 0 && ncol < m && !vis[nrow][ncol] && board[nrow][ncol] == 'O') { dfs(nrow, ncol, vis, board); } } } public void solve(char[][] board) { int n = board.length; int m = board[0].length; boolean[][] vis = new boolean[n][m]; // Visited matrix to track processed cells // Traverse border rows (first and last columns) for (int i = 0; i < n; i++) { if (!vis[i][0] && board[i][0] == 'O') dfs(i, 0, vis, board); if (!vis[i][m - 1] && board[i][m - 1] == 'O') dfs(i, m - 1, vis, board); } // Traverse border columns (first and last rows) for (int j = 0; j < m; j++) { if (!vis[0][j] && board[0][j] == 'O') dfs(0, j, vis, board); if (!vis[n - 1][j] && board[n - 1][j] == 'O') dfs(n - 1, j, vis, board); } // Flip unvisited 'O' to 'X', retain visited 'O' as is for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (!vis[i][j] && board[i][j] == 'O') { board[i][j] = 'X'; } } } } } ``` ```cpp [] class Solution { void dfs(int row, int col, vector<vector<int>> &vis, vector<vector<char>> &board) { // Mark the current cell as visited vis[row][col] = 1; int n = board.size(); // Number of rows int m = board[0].size(); // Number of columns // Direction arrays to represent four possible moves: down, up, right, left int delRow[4] = {1, -1, 0, 0}; int delCol[4] = {0, 0, 1, -1}; // Traverse all four possible directions for (int i = 0; i < 4; i++) { int nrow = row + delRow[i]; // New row index int ncol = col + delCol[i]; // New column index // Check boundary conditions, visitation status, and if the cell contains 'O' if (nrow >= 0 && nrow < n && ncol >= 0 && ncol < m && vis[nrow][ncol] == 0 && board[nrow][ncol] == 'O') { dfs(nrow, ncol, vis, board); // Recursively visit the neighbor } } } public: void solve(vector<vector<char>> &board) { int n = board.size(); // Number of rows int m = board[0].size(); // Number of columns // Visited matrix to track which cells have been processed vector<vector<int>> vis(n, vector<int>(m, 0)); // Traverse the boundary rows and mark all connected 'O's as visited for (int i = 0; i < n; i++) { // Check the first column (left boundary) if (vis[i][0] == 0 && board[i][0] == 'O') { dfs(i, 0, vis, board); } // Check the last column (right boundary) if (vis[i][m - 1] == 0 && board[i][m - 1] == 'O') { dfs(i, m - 1, vis, board); } } // Traverse the boundary columns and mark all connected 'O's as visited for (int j = 0; j < m; j++) { // Check the first row (top boundary) if (vis[0][j] == 0 && board[0][j] == 'O') { dfs(0, j, vis, board); } // Check the last row (bottom boundary) if (vis[n - 1][j] == 0 && board[n - 1][j] == 'O') { dfs(n - 1, j, vis, board); } } // Traverse the entire grid to flip unvisited 'O's to 'X's for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { // If a cell is not visited and contains 'O', flip it to 'X' if (vis[i][j] == 0 && board[i][j] == 'O') { board[i][j] = 'X'; } } } } }; ``` ``` python [] class Solution: def dfs(self, row, col, vis, board): # Mark the current cell as visited vis[row][col] = True n, m = len(board), len(board[0]) # Directions for traversing: down, up, left, right directions = [(1, 0), (-1, 0), (0, -1), (0, 1)] for dr, dc in directions: nrow, ncol = row + dr, col + dc # Check bounds, visitation, and if it's an 'O' if 0 <= nrow < n and 0 <= ncol < m and not vis[nrow][ncol] and board[nrow][ncol] == 'O': self.dfs(nrow, ncol, vis, board) def solve(self, board): n, m = len(board), len(board[0]) # Visited matrix to track processed cells vis = [[False] * m for _ in range(n)] # Traverse border rows (first and last columns) for i in range(n): if not vis[i][0] and board[i][0] == 'O': self.dfs(i, 0, vis, board) if not vis[i][m - 1] and board[i][m - 1] == 'O': self.dfs(i, m - 1, vis, board) # Traverse border columns (first and last rows) for j in range(m): if not vis[0][j] and board[0][j] == 'O': self.dfs(0, j, vis, board) if not vis[n - 1][j] and board[n - 1][j] == 'O': self.dfs(n - 1, j, vis, board) # Flip unvisited 'O' to 'X', retain visited 'O' as is for i in range(n): for j in range(m): if not vis[i][j] and board[i][j] == 'O': board[i][j] = 'X' ``` ``` javascript [] var solve = function(board) { const n = board.length; const m = board[0].length; const vis = Array.from({ length: n }, () => Array(m).fill(false)); // Visited matrix to track processed cells const dfs = (row, col) => { // Mark the current cell as visited vis[row][col] = true; // Directions for traversing: down, up, left, right const delRow = [1, -1, 0, 0]; const delCol = [0, 0, -1, 1]; for (let i = 0; i < 4; i++) { const nrow = row + delRow[i]; const ncol = col + delCol[i]; // Check bounds, visitation, and if it's an 'O' if (nrow >= 0 && nrow < n && ncol >= 0 && ncol < m && !vis[nrow][ncol] && board[nrow][ncol] === 'O') { dfs(nrow, ncol); } } }; // Traverse border rows (first and last columns) for (let i = 0; i < n; i++) { if (!vis[i][0] && board[i][0] === 'O') dfs(i, 0); if (!vis[i][m - 1] && board[i][m - 1] === 'O') dfs(i, m - 1); } // Traverse border columns (first and last rows) for (let j = 0; j < m; j++) { if (!vis[0][j] && board[0][j] === 'O') dfs(0, j); if (!vis[n - 1][j] && board[n - 1][j] === 'O') dfs(n - 1, j); } // Flip unvisited 'O' to 'X', retain visited 'O' as is for (let i = 0; i < n; i++) { for (let j = 0; j < m; j++) { if (!vis[i][j] && board[i][j] === 'O') { board[i][j] = 'X'; } } } }; ```
5
0
['Array', 'Depth-First Search', 'Graph', 'C++', 'Java', 'Python3', 'JavaScript']
0
surrounded-regions
💢☠💫Easiest👾Faster✅💯 Lesser🧠 🎯 C++✅Python3🐍✅Java✅C✅Python🐍✅C#✅💥🔥💫Explained☠💥🔥 Beats 100
easiestfaster-lesser-cpython3javacpython-w05l
\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-07T05:58:18.485213+00:00
2024-12-07T05:58:18.485253+00:00
1,133
false
![0ehh83fsnh811.jpg](https://assets.leetcode.com/users/images/9fc46acb-7ba4-42e1-864c-3b0e7e0e82b6_1730795144.4340796.jpeg)\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/surrounded-regions/submissions/1472343329\n- ***C++ Code -->*** https://leetcode.com/problems/surrounded-regions/submissions/1472289302\n- ***Python3 Code -->*** https://leetcode.com/problems/surrounded-regions/submissions/1472293047\n- ***Java Code -->*** https://leetcode.com/problems/surrounded-regions/submissions/1472283479\n- ***C Code -->*** https://leetcode.com/problems/surrounded-regions/submissions/1472358599\n- ***Python Code -->*** https://leetcode.com/problems/surrounded-regions/submissions/1472292655\n- ***C# Code -->*** https://leetcode.com/problems/surrounded-regions/submissions/1472308384\n- ***Go Code -->*** https://leetcode.com/problems/surrounded-regions/submissions/1472346575\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# Code\n![th.jpeg](https://assets.leetcode.com/users/images/a1b27204-556a-4e92-aab3-6d617a28c7cb_1733551079.0112214.jpeg)\n
5
0
['Array', 'Depth-First Search', 'Breadth-First Search', 'C', 'Python', 'C++', 'Java', 'Go', 'Python3', 'JavaScript']
0
surrounded-regions
Easy DFS || C++ || Beats 92% || Beginner friendly approach
easy-dfs-c-beats-92-beginner-friendly-ap-b43u
\n\n# Approach\n Describe your approach to solving the problem. \nDFS\n\n# Complexity\n- Time complexity: O(m * n)\n Add your time complexity here, e.g. O(n) \n
DecafCoder0312
NORMAL
2024-06-25T08:25:51.626354+00:00
2024-06-25T08:25:51.626396+00:00
1,250
false
![image.png](https://assets.leetcode.com/users/images/6482dbce-e410-4052-b409-842edf1dc7ad_1719303891.9397962.png)\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nDFS\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 {\npublic:\n void solve(vector<vector<char>>& board) {\n int m = board.size();\n int n = board[0].size();\n\n for (int i = 0; i < m; i++) {\n if (board[i][0] == \'O\')\n DFS(board, i, 0, m, n);\n if (board[i][n - 1] == \'O\')\n DFS(board, i, n - 1, m, n);\n }\n\n for (int i = 1; i < n; i++) {\n if (board[0][i] == \'O\')\n DFS(board, 0, i, m, n);\n if (board[m - 1][i] == \'O\')\n DFS(board, m - 1, i, m, n);\n }\n\n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n if (board[i][j] == \'O\')\n board[i][j] = \'X\';\n else if (board[i][j] == \'$\')\n board[i][j] = \'O\';\n }\n }\n }\n\nprivate:\n void DFS(vector<vector<char>>& board, int i, int j, int m, int n) {\n if (i >= m || j >= n || i < 0 || j < 0 || board[i][j] != \'O\')\n return;\n board[i][j] = \'$\';\n DFS(board, i + 1, j, m, n);\n DFS(board, i - 1, j, m, n);\n DFS(board, i, j + 1, m, n);\n DFS(board, i, j - 1, m, n);\n }\n};\n```
5
0
['Array', 'Depth-First Search', 'Recursion', 'Matrix', 'C++']
4
surrounded-regions
96% Beats |C++|Memory & Space Optimized| Boundary DFS |
96-beats-cmemory-space-optimized-boundar-njth
Approach\nWe can start by identifying \'O\' cells at the border of the board because these cells cannot be surrounded by \'X\'. All other \'O\' cells within the
Shivam_Sikotra
NORMAL
2023-09-06T18:46:40.596558+00:00
2023-09-06T18:46:40.596577+00:00
374
false
# Approach\nWe can start by identifying \'O\' cells at the border of the board because these cells cannot be surrounded by \'X\'. All other \'O\' cells within the border can potentially be surrounded and should be marked with \'N\'.\n\n# Algorithm\n+ Initialize variables to store the number of rows (row) and columns (col) in the matrix.\n\n+ Create a helper function dfs(i, j, mat) that performs Depth-First Search (DFS) to mark \'O\' cells and their connected neighbors as \'N\'. It should have the following steps:\n\n + Base case: If the cell (i, j) is out of bounds or already marked as \'N\', return.\n + If the cell (i, j) is \'O\', mark it as \'N\'.\n + Recursively call dfs on its adjacent cells: down (i+1, j), up (i-1, j), right (i, j+1), and left (i, j-1).\n+ Iterate through the entire matrix using two nested loops:\n + For each cell (i, j):\n + Check if mat[i][j] is equal to \'O\' and if (i, j) is a corner cell (i.e., (i, j) is on the border). You can use the isCorner function for this.\n + If both conditions are met, call dfs(i, j, mat) to mark this region as \'N\' and all connected \'O\' cells.\n+ After marking all potentially surrounded regions as \'N\', iterate through the entire matrix again:\n\n + For each cell (i, j):\n + If mat[i][j] is \'O\', change it to \'X\' because it is not part of a surrounded region.\n + If mat[i][j] is \'N\', change it back to \'O\' to restore the originally marked \'O\' cells.\n+ The matrix is now updated with the correct regions captured. The regions surrounded by \'X\' remain \'X\', and the regions not surrounded are restored to \'O\'.\n\n# Complexity\n- Time complexity: **O(row*col)**\n\n- Space complexity:**O(1)**\n\n# Code\n```\nclass Solution {\npublic:\n int row,col; // Variables to store the number of rows and columns in the matrix.\n\n // Function to check if a cell is at the corner of the matrix.\n inline bool isCorner(int i,int j){return (i==0 || j==0 || i==row-1 || j==col-1);}\n\n // Depth-First Search (DFS) function to mark \'O\' cells connected to the border as \'N\'.\n void dfs(int i,int j,vector<vector<char>>&mat){\n\n // Base case: If the cell is out of bounds, return.\n if(i<0 || j<0 || i>=row || j>=col) {return;}\n\n // If the cell is \'O\', mark it as \'N\' and explore its neighbors.\n if(mat[i][j]==\'O\') {mat[i][j]=\'N\';}\n else {return;}\n\n dfs(i+1,j,mat); // Explore down.\n dfs(i-1,j,mat); // Explore up.\n dfs(i,j+1,mat); // Explore right.\n dfs(i,j-1,mat); // Explore left.\n }\n\n // Main function to solve the problem.\n void solve(vector<vector<char>>& mat) {\n row=mat.size(); // Get the number of rows in the matrix.\n col=mat[0].size(); // Get the number of columns in the matrix.\n \n // Iterate through the matrix to find \'O\' cells at the border and start DFS.\n for(int i=0;i<row;i++){\n for(int j=0;j<col;j++){\n if(mat[i][j]==\'O\' && isCorner(i,j)){\n dfs(i,j,mat);\n }\n }\n }\n\n // Final pass to update \'O\' cells to \'X\' and \'N\' cells back to \'O\'.\n for(int i=0;i<row;i++){\n for(int j=0;j<col;j++){\n if(mat[i][j] ==\'O\') mat[i][j]=\'X\';\n else if(mat[i][j] ==\'N\') mat[i][j]=\'O\';\n }\n }\n }\n};\n\n```
5
0
['Array', 'Depth-First Search', 'Matrix', 'C++']
0
surrounded-regions
C++ || Graph || DFS || BFS || Simple Approach
c-graph-dfs-bfs-simple-approach-by-inam_-rtun
METHOD 1 -DFS\nTime complexity- O(rows * cols)\nSpace complexity- O(rows * cols)\n\nclass Solution {\n void dfs(int i, int j, vector<vector<char>>& board) {\
Inam_28_06
NORMAL
2023-08-11T17:42:57.745934+00:00
2023-08-11T17:45:25.643367+00:00
191
false
METHOD 1 -DFS\nTime complexity- O(rows * cols)\nSpace complexity- O(rows * cols)\n```\nclass Solution {\n void dfs(int i, int j, vector<vector<char>>& board) {\n // Check if the indices are within the boundaries and the cell contains \'O\'\n if (i >= 0 && j >= 0 && i < board.size() && j < board[0].size() && board[i][j] == \'O\') {\n board[i][j] = \'#\'; // Mark the cell as visited or change it to any helpful variable\n \n // Recursively visit neighboring cells\n dfs(i - 1, j, board);\n dfs(i + 1, j, board);\n dfs(i, j - 1, board);\n dfs(i, j + 1, board);\n }\n }\n\npublic:\n void solve(vector<vector<char>>& board) {\n // Step 1: Traverse the boundary and apply DFS on \'O\' cells\n for (int i = 0; i < board.size(); i++) {\n for (int j = 0; j < board[0].size(); j++) {\n if (i == 0 || j == 0 || i == board.size() - 1 || j == board[0].size() - 1) {\n if (board[i][j] == \'O\') {\n dfs(i, j, board);\n }\n }\n }\n }\n \n // Step 2: Restore the board by converting \'O\' cells to \'X\' and \'#\' cells back to \'O\'\n for (int i = 0; i < board.size(); i++) {\n for (int j = 0; j < board[0].size(); j++) {\n if (board[i][j] == \'O\') {\n board[i][j] = \'X\';\n } else if (board[i][j] == \'#\') {\n board[i][j] = \'O\';\n }\n }\n }\n }\n};\n```\nMETHOD 2 -BFS\nTime complexity- O(rows * cols)\nSpace complexity- O(rows * cols)\n```\nclass Solution {\npublic:\n void solve(vector<vector<char>>& board) {\n int rows = board.size();\n int cols = board[0].size();\n \n // Define the directions for BFS traversal (up, down, left, right)\n vector<int> dx = {-1, 1, 0, 0};\n vector<int> dy = {0, 0, -1, 1};\n \n // Perform BFS from the boundary cells and mark the reachable cells as \'#\'\n queue<pair<int, int>> q;\n for (int i = 0; i < rows; i++) {\n for (int j = 0; j < cols; j++) {\n if ((i == 0 || i == rows - 1 || j == 0 || j == cols - 1) && board[i][j] == \'O\') {\n q.push({i, j});\n }\n }\n }\n \n while (!q.empty()) {\n int x = q.front().first;\n int y = q.front().second;\n q.pop();\n \n board[x][y] = \'#\'; // Mark the cell as visited\n \n // Explore the neighboring cells\n for (int k = 0; k < 4; k++) {\n int newX = x + dx[k];\n int newY = y + dy[k];\n \n if (newX >= 0 && newX < rows && newY >= 0 && newY < cols && board[newX][newY] == \'O\') {\n q.push({newX, newY});\n }\n }\n }\n \n // Update the board: \'O\' cells that are not marked as \'#\' are surrounded and should be changed to \'X\'\n for (int i = 0; i < rows; i++) {\n for (int j = 0; j < cols; j++) {\n if (board[i][j] == \'O\') {\n board[i][j] = \'X\';\n } else if (board[i][j] == \'#\') {\n board[i][j] = \'O\';\n }\n }\n }\n }\n};\n```\n![image](https://assets.leetcode.com/users/images/d94d1136-cde0-4463-b2ea-f6c240352b44_1691775775.1309366.webp)\n
5
0
['Depth-First Search', 'Breadth-First Search', 'Graph', 'C']
0
surrounded-regions
Easy solution in Java using Union Find with a simple trick.
easy-solution-in-java-using-union-find-w-55cs
Intuition\n Describe your first thoughts on how to solve this problem. \nReplace O with X only if it\'s surrounded by Xs -> we can use union find to group conne
mega01
NORMAL
2023-08-09T11:23:02.596225+00:00
2023-08-09T11:23:54.823973+00:00
357
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nReplace O with X only if it\'s surrounded by Xs -> we can use union find to group connected Os together, but how to know whether to replace this O or not? \nwe can simply make extra dummy node if the O is in the first, last row or col and then use union find to identify if any O is connected to this node somehow or not?\n# Approach\n<!-- Describe your approach to solving the problem. -->\nNote: \n* Each cell is identified by a number (cell row) * (number of cols) + (cell col). So the cells are from 0 to n * m - 1\n* The dummy node is n * m \n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n * m)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n * m)\n# Code\n```\nclass Solution {\n int[] parent;\n public void solve(char[][] board) {\n int n = board.length;\n int m = board[0].length;\n // we have n * m elements and one dummy node\n int size = n * m + 1;\n parent = new int[size];\n // initialize the parent array\n for(int i=0;i<size;i++) parent[i] = i;\n\n // Loop over the board\n for(int i=0;i<n;i++){\n for(int j=0;j<m;j++){\n // if we are in the first, last row or col and \n // the cell = O, union this cell with the dummy node\n if((j == m - 1 || i == n - 1 || j == 0 || i == 0) \n && board[i][j] == \'O\'){\n union(size - 1, i * m + j);\n }\n // if there are any two adjacent Os union them\n\n if(i < n - 1 && board[i][j] == \'O\' && board[i + 1][j] == \'O\'){\n union((i+1)*m + j, i * m+ j);\n }\n\n if(j < m - 1 && board[i][j] == \'O\' && board[i][j + 1] == \'O\'){\n union(i * m + j, i * m + j + 1);\n }\n }\n }\n // Get the parent of the dummy node to compare it with Os parents\n int flag = find(size - 1);\n for(int i=0;i<n;i++){\n for(int j=0;j<m;j++){\n // If they are not the same, this O is surrounded by Xs\n if(board[i][j] == \'O\' && find(i * m + j) != flag ) {\n board[i][j] = \'X\';\n }\n }\n }\n return;\n }\n\n public boolean union(int x, int y){\n int xp = find(x);\n int yp = find(y);\n if(xp == yp) return false;\n parent[yp] = xp;\n return true;\n }\n\n public int find(int x){\n if(parent[x] != x) parent[x] = find(parent[x]);\n return parent[x];\n } \n}\n```
5
0
['Union Find', 'Java']
0
surrounded-regions
My Solution in Java
my-solution-in-java-by-puranjan_nitr-2lya
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\nIdea: first we traverse all the boundaries, if there is a \'O\' present w
puranjan_nitr
NORMAL
2023-06-09T18:39:36.157571+00:00
2023-06-09T18:42:30.412944+00:00
1,375
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nIdea: first we traverse all the boundaries, if there is a \'O\' present we mark that aa \'P\'\nafter that again we traverse through the board, if there is any \'O\', present than we replace that with \'X\'. else if there is a \'P\' is there than we replace that with \'O\'.\n\n# Complexity\n- Time complexity:\n$$O(m.n)$$\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public void solve(char[][] board) {\n //Approach: Using Backtracking\n //Idea: first we traverse all the boundaries, if there is a \'O\' present we mark that aa \'P\'\n /*after that again we traverse through the board, \n if there is any \'O\', present than we replace that with \'X\'.\n else if there is a \'P\' is there than we replace that with \'O\'.*/\n\n int r = board.length;\n int c = board[0].length;\n\n // 1a) Capture unsurrounded regions - top and bottom row (replace O with P)\n for(int i=0;i<c;i++){\n if(board[0][i]==\'O\'){\n dfs(0, i, board);\n }\n if(board[r-1][i]==\'O\'){\n dfs(r-1, i, board);\n }\n }\n // 1b) Capture unsurrounded regions - Left and right columns (replace O with P)\n for(int j=0;j<r;j++){\n if(board[j][0]==\'O\'){\n dfs(j, 0, board);\n }\n if(board[j][c-1]==\'O\'){\n dfs(j, c-1, board);\n }\n }\n\n //main loop\n for(int i=0;i<r;i++){\n for(int j=0;j<c;j++){\n if(board[i][j]==\'O\'){\n board[i][j]=\'X\'; //making the soraunded regions \'O\' --> \'X\'\n }\n if(board[i][j]==\'P\'){\n board[i][j]=\'O\'; //making the soraunded regions \'P\' --> \'O\'\n }\n }\n }\n }\n //dfs method\n public void dfs(int i, int j, char[][] board){\n //base case \n if(i<0 || j<0 || i>=board.length || j>=board[0].length || board[i][j]!=\'O\'){\n return;\n }\n //make the \'O\' position as \'P\'\n board[i][j] = \'P\';\n //call dfs for all direction\n dfs(i+1, j, board);\n dfs(i-1, j, board);\n dfs(i, j+1, board);\n dfs(i, j-1, board);\n }\n}\n```
5
0
['Depth-First Search', 'Java']
3
surrounded-regions
Easy & Clear Solution Python 3 Beat 99.8%
easy-clear-solution-python-3-beat-998-by-d2ez
\n# Code\n\nclass Solution:\n def solve(self, b: List[List[str]]) -> None:\n m=len(b)\n n=len(b[0])\n def dfs(i,j):\n if b[i]
moazmar
NORMAL
2023-03-30T02:59:19.590825+00:00
2023-03-30T02:59:19.590861+00:00
681
false
\n# Code\n```\nclass Solution:\n def solve(self, b: List[List[str]]) -> None:\n m=len(b)\n n=len(b[0])\n def dfs(i,j):\n if b[i][j]=="O":\n b[i][j]="P"\n if i<m-1:\n dfs(i+1,j)\n if i>0:\n dfs(i-1,j)\n if j<n-1:\n dfs(i,j+1)\n if j>0:\n dfs(i,j-1)\n for i in [0,m-1]:\n for j in range(n):\n dfs(i,j)\n for j in [0,n-1]:\n for i in range(m):\n dfs(i,j)\n for i in range(m):\n for j in range(n):\n if b[i][j]=="O":\n b[i][j]="X"\n for i in range(m):\n for j in range(n):\n if b[i][j]=="P":\n b[i][j]="O"\n\n\n\n \n\n```
5
0
['Depth-First Search', 'Python3']
0
surrounded-regions
C++ | Boundary DFS with Explanation | No-Extra Space | Easy understanding
c-boundary-dfs-with-explanation-no-extra-i9co
Approach\n Steps to Solve :\n 1. Move over the boundary of board, and find O\'s \n 2. Every time we find an O, perform DFS from it\'s position\n 3. In
imSoumyadeep
NORMAL
2022-10-30T06:25:01.831012+00:00
2022-10-30T06:31:00.228166+00:00
615
false
# Approach\n Steps to Solve :\n 1. Move over the boundary of board, and find O\'s \n 2. Every time we find an O, perform DFS from it\'s position\n 3. In DFS convert all \'O\' to \'C\' (why?? so that we can differentiate which \'O\' can be flipped and which cannot be)\n 4. After all DFSs have been performed, board contains three elements,C,O and X\n 5. \'O\' are left over elements which are not connected to any boundary \'O\', so flip them to \'X\'\n 6. \'C\' are elements which cannot be flipped to \'X\', so flip them back to \'O\'\n \n**Note:** \n1. No visited matrix is not required beacuse after dfs traversal we change O\'s to \'C\'\n2. \'C\' means a chain of adjacent O\'s is connected some \'O\' or boundary or Boundary O\'s\n \n\n# Code\n```\nclass Solution {\npublic:\n void dfs(int i,int j,vector<vector<char>>&grid)\n {\n int r=grid.size();\n int c=grid[0].size();\n if(i<0 || j<0 || i>=r || j>=c || grid[i][j]==\'X\')\n {\n return;\n }\n if(grid[i][j]==\'C\')\n {\n return;\n }\n grid[i][j]=\'C\';\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 void solve(vector<vector<char>>& grid) {\n int r=grid.size();\n int c=grid[0].size();\n //Start dfs traversal from only boundary\'s O\'s\n //Moving over first row\n for(int i=1;i<c;i++)\n {\n if(grid[0][i]==\'O\')\n {\n dfs(0,i,grid);\n }\n }\n //Moving over Last row\n for(int i=0;i<r;i++)\n {\n if(grid[i][0]==\'O\')\n {\n dfs(i,0,grid);\n }\n }\n //Moving over first column \n for(int i=0;i<r;i++)\n {\n if(grid[i][c-1]==\'O\')\n {\n dfs(i,c-1,grid);\n }\n }\n //Moving over first column\n for(int i=0;i<c;i++)\n {\n if(grid[r-1][i]==\'O\')\n {\n dfs(r-1,i,grid);\n }\n }\n\n //\'O\' are left over elements which are not connected to any boundary O, so flip them to \'X\' \n for(int i=1;i<r-1;i++)\n {\n for(int j=1;j<c-1;j++)\n {\n if(grid[i][j]==\'O\')\n {\n grid[i][j]=\'X\';\n }\n }\n }\n //\'C\' are elements which cannot be flipped to \'X\', so flip them back to \'O\'\n for(int i=0;i<r;i++)\n {\n for(int j=0;j<c;j++)\n {\n if(grid[i][j]==\'C\')\n {\n grid[i][j]=\'O\';\n }\n }\n }\n }\n};\n```\n\nIf this was helpful, don\'t hesitate to upvote! :)\nHave a nice day\uD83D\uDE04\uD83D\uDE03!
5
0
['Depth-First Search', 'Graph', 'Recursion', 'C++']
1
surrounded-regions
Easy DFS intuitive Java solution beats 99.98%
easy-dfs-intuitive-java-solution-beats-9-sl4h
\nclass Solution {\n public void solve(char[][] a) {\n int n = a.length, m = a[0].length;\n for(int i = 0; i < n; i++){ // Boundary calls o
lagaHuaHuBro
NORMAL
2021-11-01T10:27:29.394239+00:00
2021-11-01T12:47:56.109262+00:00
47
false
```\nclass Solution {\n public void solve(char[][] a) {\n int n = a.length, m = a[0].length;\n for(int i = 0; i < n; i++){ // Boundary calls on 0th and a[0].length - 1 th coll\n if(a[i][0] == \'O\'){\n dfs(a, i, 0);\n }\n if(a[i][m - 1] == \'O\'){\n dfs(a, i, m - 1);\n }\n }\n for(int i = 0; i < m; i++){ // Boundary calls on 0th and a.length - 1 th row\n if(a[0][i] == \'O\'){\n dfs(a, 0, i);\n }\n if(a[n - 1][i] == \'O\'){\n dfs(a, n - 1, i);\n }\n }\n for(int i = 0; i < n; i++){ // Updating Values\n for(int j = 0; j < m; j++){\n if(a[i][j] == \'M\'){\n a[i][j] = \'O\';\n } else {\n a[i][j] = \'X\';\n }\n }\n }\n }\n \n public void dfs(char[][] a, int r, int c){\n // if our cell is already marked or out of bound or an \'X\' return\n if(r<0 || c<0 || r>=a.length || c>=a[0].length || a[r][c]==\'X\' || a[r][c]==\'M\') return;\n a[r][c] = \'M\'; // marking curr cell as it is \'O\' and connected to the boundary four-Directionally\n dfs(a, r - 1, c); // top call\n dfs(a, r, c + 1); // right call\n dfs(a, r + 1, c); // bottom call\n dfs(a, r, c - 1); // left call\n }\n}\n```\n```\nTime Complexity : O(N*M)
5
0
[]
0
surrounded-regions
Simple - Best Solution
simple-best-solution-by-kukreti-59ay
class Solution {\npublic:\n \n void change(vector>& board , int i , int j){\n board[i][j] = \'\';\n int dx[] = {0 ,0 ,-1,1};\n int dy
kukreti____________
NORMAL
2021-11-01T02:57:07.823657+00:00
2021-11-01T05:38:18.378335+00:00
160
false
class Solution {\npublic:\n \n void change(vector<vector<char>>& board , int i , int j){\n board[i][j] = \'*\';\n int dx[] = {0 ,0 ,-1,1};\n int dy[] = {1,-1 ,0,0};\n for(int k=0;k<4;k++){\n int cx = i +dx[k];\n int cy = j+ dy[k];\n if(cx>=0 && cx<board.size() && cy>=0 && cy<board[0].size() && board[cx][cy]==\'O\'){\n change(board, cx ,cy);\n }\n }\n }\n \n void solve(vector<vector<char>>& board) {\n int n= board.size();\n int m = board[0].size();\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(board[i][j]==\'O\'){\n change(board, i, j);\n }\n }\n }\n }\n for(int i=0;i<n;i++){\n for(int j=0;j<m;j++){\n if(board[i][j]==\'O\'){\n board[i][j] = \'X\';\n }\n\t\t\t\telse if(board[i][j]==\'*\'){\n board[i][j] = \'O\';\n }\n }\n }\n \n }\n};
5
1
[]
0
surrounded-regions
[Python] Interview Solution Explained (DFS)
python-interview-solution-explained-dfs-bu5yw
```\nclass Solution:\n \n # Helper function to determine if a postiion is on the border of the matrix\n def is_border(self, row, col, m, n):\n ret
hasanaltaf2001
NORMAL
2021-08-08T20:10:33.850348+00:00
2021-08-08T20:10:33.850377+00:00
348
false
```\nclass Solution:\n \n # Helper function to determine if a postiion is on the border of the matrix\n def is_border(self, row, col, m, n):\n return row == 0 or row == m - 1 or col == 0 or col == n-1\n \n # Helper function to get valid neighbours\n def get_valid_neighbours(self, row, col, board):\n valid_directions = []\n for drow, dcol in [(-1,0),(1,0),(0,-1),(0,1)]:\n new_row, new_col = row + drow, col + dcol\n if 0 <= new_row < len(board) and 0 <= new_col < len(board[0]) and board[new_row][new_col] == \'O\':\n valid_directions.append((new_row, new_col))\n return valid_directions\n \n # Perform DFS \n def dfs(self, row, col, board):\n board[row][col] = \'E\'\n # Get Valid rows before performing DFS to reduce recursive stack (Optimization)\n for row,col in self.get_valid_neighbours(row, col, board):\n self.dfs(row, col, board)\n\n\n def solve(self, board: List[List[str]]) -> None:\n """\n Do not return anything, modify board in-place instead.\n """\n m,n = len(board), len(board[0])\n # Perform DFS from all nodes at the border and mark as "escaped (E)" as they are not "surrounded" by X\n for row in range(m):\n for col in range(n):\n if self.is_border(row, col, m, n) and board[row][col] == \'O\':\n self.dfs(row, col, board)\n \n # Iterate through all elements again and change the "E" elements back to "O" and everything else to \'X\'\n for row in range(m):\n for col in range(n):\n if board[row][col] == \'O\': \n board[row][col] = \'X\'\n elif board[row][col] == \'E\':\n board[row][col] = \'O\'\n
5
0
['Depth-First Search', 'Recursion', 'Python']
2
surrounded-regions
Simple Detailed C++ DFS approach faster than 100%
simple-detailed-c-dfs-approach-faster-th-yxeu
Travel on the boundary of the given board and call dfs everytime you encounter \'O\'.\n Now when you call dfs at a cell which is \'O\', make it \'S\' (or any ot
persistentBeast
NORMAL
2021-04-07T20:35:43.024259+00:00
2021-04-09T15:40:04.327530+00:00
129
false
* Travel on the boundary of the given board and call dfs everytime you encounter \'O\'.\n* Now when you call dfs at a cell which is \'O\', make it \'S\' (or any other recognisable marker) and call dfs to its neighbours \n* So all \'O\' reachable from the boundary \'O\' will get marker \'S\' along with the one at the boundary.\n* But still some \'O\' reachable from some \'O\' at the boundary might get left. For those of them you have to continue iterating over the boundary of the board.\n* In the end, travel again on all of the cells of your board and convert all \'S\' to \'O\'. If a cell is found to be \'O\' then it has to be converted to \'X\' as it was not reachable from the boundary.\n\nTime complexity will be O(m*n).\n\n\n\n\n\n\n```\nclass Solution {\npublic:\n \n void dfs(vector<vector<char>>& board, int i, int j,int m,int n){\n if(i>=m || i<0 || j>=n || j<0 ) return;\n else if(board[i][j]==\'X\' || board[i][j]==\'S\' ) return;\n \n board[i][j]=\'S\';\n dfs(board,i+1,j,m,n);\n dfs(board,i,j+1,m,n);\n dfs(board,i-1,j,m,n);\n dfs(board,i,j-1,m,n); \n }\n \n void solve(vector<vector<char>>& board) {\n int m=board.size(),n=board[0].size();\n for(int j=0;j<n;j++){\n if(board[0][j]==\'O\') dfs(board,0,j,m,n);\n }\n for(int i=1;i<m;i++){\n if(board[i][n-1]==\'O\') dfs(board,i,n-1,m,n);\n }\n for(int j=n-2;j>=0;j--){\n if(board[m-1][j]==\'O\') dfs(board,m-1,j,m,n);\n }\n for(int i=m-2;i>0;i--){\n if(board[i][0]==\'O\') dfs(board,i,0,m,n);\n }\n for(int i=0;i<m;i++){\n for(int j=0;j<n;j++){\n if(board[i][j]==\'S\') board[i][j]=\'O\';\n else if(board[i][j]==\'O\') board[i][j]=\'X\';\n }\n }\n \n }\n};\n```\n\n```
5
0
[]
0
surrounded-regions
[Python 3] DFS & backtracking - with explanation (128ms runtime, O(1) extra space)
python-3-dfs-backtracking-with-explanati-x7xg
Approach:\nUse dfs from every "O" that is on the boarders and convert all those "O" that are connected into "A" which temporarily means they are explored, but w
vikktour
NORMAL
2021-01-01T21:03:49.200833+00:00
2024-09-28T02:32:07.086996+00:00
593
false
Approach:\nUse dfs from every "O" that is on the boarders and convert all those "O" that are connected into "A" which temporarily means they are explored, but will turn back to "O" at the end of the dfs. After finishing dfs on all boarder "O", we can then iterate through the entire board and convert all "O" into "X", and "A" into "O".\n\n```\nfrom typing import List\nclass Solution:\n # 128ms ~ O((M+N) * 3^(M*N))) (upperbound) runtime. The first M+N is from looking through the boundary, and 3^(M*N) for dfs up to a maximum depth of M*N nodes \n # M+N is dependent on 3^(M*N) if we have 3^(M*N) on the first dfs search, then the rest of the M+N-1 iterations won\'t be searched past the first node\n # which means it\'s just O(3^(M*N) + (M+N-1)), but likewise (M+N) will increase if 3^(M*N) is decreased.\n\n # O(1) extra space used, we only need to modify the given input board, rather than making a new one.\n\n def solve(self, board: List[List[str]]) -> None:\n """\n Do not return anything, modify board in-place instead.\n """\n \n if not board or len(board[0]) == 0:\n return\n \n rows = len(board)\n cols = len(board[0])\n \n # input a boarder "O" position, and convert all connected "O" into "A"\n def dfs(x,y):\n board[x][y] = "A"\n # check the neighbors\n for dx,dy in [(-1,0),(1,0),(0,-1),(0,1)]:\n newX, newY = x + dx, y + dy\n \n # check for bounds\n if 0 <= newX < rows and 0 <= newY < cols:\n if board[newX][newY] == "O":\n dfs(newX,newY)\n return\n \n # iterate through the boundary of the board and insert any "O" into dfs\n # top boundary\n x = 0\n for y in range(cols):\n if board[x][y] == "O":\n dfs(x,y)\n # bottom boundary\n x = rows - 1\n for y in range(cols):\n if board[x][y] == "O":\n dfs(x,y)\n \n # note that left and right boundaries check top and bottom values (even though it\'s checked previously)\n # but that doesn\'t matter since the label is no longer "O" it will be "A"\n \n # left boundary\n y = 0\n for x in range(rows):\n if board[x][y] == "O":\n dfs(x,y)\n # right boundary\n y = cols - 1\n for x in range(rows):\n if board[x][y] == "O":\n dfs(x,y)\n \n # iterate through board and convert all "O" into "X" and "A" into "O"\n for x in range(rows):\n for y in range(cols):\n if board[x][y] == "O":\n board[x][y] = "X"\n elif board[x][y] == "A":\n board[x][y] = "O"\n \n return\n```
5
0
['Depth-First Search', 'Python', 'Python3']
0
valid-triangle-number
A similar O(n^2) solution to 3-Sum
a-similar-on2-solution-to-3-sum-by-jeant-17n9
This problem is very similar to 3-Sum, in 3-Sum, we can use three pointers (i, j, k and i < j < k) to solve the problem in O(n^2) time for a sorted array, the w
jeantimex
NORMAL
2018-05-02T07:02:05.505940+00:00
2018-10-18T01:40:18.963350+00:00
21,758
false
This problem is very similar to 3-Sum, in 3-Sum, we can use three pointers (i, j, k and i < j < k) to solve the problem in O(n^2) time for a sorted array, the way we do in 3-Sum is that we first lock pointer i and then scan j and k, if nums[j] + nums[k] is too large, k--, otherwise j++, once we complete the scan, increase pointer i and repeat.\n\nFor this problem, once we sort the input array nums, the key to solve the problem is that given nums[k], count the combination of i and j where nums[i] + nums[j] > nums[k] (so that they can form a triangle). If nums[i] + nums[j] is larger than nums[k], we know that there will be j - i combination.\n\nLet\'s take the following array for example, let\'s mark the three pointers:\n```\n i j k\n[3, 19, 22, 24, 35, 82, 84]\n```\nbecause 3 + 82 > 84 and the numbers between 3 and 82 are always larger than 3, so we can quickly tell that there will be j - i combination which can form the triangle, and they are:\n```\n3, 82, 84\n19, 82, 84\n22, 82, 84\n24, 82, 84\n35, 82, 84\n```\nNow let\'s lock k and point to 35:\n```\n i j k\n[3, 19, 22, 24, 35, 82, 84]\n```\nbecause 3 + 24 < 35, if we move j to the left, the sum will become even smaller, so we have to move pointer i to the next number 19, and now we found that 19 + 24 > 35, and we don\'t need to scan 22, we know that 22 must be ok!\n\nFollowing is the JavaScript solution:\n```\nconst triangleNumber = nums => {\n nums.sort((a, b) => a - b);\n\n let count = 0;\n\n for (let k = nums.length - 1; k > 1; k--) {\n for (let i = 0, j = k - 1; i < j;) {\n if (nums[i] + nums[j] > nums[k]) {\n count += j - i;\n j--;\n } else {\n i++;\n }\n }\n }\n\n return count;\n};\n```
489
0
[]
19
valid-triangle-number
[C++/Java/Python] Two Pointers - Picture Explain - Clean & Concise - O(N^2)
cjavapython-two-pointers-picture-explain-2245
\u2714\uFE0F Solution 1: Two Pointer\n\nTheorem: In a triangle, the length of any side is less than the sum of the other two sides.\n\n- So 3 side lengths a, b
hiepit
NORMAL
2021-07-15T10:19:10.984057+00:00
2023-08-28T16:33:19.166340+00:00
11,808
false
**\u2714\uFE0F Solution 1: Two Pointer**\n\n**Theorem**: In a triangle, the length of any side is less than the sum of the other two sides.\n![image](https://assets.leetcode.com/users/images/3a8ebfd1-b8e4-4931-a525-29f8b7a08a54_1626365313.7172236.png)\n- So 3 side lengths `a`, `b`, `c` can form a Triangle if and only if `a + b > c` && `a + c > b` && `b + c > a`.\n- To make it simple, let `c` present maximum side among 3 sides `a`, `b`, `c`, it means `c >= a` and `c >= b`, so we have:\n\t- `a + c > b`, since `c >= b` and `a, b, c > 0` (prove all side of triangle must be greater than zero?)\n\t- `b + c > a`, since `c >= a` and `a, b, c > 0` (prove all side of triangle must be greater than zero?)\n- All we need to do is that we find number of pairs `a`, `b` so that `a + b > c` and `c >= a`, `c >= b`.\n\n**Prove all side of triangle must be greater than zero?**\n- If one side of triangle is zero, let the smallest side is zero, so `a = 0`.\n- To form a valid triangle, `a + b > c` <=> `0 + b > c` <=> `b > c`, which is incorrect. Since `c` is the largest side.\n\n**Algorithm**\n- Let sort `nums` in increasing order.\n- Let `nums[i]` is the smallest element, `nums[j]` is the middle element, `nums[k]` is the largest element `(i < j < k)`. Then `nums[i], nums[j], nums[k]` can form a valid **Triangle** if and only if **nums[i] + nums[j] > nums[k]**.\n\nNow, the problem become the same with **[259. 3Sum Smaller](https://leetcode.com/problems/3sum-smaller/)**\n- We fix `nums[k]`, by iterating `k` in range `[2..n-1]`, the answer is the total number of pairs `(nums[i]`, `nums[j])` for each `nums[k]`, `(i < j < k)`, so that `nums[i] + nums[j] > nums[k]`.\n\t- We start with` i = 0`, `j = k - 1`\n\t- If `nums[i] + nums[j] > nums[k]` then:\n\t\t- There are `j-i` valid pairs, because in that case, when `nums[k]` and `nums[j]` are fixed, moving `i` to the right side always causes `nums[i] + nums[j] > nums[k]`.\n\t\t- Try another `nums[j]` by decreasing `j` by one, so `j -= 1`.\n\t- Else if `nums[i] + nums[j] <= nums[k]` then:\n\t\t- Because `nums[k]` is fixed, to make the inequality correct, we need to increase sum of `nums[i] + nums[j]`.\n\t\t- There is only one choice is to increase `nums[i]`, so `i += 1`.\n\n![image](https://assets.leetcode.com/users/images/494bd84a-a716-41d9-9d21-cee1a4cb1df5_1626399365.2078004.png)\n\n\n<iframe src="https://leetcode.com/playground/CjfWgLo9/shared" frameBorder="0" width="100%" height="400"></iframe>\n\n**Complexity**\n- Time: `O(N^2)`, where `N <= 1000` is number of elements in the array `nums`.\n- Space: `O(sorting)`\n\n\nIf you think this **post is useful**, I\'m happy if you **give a vote**. Any **questions or discussions are welcome!** Thank a lot.
385
105
['Two Pointers']
15
valid-triangle-number
Java O(n^2) Time O(1) Space
java-on2-time-o1-space-by-compton_scatte-vis2
\npublic static int triangleNumber(int[] A) {\n Arrays.sort(A);\n int count = 0, n = A.length;\n for (int i=n-1;i>=2;i--) {\n int l = 0, r = i-1
compton_scatter
NORMAL
2017-06-11T03:15:33.169000+00:00
2019-11-07T07:55:30.966578+00:00
36,439
false
```\npublic static int triangleNumber(int[] A) {\n Arrays.sort(A);\n int count = 0, n = A.length;\n for (int i=n-1;i>=2;i--) {\n int l = 0, r = i-1;\n while (l < r) {\n if (A[l] + A[r] > A[i]) {\n count += r-l;\n r--;\n }\n else l++;\n }\n }\n return count;\n}\n```
357
11
[]
34
valid-triangle-number
[Python] sort + 2 pointers solution, explained
python-sort-2-pointers-solution-explaine-lhaj
Let n be number of our numbers. Then bruteforce solution is O(n^3). Another approach is to sort numbers and for each pair a_i and a_j, where i<j we need to find
dbabichev
NORMAL
2021-07-15T09:12:33.783836+00:00
2021-07-15T09:12:33.783866+00:00
5,088
false
Let `n` be number of our numbers. Then bruteforce solution is `O(n^3)`. Another approach is to sort numbers and for each pair `a_i` and `a_j`, where `i<j` we need to find the biggest index `k`, such that `a_k < a_i + a_j`. It can be done with binary search with overall complexity `O(n^2 * log n)`.\n\nThere is even better solution, using two pointers approach. Let us choose first index `i`. Then we need to find number of pairs `(left, right)` where `left < right < i` and `a_{left} + a_{right} > a_i`. Let us start with `left = 1` and `right = i-1`. Then we can use **Two Pointers** approach to find number of desired pairs in`O(n)` for fixed `i`. Note, that it is very similar to all **2Sum** or **3Sum** problems.\n\n#### Complexity\nTime complexity is `O(n^2)`, space complexity is `O(1)`.\n\n#### Code\n```python\nclass Solution:\n def triangleNumber(self, nums):\n nums, count, n = sorted(nums), 0, len(nums)\n for i in range(2, n):\n left, right = 0, i-1\n while left < right:\n if nums[left] + nums[right] > nums[i]:\n count += (right - left)\n right -= 1\n else:\n left += 1\n return count\n```\n\nIf you have any questions, feel free to ask. If you like solution and explanations, please **Upvote!**
99
0
['Two Pointers']
8
valid-triangle-number
Java Solution, 3 pointers
java-solution-3-pointers-by-shawngao-ctn4
Same as https://leetcode.com/problems/3sum-closest\n\nAssume a is the longest edge, b and c are shorter ones, to form a triangle, they need to satisfy len(b) +
shawngao
NORMAL
2017-06-11T03:18:58.194000+00:00
2018-09-16T08:07:09.015489+00:00
12,311
false
Same as https://leetcode.com/problems/3sum-closest\n\nAssume ```a``` is the longest edge, ```b``` and ```c``` are shorter ones, to form a triangle, they need to satisfy ```len(b) + len(c) > len(a)```.\n\n```\npublic class Solution {\n public int triangleNumber(int[] nums) {\n int result = 0;\n if (nums.length < 3) return result;\n \n Arrays.sort(nums);\n\n for (int i = 2; i < nums.length; i++) {\n int left = 0, right = i - 1;\n while (left < right) {\n if (nums[left] + nums[right] > nums[i]) {\n result += (right - left);\n right--;\n }\n else {\n left++;\n }\n }\n }\n \n return result;\n }\n}\n```
81
2
[]
6
valid-triangle-number
C++ Simple and Clean Solution
c-simple-and-clean-solution-by-yehudisk-hnwh
\nclass Solution {\npublic:\n int triangleNumber(vector<int>& nums) {\n int res = 0, n = nums.size();\n \n sort(nums.begin(), nums.end()
yehudisk
NORMAL
2021-07-15T07:33:42.070534+00:00
2021-07-15T07:33:42.070579+00:00
5,035
false
```\nclass Solution {\npublic:\n int triangleNumber(vector<int>& nums) {\n int res = 0, n = nums.size();\n \n sort(nums.begin(), nums.end());\n \n for (int i = n-1; i >= 0; i--) {\n int lo = 0, hi = i-1;\n \n while (lo < hi) {\n if (nums[lo] + nums[hi] > nums[i]) {\n res += hi - lo;\n hi--;\n }\n \n else lo++;\n }\n }\n \n return res;\n }\n};\n```\n**Like it? please upvote!**
76
2
['C']
3
valid-triangle-number
Python3 O(n^2) pointer solution
python3-on2-pointer-solution-by-skekre98-0412
\nclass Solution:\n def triangleNumber(self, nums):\n """\n :type nums: List[int]\n :rtype: int\n """\n \n c = 0\n
skekre98
NORMAL
2018-11-29T02:37:54.558361+00:00
2018-11-29T02:37:54.558402+00:00
4,933
false
```\nclass Solution:\n def triangleNumber(self, nums):\n """\n :type nums: List[int]\n :rtype: int\n """\n \n c = 0\n n = len(nums)\n nums.sort()\n for i in range(n-1,1,-1):\n lo = 0\n hi = i - 1\n while lo < hi:\n if nums[hi]+nums[lo] > nums[i]:\n c += hi-lo\n hi -= 1\n else:\n lo += 1\n return c\n \n \n```
51
0
[]
3
valid-triangle-number
O(N^2) solution for C++ & Python
on2-solution-for-c-python-by-zqfan-ilia
c++\n\nclass Solution {\npublic:\n int triangleNumber(vector<int>& nums) {\n vector<int> snums(nums);\n sort(snums.begin(), snums.end());\n
zqfan
NORMAL
2017-06-11T09:14:14.015000+00:00
2018-09-09T21:40:28.333919+00:00
6,111
false
c++\n```\nclass Solution {\npublic:\n int triangleNumber(vector<int>& nums) {\n vector<int> snums(nums);\n sort(snums.begin(), snums.end());\n int count = 0;\n for ( int n = nums.size(), k = n - 1; k > 1; --k ) {\n int i = 0, j = k - 1;\n while ( i < j ) {\n // any value x between i...j will satisfy snums[x] + snums[j] > snums[k]\n // and because snums[k] > snums[j] > snums[x] >= 0, they will always satisfy\n // snums[k] + snums[x] > snums[j] and snums[k] + snums[j] > snums[x]\n if ( snums[i] + snums[j] > snums[k] )\n count += --j - i + 1;\n else\n ++i;\n }\n }\n return count;\n }\n};\n\n// 243 / 243 test cases passed.\n// Status: Accepted\n// Runtime: 59 ms\n```\npython solution, sometimes it might fail TLE\n```\nclass Solution(object):\n def triangleNumber(self, nums):\n """\n :type nums: List[int]\n :rtype: int\n """\n nums, count, n = sorted(nums, reverse=1), 0, len(nums)\n for i in xrange(n):\n j, k = i + 1, n - 1\n while j < k:\n # any value x between j...k will satisfy nums[j] + nums[x] > nums[i]\n # and because nums[i] > nums[j] > nums[x] >= 0, they will always satisfy\n # nums[i] + nums[x] > nums[j] and nums[i] + nums[j] > nums[x]\n if nums[j] + nums[k] > nums[i]:\n count += k - j\n j += 1\n else:\n k -= 1\n return count\n\n# 243 / 243 test cases passed.\n# Status: Accepted\n# Runtime: 1855 ms\n```
36
3
[]
4
valid-triangle-number
C++ || Detailed explanation || Two-pointer || Clear Intuitions
c-detailed-explanation-two-pointer-clear-4yue
*INTUITIONS:\n## We will understand with an example [1 , 2 , 3 , 5 , 6 , 7, 9]\n## After sorting , Take pointer left as 0 , take right as n-1 (intially as loop
KR_SK_01_In
NORMAL
2022-04-09T15:26:09.066606+00:00
2022-04-09T15:34:29.052232+00:00
2,145
false
# ****INTUITIONS:\n## We will understand with an example [1 , 2 , 3 , 5 , 6 , 7, 9]\n## After sorting , Take pointer left as 0 , take right as n-1 (intially as loop will be going for it from n-1 to 2) . Take mid as right-1 intially . \n\n## while(left<mid) , now check the nums[left] + nums[mid] > nums[right] , if this exists then for all ( p=left to p=mid-1) there exist possibility as all the values after the nums[left] are greater than nums[left] .\n\n## Possibilities are as follows :\n## {left , mid , right} , {left+1 , mid , right} , {left+2 , mid , right} , ..... {mid-1 , mid , right} . ans +=(mid-left) and also decrese mid as all possible possibility of ( [] , mid , right) has been taken. so mid--;\n\n\n\n## when nums[left]+nums[mid] > nums[right] , not exists in this case we increment the left as to see the possibility of existing the condition . U may think why would are not changing mid , as decresing mid will lead to decrementing the (nums[l]+nums[mid]) value , it does not leads to our required condition .\n\n## [1 , 2 , 3 , 4 , 6 , 7, 9] right at 9 , left at 1 , mid at 7 . so sum = 1 + 7 > 9 : FALSE (left++)\n## left at 2 , mid at 7 , right at 9 sum=2+7>9 :false\n## left at 3, mid at 7 , right at 9 sum=3+7>9 :true ans+=(mid-left) {3,7,9} , {5,7,9} , {6,7,9}\n# after taking it decrease mid-- . \n## left at 3 , mid at 6 , right at 9 . 3+6>9:false . so , left++\n## left at 4 , mid at 6 , right at 9 , 4+6>9 : true ans+=(mid-left) { 4 , 6 , 9} .\n\n## while loop will run till(left<mid) \n\n## for loop of right will ru from right=n-1 to 2.\n\n# **IF U FIND IT HEPLFUL , PLEASE UPVOTE!!!**\n\n\n\n\n```\n int triangleNumber(vector<int>& nums) {\n int n=nums.size();\n \n int ans=0;\n \n sort(nums.begin(),nums.end());\n \n\t\t/*taking left -> leftmost number , mid -> middle element , right -> rightmost elemnt\n left is smallest one , mid -> middle element , right is largest one*/\n \n for(int right=n-1 ; right>=2 ;right--)\n {\n int left=0;\n int mid=right-1;\n while(left<mid)\n {\n \n if(nums[left]+nums[mid]>nums[right])\n {\n ans+=(mid-left);\n mid--;\n }\n else\n {\n left++;\n }\n }\n }\n \n return ans;\n \n \n }\n```
23
0
['C', 'Sorting', 'C++']
3
valid-triangle-number
Python3 solution in O(n^2 log(n)) using bisect_left
python3-solution-in-on2-logn-using-bisec-n9ps
\nfrom bisect import bisect_left\n\nclass Solution:\n def triangleNumber(self, nums: List[int]) -> int:\n nums.sort()\n n = len(nums)\n
de_mexico
NORMAL
2019-05-01T18:06:44.316486+00:00
2019-05-01T18:06:44.316538+00:00
1,516
false
```\nfrom bisect import bisect_left\n\nclass Solution:\n def triangleNumber(self, nums: List[int]) -> int:\n nums.sort()\n n = len(nums)\n ans = 0\n for i in range(n):\n for j in range(i+1, n):\n k = bisect_left(nums, nums[i] + nums[j])\n ans += max(0, k - 1 - j)\n return ans\n```\t\t
23
1
[]
2
valid-triangle-number
Python O( n^2 ) sol. based on sliding window and sorting. 85%+ [ With explanation ]
python-o-n2-sol-based-on-sliding-window-odl23
Python O( n^2 ) sol. based on sliding window and sorting.\n\nMain idea:\n1. [ Pre-processing ] Use in-place nums.sort() to keep numbers in ascending order\n\n2.
brianchiang_tw
NORMAL
2020-01-22T14:59:42.798892+00:00
2020-01-22T15:15:14.908861+00:00
2,083
false
Python O( n^2 ) sol. based on sliding window and sorting.\n\nMain idea:\n1. [ Pre-processing ] Use in-place nums.**sort()** to **keep numbers in ascending order**\n\n2. First **fix third edge with current largest one**, then **maintain a sliding window** to **compute all valid pairs** of **first edge** and **second edge**\n\n3. Catch valid edges with **triangle\'s basic property**: **a + b > c must be True** for **any two edges a, b**\n\n4. This algorithm is making triplets with the rule: **smallest edge A + medium edge B> largest edge C**, \nand also guarantees that other two cases must be True, \ni.e., \nsmallest edge A + largest edge C > medium edge B, and \nmedium edge B+ largest edge C > smallest edge A\n\n---\n\n```\n\nclass Solution:\n def triangleNumber(self, nums: List[int]) -> int:\n \n # sort in-place\n # keep numbers in ascending order\n nums.sort()\n \n # counter for valid triplet to make triangle\n valid_triplet = 0\n \n for index_i in range( len(nums)-1, 1, -1):\n \n third_edge = nums[index_i]\n \n index_of_first_edge, index_of_second_edge = 0, index_i - 1\n \n while index_of_first_edge < index_of_second_edge:\n \n first_edge = nums[index_of_first_edge]\n second_edge = nums[index_of_second_edge]\n \n if first_edge + second_edge > third_edge:\n \n # valid triplets\n # first_edge : from nums[index_of_first_edge] to nums[(index_of_second_edge-1)]\n # second edge : nums[index_of_second_edge]\n # third edge : nums[index_i]\n valid_triplet += ( index_of_second_edge - index_of_first_edge )\n \n # second edge large enough\n # make it smaller and try next run\n index_of_second_edge -= 1\n else:\n # first edge is too small\n # make it larger and try next run\n index_of_first_edge += 1\n \n \n \n return valid_triplet\n \n \n```
22
0
['Sliding Window', 'Sorting', 'Python']
5
valid-triangle-number
C++ || Brut-force to optimal || Faster then 100.00%
c-brut-force-to-optimal-faster-then-1000-serz
Theorem: In a triangle, the length of any side is less than the sum of the other two sides.\n\n\nBrut-Force solutions:\nit give TLE\n\nclass Solution {\npublic
nitin23rathod
NORMAL
2022-06-30T11:20:59.653160+00:00
2022-06-30T11:26:03.548618+00:00
886
false
**Theorem**: In a triangle, the length of any side is less than the sum of the other two sides.\n![image](https://assets.leetcode.com/users/images/3e1c1958-53ca-4f57-8058-23fbe524cf97_1656587820.0885897.png)\n\n**Brut-Force solutions:**\nit give **TLE**\n```\nclass Solution {\npublic:\n// If the sum of any two side lengths is greater than the third in every combination\n int triangleNumber(vector<int>& a) {\n sort(a.begin(), a.end());\n int ans=0, n = a.size();\n for(int i=0; i<n; i++){\n for(int j=i+1; j<n; j++){\n for(int k=j+1; k<n; k++){\n if(a[i]+a[j]>a[k]){\n // cout<<a[i]<<" "<<a[j]<<" "<<a[k]<<" ";\n ans++;\n }\n else break;\n }\n }\n }\n return ans;\n }\n};\n```\n\n* **optimal approch** :-**\n* So 3 side lengths a, b, c can form a Triangle if and only if a + b > c && a + c > b && b + c > a.\n* To make it simple, we can sort nums in increasing order.\n* Let nums[i] is the smallest element, nums[j] is the middle element, nums[k] is the largest element (i < j < k). Then nums[i], nums[j], nums[k] can form a valid Triangle if and only if **nums[i] + nums[j] > nums[k].**\n\n* We fix nums[k], by iterating k in range [2..n-1], the answer is the total number of pairs (nums[i], nums[j]) for each nums[k], (i < j < k), so that nums[i] + nums[j] > nums[k].\n\n* We start withi = 0, j = k - 1\n* If nums[i] + nums[j] > nums[k] then:\n* There are j-i valid pairs, because in that case, when nums[k] and nums[j] are fixed, moving i to the right side always causes nums[i] + nums[j] > nums[k].\n* Try another nums[j] by decreasing j by one, so j -= 1.\n* Else if nums[i] + nums[j] <= nums[k] then:\n* Because nums[k] is fixed, to make the inequality correct, we need to increase sum of nums[i] + nums[j].\n* There is only one choice is to increase nums[i], so i += 1.\n*\n\n![image](https://assets.leetcode.com/users/images/af2c8e79-4f0a-4032-9a10-6185e0672f7a_1656587940.645748.png)\n\n**C++ Code**\n\n```\nclass Solution {\npublic:\n int triangleNumber(vector<int>& nums) {\n sort(nums.begin(), nums.end());\n int n = nums.size(), ans = 0;\n for (int k = 2; k < n; ++k) {\n int i = 0, j = k - 1;\n while (i < j) {\n if (nums[i] + nums[j] > nums[k]) {\n ans += j - i;\n j -= 1;\n } else {\n i += 1;\n }\n }\n }\n return ans;\n }\n};\n```\n**If you think this post is useful, I\'m happy if you give a vote. Any questions or discussions are welcome! Thank a lot. Balence the number of view and upvote\uD83D\uDE01**\n\n**Complexity**\n\n* Time: O(N^2), where N <= 1000 is number of elements in the array nums.\n* Space: O(logN), logN is the space complexity for sorting.\n\n**If you think this post is useful, I\'m happy if you give a vote. Any questions or discussions are welcome! Thank a lot.**\n
19
0
['C']
0
valid-triangle-number
Solution Similar to Leetcode 259. 3Sum Smaller
solution-similar-to-leetcode-259-3sum-sm-gyx4
/** we need to find 3 number, i < j < k, and a[i] + a[j] > a[k];\n\t * if we sort the array, then we can easily use two pointer to find all the pairs we need.
helloworldzt
NORMAL
2017-06-11T03:19:02.722000+00:00
2017-06-11T03:19:02.722000+00:00
3,809
false
/** we need to find 3 number, i < j < k, and a[i] + a[j] > a[k];\n\t * if we sort the array, then we can easily use two pointer to find all the pairs we need.\n\t * if at some point a[left] + a[right] > a[i], all the elements from left to right-1 are valid.\n\t * because they are all greater then a[left];\n\t * so we do count += right - left; and right--\n\t * \n\t * otherwise, we increment left till we get a valid pair.\n\n\n```\npublic int triangleNumber(int[] nums) {\n\t\tif (nums == null || nums.length <= 2) {\n\t\t\treturn 0;\n\t\t}\n\t\tArrays.sort(nums);\n\t\tint count = 0;\n\t\t\n\t\tfor (int i = 0; i < nums.length; i++) {\n\t\t\tint left = 0, right = i-1;\n\t\t\twhile (left < right) {\n\t\t\t\tif (nums[left] + nums[right] > nums[i]) {\n\t\t\t\t\tcount += right - left;\n\t\t\t\t\tright--;\n\t\t\t\t} else {\n\t\t\t\t\tleft++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn count;\n }\n```
15
2
[]
3
valid-triangle-number
java binary search(log(n) * n^2) and two pointer (O(n^2))
java-binary-searchlogn-n2-and-two-pointe-6ue0
````\nBinary search: \nloop all the combination of the first two edges, and then binary search the position of third edge. It should be the last index that smal
seanshen20
NORMAL
2019-06-27T12:58:36.521314+00:00
2019-06-27T13:00:27.524015+00:00
1,058
false
````\nBinary search: \nloop all the combination of the first two edges, and then binary search the position of third edge. It should be the last index that smaller than sum(edge1 + edge2). \nIf there is no edge meet the a+b> c, then return -1. Count will not include return value of -1\n\nclass Solution {\n public int triangleNumber(int[] nums) {\n int n = nums.length;\n Arrays.sort(nums);\n int count = 0;\n for (int i = 0; i < n - 2; i++) {\n for (int j = i + 1; j < n - 1; j++) {\n int sum = nums[i] + nums[j];\n // find the first number < sum, return the index\n int temp = binarySearch(j + 1, sum, nums);\n // System.out.println("\xEF: " + nums[i] + " j: " + nums[j]);\n // System.out.println(temp);\n if (temp != -1) {\n count += temp - j;\n } \n }\n }\n return count;\n }\n \n \n private int binarySearch(int begin, int sum, int[] nums) {\n int end = nums.length - 1;\n int start = begin;\n while (start + 1 < end) {\n int mid = start + (end - start)/2;\n if (nums[mid] < sum) {\n start = mid;\n } else {\n end = mid;\n }\n }\n if (nums[end] < sum) return end;\n if (nums[start] < sum) return start;\n return -1;\n }\n}\n\nTwo pointer: inspired by 3 sum by using 2 sum two pointer \nLoop the third edge from the end, and then use Two pointer from start and end\nif nums[start] + nums[end] < third edge, move start\nelse move end\nJust find the boundary, j - i is all the possible combination that ended at j e.g. (3,7), (5,7),(6,7)\n{3,5,6,7,9}\n i j\nclass Solution {\n public int triangleNumber(int[] nums) {\n if (nums == null || nums.length < 3) return 0;\n Arrays.sort(nums);\n int n = nums.length;\n int count = 0;\n for (int i = 2; i < n; i++) {\n int start = 0;\n int end = n - i;\n System.out.println(end);\n while(start < end) {\n if (nums[start] + nums[end] <= nums[n + 1 - i]) {\n start++;\n } \n if (nums[start] + nums[end] > nums[n + 1 - i]) {\n count += end - start;\n end--; \n } \n }\n }\n return count;\n }\n}
13
0
[]
0
valid-triangle-number
C++ O(n^2) | Solution with explanation | Easy to understand
c-on2-solution-with-explanation-easy-to-04gdz
So we have to give the count of all the 3 numbers from the array such that they form a triangle;\nFor 3 sides to form a triangle there are 3 main conditions:\n1
Job-lagwado
NORMAL
2022-02-06T21:08:45.370126+00:00
2022-02-06T21:16:41.587246+00:00
759
false
So we have to give the count of all the 3 numbers from the array such that they form a triangle;\nFor 3 sides to form a triangle there are 3 main conditions:\n1) **s1+s2>s3**\n2) **s2+s3>s1**\n3) **s3+s1>s2** (where s1, s2, s3 are the sides of triangle).\n\nIf you haven\'t tried the bruteforce method just take 3 "for" loops, iterating the array in each different loop and increment the count if you find a suitable triplet that satisfies the condition;\nSo assume there are three sides and sort the array(I will tell you why) to get the size in increasing order;\nWhat will happen is we will get the triplet in form of the **s1<s2<s3**;\n\nHere we can notice that since s1 is smaller than s2 and s3, sum of both s2 and s3 will be greater than s1, i.e., **s2+s3>s1**; (1 condition \u2705)\nAlso since s3>s2 so even if we add s1 to s3 it will still be greater than s2, i.e., **s3+s1>s2**; (2 condition \u2705)\n**All we need to do now is to find the last condition s1+s2>s3 to get our required triplet and that is why we sorted the array;**\n\nSo we first start iterating(**variable I**) through the second element to the last element so that index 0 and index 1 elements can be considered;\nWe intialize the left_pointer(**variable L**) to 0 and right_pointer(**variable R**) just previous to one we are iterating through, in simple words we consider the range of elements previous to where we are currently iterating; (Keep in note **nums[L]<nums[R]<nums[I]** because array is sorted and **I>R>L**)\nSince the array is sorted nums[I] element will be the largest so we will check if sum of nums[L] and nums[R] is greater than nums[I];\n\nIf **no**, then we simply increment the left_pointer to check if the sum of next element and the element at **Rth** index can beat Rth index;\nIf **yes**, then we **add R-L** to aur answer(I will tell you why) and decrement the right_pointer to check if the sum of element at **Lth** index and the element at previous index to R can still beat** Ith** index;\n\n**Big Revelation**: Now why have we taken the **R-L** into our consideration? See if the **sum of element at Lth index** and the **element at Rth index** is larger than **element at Ith index** then, if we take the **sum of next element to Lth index** and the **element at Rth Index** it will still be larger than **element at Ith index**; Reading this makes mind go \uD83E\uDD2F? Let\'s understand this;\n\nTake already sorted array [7, 8, 9, 15, 20]; (Assume 0 based indexing in the examples)\nExample 1: Suppose **Ith** index is 3, **Lth** index is 0 and **Rth** index is 2; (nums[I] = 15, nums[L] = 7, nums[R] = 9)\nSo we check if nums[L]+nums[R]>nums[I], yes it is, and we have found one triplet but wait we can see that if we go to the next element of left_pointer that is 8 and 8+9>15 which still satisfies our condition; **So we actually got 2 triplets that can form a triangle**; Still scratching your head?\n\nExample 2: Suppose **Ith** index is 4, **Lth** index is 0 and **Rth** index is 3; (nums[I] = 20, nums[L] = 7, nums[R] = 15)\nSo we check if nums[L]+nums[R]>nums[I], yes it is, and we have found one triplet but wait we can see that if we go to the next element of left_pointer it still satisfies our condition(8+15>20) and so on (9+15>20) to next element; \n**VVIP: So we can conclude if the element at Lth and Rth index satisfy our required condition all the elements between Lth index and Rth index satisfy the same condition too since the array is in increasing order**;\n\nHence I have added the range R-L to our answer directly to save time;That\'s it you have reached the end of this long explanation; \nIf you do find this solution or it helped you in any way **please upvote this :")**\n\n\n\n\n\n```\nif(nums.size()<3) return 0; // you can\'t form a triangle without 3 sides :")\nint res = 0;\nsort(nums.begin(), nums.end()); // sorted the array so the sides get in increasing order\n\nfor(int i = 2; i<nums.size(); i++){\n\t// we have started from index 2 so that the index 0 and index 1 elements \n\t// can be considered in the iteration.\n\tint l = 0, r = i - 1;\n\twhile(l < r){\n\t\tif(nums[l] + nums[r] > nums[i]){\n\t\t\t// if the element at Lth and Rth index satisfy our required condition \n\t\t\t// all the elements between Lth index and Rth index satisfy the same \n\t\t\t// condition too since the array is in increasing order\n\t\t\tres += (r - l);\n\t\t\tr--;\n\t\t}else{\n\t\t\tl++;\n\t\t}\n\t}\n}\nreturn res;\n```\n
12
0
['Two Pointers', 'C']
0
valid-triangle-number
C++ Optimal Solution || Easy to understand || Beginner's Friendly
c-optimal-solution-easy-to-understand-be-agvt
Please Upvote the solution if it helped you because it motivate the creators like us to produce more such content...........\n\nHappy Coding :-)\nCode->\n\nclas
lakshgaur
NORMAL
2022-06-02T08:21:31.060770+00:00
2022-06-02T08:21:31.060804+00:00
1,089
false
**Please Upvote the solution if it helped you because it motivate the creators like us to produce more such content...........**\n\n**Happy Coding :-)**\nCode->\n```\nclass Solution {\npublic:\n int triangleNumber(vector<int>& nums) {\n int n=nums.size();\n if(n<3) return 0;\n sort(nums.begin(),nums.end());\n \n int count=0;\n for(int i=2;i<n;i++){\n int s=0;\n int e=i-1;\n while(s<e){\n if(nums[s]+nums[e]>nums[i]){\n count+=e-s;\n e--;\n }\n else\n s++;\n }\n }\n return count;\n }\n};\n```
10
0
['Two Pointers', 'C', 'Binary Tree', 'C++']
1
valid-triangle-number
💥[EXPLAINED] Runtime beats 95.00%
explained-runtime-beats-9500-by-r9n-cc5a
Intuition\nSort the array to simplify checking triangle validity. For each potential largest side, use two pointers to count valid triangles efficiently.\n\n# A
r9n
NORMAL
2024-08-23T01:33:30.354524+00:00
2024-08-26T19:51:46.147509+00:00
178
false
# Intuition\nSort the array to simplify checking triangle validity. For each potential largest side, use two pointers to count valid triangles efficiently.\n\n# Approach\n1 - Sort the array.\n\n2 - For each element as the largest side, use two pointers to find all pairs that form valid triangles.\n\n3 - Count valid triangles using the sorted order and two-pointer technique.\n\nThis approach runs in O(n^2) time.\n\n# Complexity\nTime complexity:\nO(n^2): Sorting takes O(n log n), and the two-pointer loop runs in O(n^2) in the worst case. This is the best time complexity achievable for this problem using this approach.\n\nSpace complexity:\nO(1): No additional data structures are used, and the sorting is done in place.\n\n# Code\n```typescript []\nfunction triangleNumber(nums: number[]): number {\n nums.sort((a, b) => a - b);\n let count = 0;\n\n for (let i = nums.length - 1; i >= 2; i--) {\n let left = 0;\n let right = i - 1;\n while (left < right) {\n if (nums[left] + nums[right] > nums[i]) {\n count += right - left;\n right--;\n } else {\n left++;\n }\n }\n }\n\n return count;\n}\n\n```
8
0
['TypeScript']
0
valid-triangle-number
611: Solution with step by step explanation
611-solution-with-step-by-step-explanati-cns7
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n1. Sort the input array "nums" in ascending order.\n2. Initialize a varia
Marlen09
NORMAL
2023-03-17T17:15:40.754337+00:00
2023-03-17T17:16:42.769112+00:00
2,081
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Sort the input array "nums" in ascending order.\n2. Initialize a variable "count" to 0, which will keep track of the number of valid triangles.\n3. Loop through all possible triplets in the array, using two pointers "i" and "j".\n4. For each triplet, initialize a third pointer "k" to "i + 2".\n5. If the first element of the triplet is 0, skip to the next element by using the "continue" statement.\n6. If all remaining elements in the array are zero, break out of the loop by using the "break" statement.\n7. Loop through all possible second elements of the triplet, starting at "j = i + 1" and ending at "len(nums) - 1".\n8. Move the third pointer "k" to the first element that is greater than or equal to the sum of the first two elements.\n9. Calculate the number of valid triangles that can be formed with the current pair of first two elements as "k - j - 1", and add it to the "count" variable.\n10. Return the final value of "count", which represents the total number of valid triangles that can be formed from the input array.\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 triangleNumber(self, nums: List[int]) -> int:\n nums.sort() # Sort the input array\n count = 0 # Initialize count of valid triangles\n \n # Loop through all possible triplets using two pointers\n for i in range(len(nums) - 2):\n k = i + 2 # Initialize third pointer to i + 2\n \n # If the first element of the triplet is 0, move to the next element\n if nums[i] == 0:\n continue\n \n # If all remaining elements in the array are zero, break out of the loop\n if nums[i+1] == 0 and nums[-1] == 0:\n break\n \n # Loop through all possible second elements of the triplet\n for j in range(i + 1, len(nums) - 1):\n \n # Move the third pointer to the first element that is greater than or equal to the sum of the first two elements\n while k < len(nums) and nums[i] + nums[j] > nums[k]:\n k += 1\n \n # The number of valid triangles that can be formed with the current pair of first two elements is the difference between the third pointer and the second pointer minus 1\n count += k - j - 1\n \n return count\n\n```
8
0
['Array', 'Two Pointers', 'Binary Search', 'Python', 'Python3']
0
valid-triangle-number
[Python] O(N^2) Explanation with Diagram
python-on2-explanation-with-diagram-by-w-mid8
Let\'s assume that a triplet for-loop (i, j, k) is used. Now, consider the following case.\n\n\n\n2. What should we do next? We can either\n\n\t Advance j, then
wei_lun
NORMAL
2020-07-13T13:42:33.390360+00:00
2020-07-13T13:42:33.390394+00:00
691
false
1. Let\'s assume that a triplet for-loop (i, j, k) is used. Now, consider the following case.\n\n![image](https://assets.leetcode.com/users/images/cdcf7fab-b679-4bc8-bcec-d2490386f2f1_1594647564.0569782.png)\n\n2. What should we do next? We can either\n\n\t* Advance j, then bring k to j + 1, or - O(N)\n\t* Advance j, then hold k where it is - O(1)\n\n3. Notice that if `num[i] + num[j] > num[k]`, then all numbers from [j + 1, k - 1] (the green area) must meet the condition. There is no need to drag k all the back to j + 1 and scan the elements all over again.\n\n4. Instead, we can set **increment count by the length of the green area** for every j value that we try.\n\n```\nclass Solution:\n def triangleNumber(self, nums: List[int]) -> int:\n count = 0\n nums = sorted(nums)\n \n # I REPRESENTS OUR 1ST (LHS) NUMBER\n for i in range(len(nums) - 2):\n \n # K REPRESENTS OUR 3RD (RHS) NUMBER\n k = i + 2\n \n # J REPRESENTS OUR 2ND (MID) NUMBER\n for j in range(i + 1, len(nums) - 1):\n \n # KEEP ADVANCING K UNTIL K > SUM(I, J)\n while k < len(nums) and nums[k] < nums[i] + nums[j]:\n k += 1\n \n # AS SOON AS K > SUM(I, J), RECORD THE COUNT\n count += max(0, k - j - 1)\n \n return count\n```
8
0
[]
1
valid-triangle-number
✅💯🔥Simple Code🚀📌|| 🔥✔️Easy to understand🎯 || 🎓🧠Beats 97%🔥|| Beginner friendly💀💯
simple-code-easy-to-understand-beats-97-h1b21
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
atishayj4in
NORMAL
2024-07-27T20:55:09.474332+00:00
2024-08-01T19:50:07.966775+00:00
1,021
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```\n// //////////////////ATISHAY\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ \\\\\n// \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\JAIN////////////////// \\\\\nclass Solution {\n public int triangleNumber(int[] nums) {\n Arrays.sort(nums);\n int res = 0, n = nums.length, i, j, k;\n for(i = 0; i<n ; i++) {\n for(j = i+1, k = j+1; j<(n - 1) && k<=n;) {\n if(k == n || nums[i]+nums[j] <= nums[k]){\n if(k > (j+1))\n res += k - j - 1;\n j++;\n }else k++;\n }\n }\n return res;\n }\n}\n```\n![7be995b4-0cf4-4fa3-b48b-8086738ea4ba_1699897744.9062278.jpeg](https://assets.leetcode.com/users/images/fe5117c9-43b1-4ec8-8979-20c4c7f78d98_1721303757.4674635.jpeg)
7
0
['Array', 'Two Pointers', 'Binary Search', 'Greedy', 'C', 'Sorting', 'Python', 'C++', 'Java']
0
valid-triangle-number
Easiest Python Solution to understand using two pointers
easiest-python-solution-to-understand-us-pqzj
\n# Code\n\nclass Solution:\n def triangleNumber(self, nums: List[int]) -> int:\n nums.sort()\n count = 0\n for k in range(len(nums) - 1
virendrapatil24
NORMAL
2024-05-18T12:39:40.970298+00:00
2024-05-18T12:39:40.970326+00:00
749
false
\n# Code\n```\nclass Solution:\n def triangleNumber(self, nums: List[int]) -> int:\n nums.sort()\n count = 0\n for k in range(len(nums) - 1, -1, -1):\n i = 0\n j = k - 1\n while i < j:\n if nums[i] + nums[j] > nums[k]:\n count += j - i\n j -= 1\n else:\n i += 1\n return count\n \n```
7
0
['Two Pointers', 'Python3']
0
valid-triangle-number
Easy peasy python solution O(n^2) time, O(1) space with explanation, very similar to 3sum smaller
easy-peasy-python-solution-on2-time-o1-s-ua3f
\tdef triangleNumber(self, nums: List[int]) -> int:\n ln = len(nums)\n if ln < 3:\n return 0\n res = 0\n nums.sort()\n
lostworld21
NORMAL
2019-08-14T04:40:15.224165+00:00
2019-08-14T05:05:03.565151+00:00
777
false
\tdef triangleNumber(self, nums: List[int]) -> int:\n ln = len(nums)\n if ln < 3:\n return 0\n res = 0\n nums.sort()\n \n # target(nums[i]) is till index 2, because start and end should be different\n # for i == 2, start 0 and end = 1\n for i in range(ln-1, 1, -1):\n start, end = 0, i-1\n target = nums[i]\n while start < end:\n if nums[start] + nums[end] > target:\n # assuming I fix the end and take all the elements from star to end-1 one by one\n # because, if nums[start] + nums[end] > target then nums[start+k] + nums[end],\n # where k < end is also greater than target\n # so now move on and try with end-1\n res += (end - start)\n end -= 1\n else:\n # I need to increase the nums[start] + nums[end], so move forward\n start += 1\n \n return res\n\t\t\n\n#3 sum solution, very similar\nhttps://leetcode.com/problems/3sum-smaller/discuss/358262/easy-peasy-python-solution-using-sort-O(n2)-with-comments
7
0
[]
2
valid-triangle-number
C++ Clean Code
c-clean-code-by-alexander-rhff
Binary Search O(N2lgN)\n\nclass Solution {\npublic:\n int triangleNumber(vector<int>& a) {\n int n = a.size();\n sort(a.begin(), a.end());\n
alexander
NORMAL
2017-06-11T03:18:53.286000+00:00
2017-06-11T03:18:53.286000+00:00
2,132
false
**Binary Search O(N<sup>2</sup>lgN)**\n```\nclass Solution {\npublic:\n int triangleNumber(vector<int>& a) {\n int n = a.size();\n sort(a.begin(), a.end());\n int res = 0;\n for (int i = 0; i < n - 2; i++) {\n for (int j = i + 1; j < n - 1; j++) {\n int sum = a[i] + a[j]; // the sum of 2 shortest sides;\n int firstGE = firstGreatOrEqual(a, j + 1, sum);\n res += firstGE - 1 - j;\n }\n }\n return res;\n }\n\nprivate:\n int firstGreatOrEqual(vector<int>& a, int i0, int target) {\n int lo = i0, hi = a.size();\n while (lo < hi) {\n int mid = (lo + hi) / 2;\n if (a[mid] < target) {\n lo = mid + 1;\n }\n else {\n hi = mid;\n }\n }\n return hi;\n }\n};\n```\n**2 Pointers O(N<sup>2</sup>)**\n```\nclass Solution {\npublic:\n int triangleNumber(vector<int>& a) {\n int res = 0;\n sort(a.begin(), a.end());\n reverse(a.begin(), a.end()); // a is decreasing\n for (int i = 0; i + 2 < a.size(); i++) {\n for (int j = i + 1, k = a.size() - 1; j < k; j++) {\n while (j < k && a[j] + a[k] <= a[i]) {\n k--;\n }\n res += k - j;\n }\n }\n return res;\n }\n};\n```
7
1
[]
4
valid-triangle-number
Two-pointers approach explained || Beats 96.12%🔥✌️|| JAVA
two-pointers-approach-explained-beats-96-vbof
Intuition\n The problem requires us to find the number of valid triangles that can be formed using elements from the input array.\n We can use a two-pointer app
prateekrjt14
NORMAL
2024-02-15T04:43:19.325767+00:00
2024-02-15T04:43:19.325797+00:00
984
false
# Intuition\n* *The problem requires us to find the number of valid triangles that can be formed using elements from the input array.*\n* *We can use a two-pointer approach to efficiently find these triangles.*\n# Approach\n1. Sort the input array in non-decreasing order.\n2. Initialize a variable count to keep track of the number of valid triangles found.\n3. Iterate through the array from right to left, considering each element as the largest side of a potential triangle.\n4. For each element at index i, use two pointers (left and right) to find pairs of smaller sides that can form a valid triangle with the element at index i.\n5. If the sum of two smaller sides (pointed by left and right) is greater than the largest side (at index i), it forms a valid triangle with all elements between left and right.\n6. Increment count by the number of valid triangles found between left and right.\n7. Move the right pointer one step to the left if a valid triangle is found, else move left pointer one step to the right.\n8. Repeat steps 4-7 until all combinations are checked for each element as the largest side.\n\n# Complexity\n- Time complexity:\n**O(n^2)**\n\n- Space complexity:\n**O(1)** since we are using only a constant amount of extra space for variables like count, left, and right pointers\n\n# Code\n```\nclass Solution {\n public int triangleNumber(int[] nums) {\n // Sort the input array\n Arrays.sort(nums);\n \n int n = nums.length;\n int count = 0;\n \n // Iterate through the array from right to left\n for (int i = n - 1; i >= 1; i--) {\n int left = 0;\n int right = i - 1;\n \n // Use two pointers approach to find valid triangles\n while (left < right) {\n // If the sum of two smaller sides is greater than the largest side, it forms a valid triangle\n if (nums[left] + nums[right] > nums[i]) {\n // Increment count by the number of valid triangles found between left and right pointers\n count += right - left;\n right--;\n } else {\n left++;\n }\n }\n }\n \n return count;\n }\n}\n\n```
6
0
['Array', 'Two Pointers', 'Greedy', 'Sorting', 'Java']
2
valid-triangle-number
Fast & Easy Solution
fast-easy-solution-by-purandhar999-vziu
\n# Code\n\nclass Solution {\n public int triangleNumber(int[] a) {\n Arrays.sort(a);\n int n=a.length;\n int count=0;\n for(int
Purandhar999
NORMAL
2023-12-10T09:31:03.990553+00:00
2023-12-10T09:31:03.990577+00:00
690
false
\n# Code\n```\nclass Solution {\n public int triangleNumber(int[] a) {\n Arrays.sort(a);\n int n=a.length;\n int count=0;\n for(int i=n-1;i>=1;i--){\n int left=0,right=i-1;\n while(left<right){\n if(a[left]+a[right]>a[i]){\n count+=right-left;\n right--;\n }\n else\n left++;\n }\n }\n return count;\n }\n}\n```
6
0
['Java']
0
valid-triangle-number
Python - O(N^3) ➜ O(N^2 * LogN) ➜ O(N^2)
python-on3-on2-logn-on2-by-itsarvindhere-6hxb
1. BRUTE FORCE - O(N^3)\n\nThe most straightforward way is to have three nested loops and try to find all the combinations of sides a,b and c such that - \n\t\t
itsarvindhere
NORMAL
2022-10-20T09:05:14.536382+00:00
2022-10-20T10:30:05.365122+00:00
825
false
## **1. BRUTE FORCE - O(N^3)**\n\nThe most straightforward way is to have three nested loops and try to find all the combinations of sides a,b and c such that - \n\t\t\n\t\t\ta + b > c\n\t\t\ta + c > b\n\t\t\tb + c > a\n\t\t\t\nWill give TLE for large inputs.\n\n def triangleNumber(self, nums: List[int]) -> int:\n count = 0\n \n nums.sort()\n \n for i1 in range(len(nums)):\n for i2 in range(i1 + 1, len(nums)):\n for i3 in range(i2 + 1, len(nums)):\n \n condition1 = nums[i1] + nums[i2] > nums[i3]\n condition2 = nums[i1] + nums[i3] > nums[i2]\n condition3 = nums[i2] + nums[i3] > nums[i1]\n \n if condition1 and condition2 and condition3: count += 1\n \n return count\n\t\t\n## **2. BINARY SEARCH - O(N^2 * LogN) (TLE in Python, works in Java)**\n\nIf we sort the given list, then we can use Binary search to get the time complexity down from O(N^3) to O(N^2 * LogN). As you can notice, we will do that by using Binary Search on the inner most loop instead of linear search i.e., O(N) to O(LogN)\n\n\tLets take nums = [2,2,3,4]\n\t\n\tSo, we will still have two nested for loops for two sides. So initially,\n\t\n\twe have \n\t\n\t\ta = 2\n\t\tb = 2\n\t\t\n\tAnd we want to search a side c. \n\nWhat should be the criteria to search side c? How can we say if a particular side "c" is valid?\n\t\n\tNotice the conditions - \n\t\n\t\t\ta + b > c\n\t\t\ta + c > b\n\t\t\tb + c > a\n\t\n\tSince we have sorted our list, that means "c" will always be bigger or equal to a and b. \n\t\n\tThat also means, \n\t\t\t\n\t\t\t\ta + c > b \n\t\t\t\t and \n\t\t\t\tb + c > a\n\t\t\t\t\n\twill always be true for any value of "c" because c is >= a and c >= b\n\t\n\t\n\tSo the only condition left is a + b > c\n\t\n\tSince the array is sorted, that means if we can find the largest possible value of "c" \n\tsuch that it is still smaller than "a +b", \n\tthen all the numbers in between will be all the value values of third side.\n\t\n\te.g. [2,2,3,4]\n\t\n\tSince a = 2 and b = 2\n\t\n\tWe start binary search from value 3 (index = 2)\n\t\n\tWe get mid = index 2 at which we have 3. \n\t\n\tNow we check if a + b > c or not.\n\t\n\tSince 2 + 2 > 3, that means, 3 is a valid value for a third side if first and second side is 2 and 2 respectively.\n\t\n\tBut we won\'t stop here. Can we find a value bigger than 3 that also satisfies this condition? \n\t\n\tSo we continue. Next, mid = index 3 at which we have value = 4\n\t\n\tNow we check if a + b > c. \n\t\n\tSince 2 + 2 > 4 is not correct, that means, 4 cannot be a valid third side length if a = 2 and b = 2\n\t\n\tHence, for a = 2 and b = 2, we can have only one valid value as third side.\n\n\nThis means, once we find the largest value for third side such that a + b > c, we can use any value that is between the index of b and the largest value we found via binary search (both included) to make a triangle. Hence, we increment our count by the number of values between "b" index and the index of the largest valid value we got via Binary Search.\n\n### **IN PYTHON, IT GIVES TLE**\n\n```\ndef triangleNumber(self, nums: List[int]) -> int:\n count = 0\n \n # Sort the list in increasing order\n nums.sort()\n \n n = len(nums)\n \n for i in range(n - 2):\n for j in range(i + 1, n - 1):\n \n # Binary Search for the third side\n start = j + 1\n end = n - 1\n res = None\n \n while start <= end:\n mid = start + (end - start) // 2\n \n if nums[i] + nums[j] > nums[mid]:\n res = mid\n start = mid + 1\n else: end = mid - 1\n\n if res: count += res - j\n \n return count\n```\n\t\n### **IN JAVA, IT WORKS**\t\n\n```\npublic int triangleNumber(int[] nums) {\n int count = 0;\n \n Arrays.sort(nums);\n \n int n = nums.length;\n \n \n for (int i = 0; i < n - 2; i++){\n for (int j = i + 1; j < n - 1; j++){\n \n int start = j + 1;\n int end = n - 1;\n int res = -1;\n \n while (start <= end){\n int mid = start + ((end - start) / 2);\n \n if(nums[i] + nums[j] > nums[mid]){\n res = mid;\n start = mid + 1;\n } else {\n end = mid - 1;\n }\n \n }\n \n if (res != -1) count += res - j;\n }\n }\n \n return count;\n```\n\t\n\t\n### **OPTIMIZATION TO MAKE THE BINARY SEACH SOLUTION FASTER**\t\n\n\nWe see that in the Binary Search code, for every new "j" value, we are again starting our binary search from "j+1" to the "last index", even if "i" is still the same. \n\nSo to make it better, we can pick off form where we left in previous "j" value. That is, reuse the previous "k" value in each iteration of the for loop for "j" value.\n\n```\n\ndef triangleNumber(self, nums: List[int]) -> int:\n count = 0\n \n # Sort the list in increasing order\n nums.sort()\n \n n = len(nums)\n \n for i in range(n - 2):\n k = i + 2\n if nums[i] != 0:\n for j in range(i + 1, n - 1):\n\n # Binary Search for the third side\n start = k\n end = n - 1\n res = None\n\n while start <= end:\n mid = start + (end - start) // 2\n\n if nums[i] + nums[j] > nums[mid]:\n res = mid\n start = mid + 1\n else: end = mid - 1\n\n if res: \n k = res\n count += res - j\n \n return count\n```\n\n\n\n## **3. TWO POINTERS (OR RATHER THREE) - O(N^2 )**\n\n```\ndef triangleNumber(self, nums: List[int]) -> int:\n count = 0\n \n # Sort the list in increasing order\n nums.sort()\n \n n = len(nums)\n \n \n # Initially, "c" points to the largest value in the list i.e., last index\n # a points to the smallest value in the list i.e., first index\n # b points to the value just before "c" i.e., last index - 1\n i = n - 1\n while i >= 2:\n # a => first side\n # b => second side\n # c => third side (largest of two)\n a,b,c = 0, i - 1, i\n \n \n while a < b: \n side1,side2,side3 = nums[a], nums[b], nums[c]\n \n # If this is true for any "a" and "b"\n # Then this will be true for any value between "a" and "b" as well\n # Because list is sorted\n if side1 + side2 > side3:\n # Hence, increment count by number of values between "b" and "a" indices (both included)\n count += b - a\n # Decrement "b" pointer\n b -= 1\n else:\n # Otherwise, increment "a" pointer\n a += 1\n \n # After each iteration, decrement the "c" pointer\n i -= 1\n \n return count\n```\n\n\n\n\n\n\n\n\n\n\n\n
6
0
['Binary Search', 'Binary Tree', 'Python']
1
valid-triangle-number
C++ Basic Simple Solution || Without Upper/Lower Bound
c-basic-simple-solution-without-upperlow-trlb
\nclass Solution {\npublic:\n int triangleNumber(vector<int>& nums) {\n sort(nums.begin() , nums.end()) ;\n int ans = 0 ;\n int n = nums
Maango16
NORMAL
2021-07-16T05:37:29.459117+00:00
2021-07-16T05:37:29.459159+00:00
181
false
```\nclass Solution {\npublic:\n int triangleNumber(vector<int>& nums) {\n sort(nums.begin() , nums.end()) ;\n int ans = 0 ;\n int n = nums.size() ;\n for(int k = 2 ; k < n ; k++)\n {\n int i = 0 , j = k - 1 ;\n while(i < j)\n {\n if(nums[i] + nums[j] <= nums[k])\n {\n i++ ;\n }\n else\n {\n ans += (j - i) ;\n j-- ;\n }\n }\n }\n return ans ; \n }\n};\n```
6
0
[]
0
valid-triangle-number
C++ Binary Search O(n^2logn)
c-binary-search-on2logn-by-shtanriverdi-jvc7
\nclass Solution {\npublic:\n int triangleNumber(vector<int>& nums) {\n sort(begin(nums), end(nums));\n int count = 0, len = nums.size(), wante
shtanriverdi
NORMAL
2021-07-15T20:28:17.686559+00:00
2021-07-15T20:28:17.686602+00:00
664
false
```\nclass Solution {\npublic:\n int triangleNumber(vector<int>& nums) {\n sort(begin(nums), end(nums));\n int count = 0, len = nums.size(), wanted;\n for (int i = 0; i < len - 2; i++) {\n for (int j = i + 1; j < len - 1; j++) {\n wanted = nums[i] + nums[j];\n int index = binarySearch(wanted, j + 1, len, nums);\n if (index != -1) {\n count += index - 1 - j;\n }\n }\n }\n return count;\n }\n \n // Return the left most number "c" such that a + b > c, return -1 otherwise\n int binarySearch(int target, int start, int &len, vector<int> &nums) {\n int l = start, r = len, mid;\n while (l < r) {\n mid = (l + r) / 2;\n if (nums[mid] < target) {\n l = mid + 1;\n }\n else {\n r = mid;\n }\n }\n return l;\n }\n};\n```
6
0
['C', 'Binary Tree']
0
valid-triangle-number
[Python3] Clean | Using bisect_left() | Binary Search
python3-clean-using-bisect_left-binary-s-h98d
This is the binary search solution using python module bisect_left()\n\nimport bisect as bs\nclass Solution:\n def triangleNumber(self, nums: List[int]) -> i
yadvendra
NORMAL
2021-07-15T18:59:34.013746+00:00
2021-07-16T05:02:30.264926+00:00
1,039
false
This is the binary search solution using python module [bisect_left()](https://docs.python.org/3/library/bisect.html)\n```\nimport bisect as bs\nclass Solution:\n def triangleNumber(self, nums: List[int]) -> int:\n n = len(nums)\n a= sorted(nums)\n count = 0\n for i in range(n):\n for j in range(i+1, n-1):\n k = bs.bisect_left(a, a[i] + a[j], lo = j+1)\n count += k - j - 1\n return count\n```\n\n**Time complexity:** O(N^2 logN)\n**Space complexity:** O(1)\n\nPlease upvote and share if this helps.!
6
1
['Binary Tree', 'Python', 'Python3']
0
valid-triangle-number
[Python] Two solutions with explanations
python-two-solutions-with-explanations-b-i66s
Sol 1. Binary Search\nPrior: If we know a < b < c , we know if a + b > c , then a, b, c can compose a valid triangle.\nExplanations: If we know the first two nu
codingasiangirll
NORMAL
2020-10-23T04:06:08.065955+00:00
2020-10-23T04:06:08.065994+00:00
681
false
Sol 1. Binary Search\n**Prior**: If we know `a < b < c` , we know if `a + b > c` , then `a, b, c` can compose a valid triangle.\n**Explanations**: If we know the first two numbers (`a, b`), then `c < a + b`. Since `nums` is sorted, we can find the left most upper bound and calculate the number of `c` that can compose valid triangle based on the other two sides is `a, b`.\n```\nclass Solution:\n def triangleNumber(self, nums: List[int]) -> int:\n nums.sort()\n res = 0\n for i, a in enumerate(nums):\n for j in range(i + 1, len(nums)):\n b = nums[j]\n # a + b > c\n k = bisect.bisect_left(nums, a + b)\n res += max(k - j - 1, 0)\n return res\n```\n**Complexity Analysis**: Time is O(N ^2 * logN), N is the length of `nums`. Space is O(logN), since sorting.\n\nSol 2. Two pointers\n**Explanations**: Sol 1 takes `a, b` as fixed term to find `c`, but we can fix `c` to find `a, b`.\nSince `nums` is sorted, we travrse backwards. If we find `nums[left] + nums[right] > nums[i]`, we know at index `left, right, i` have a triangle. Moreover, we know all indexs before `left` can combine with `right, i` to build a triangle. Hence, the number of valid triangles is `(right - left)`. If `nums[left] + nums[right] <= nums[i]`, we need to find bigger sum.\n```\nclass Solution:\n def triangleNumber(self, nums: List[int]) -> int:\n nums.sort()\n res = 0\n for i in range(len(nums) - 1, 1, -1):\n left, right = 0, i - 1\n while left < right:\n if nums[left] + nums[right] > nums[i]:\n res += (right - left)\n right -= 1\n else:\n left += 1\n return res\n```\n**Complexity Analysis**: Time is O(N ^2), N is the length of `nums`. Space is O(logN), since sorting.
6
0
['Two Pointers', 'Binary Tree']
1
valid-triangle-number
[Python3] O(N^2) time solution
python3-on2-time-solution-by-ye15-zwrt
O(N^2) 94.94%\n\nclass Solution:\n def triangleNumber(self, nums: List[int]) -> int:\n nums.sort()\n ans = 0\n for i in range(len(nums))
ye15
NORMAL
2020-10-08T03:36:44.342776+00:00
2021-07-15T19:50:43.681211+00:00
792
false
`O(N^2)` 94.94%\n```\nclass Solution:\n def triangleNumber(self, nums: List[int]) -> int:\n nums.sort()\n ans = 0\n for i in range(len(nums)): \n lo, hi = 0, i-1\n while lo < hi: \n if nums[lo] + nums[hi] > nums[i]:\n ans += hi - lo \n hi -= 1\n else: lo += 1\n return ans \n```\n\n```\nclass Solution:\n def triangleNumber(self, nums: List[int]) -> int:\n nums.sort()\n ans = 0\n for i in range(len(nums)):\n k = i+2\n for j in range(i+1, len(nums)):\n while k < len(nums) and nums[i] + nums[j] > nums[k]: k += 1\n if j < k: ans += k-1-j\n return ans \n```
6
0
['Python3']
5
valid-triangle-number
C++ CODE || Binary Search
c-code-binary-search-by-chiikuu-1h0u
Complexity\n- Time complexity: O(n*n(logn))\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)
CHIIKUU
NORMAL
2023-02-13T13:59:16.693437+00:00
2023-02-13T13:59:16.693473+00:00
1,297
false
# Complexity\n- Time complexity: **O(n*n(logn))**\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 {\npublic:\n int triangleNumber(vector<int>& nums) {\n sort(nums.begin(),nums.end());\n int t=0;\n for(int i=0;i<nums.size();i++){\n for(int j=i+1;j<nums.size();j++){\n int h = abs(nums[i]-nums[j]) + 1;\n h = lower_bound(nums.begin(),nums.end(),h) - nums.begin();\n int g = nums[i] + nums[j];\n g = lower_bound(nums.begin(),nums.end(),g) - nums.begin();\n g--;\n if(g>j)\n t+=g-(j+1)+1;\n }\n }\n return t;\n }\n};\n```
5
0
['Math', 'Binary Search', 'C++']
0
valid-triangle-number
C++ || Two Pointer || Easy Understanding || Fast
c-two-pointer-easy-understanding-fast-by-nbsi
Intuition\n Describe your first thoughts on how to solve this problem. \nTWO POINTER APPROACH ON DESCENDING ORDER ARRAY\n\n# Approach\n Describe your approach t
Asad9113
NORMAL
2022-12-07T17:02:21.711324+00:00
2022-12-07T17:02:21.711368+00:00
1,457
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTWO POINTER APPROACH ON DESCENDING ORDER ARRAY\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe all know that two pointer approach works easily on sorted array, but here is a trick we have to sort in descending order,\nsince if sum of two sides is greater than the larger side ,then our triangle is valid and this is a sufficient condition .No need to check any two sides....\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n^2)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1)\n\n# Code\n```\nclass Solution {\npublic:\n int triangleNumber(vector<int>& nums) {\n \n sort(nums.begin(),nums.end());\n reverse(nums.begin(),nums.end());\n \n int n=nums.size();\n int cnt=0;\n \n for(int i=0;i<n;i++){\n int j=i+1,k=n-1;\n \n while(j<k){\n int a=nums[i],b=nums[j],c=nums[k];\n if(b+c > a){\n cnt+=k-j;\n j++;\n }\n else{\n k--;\n }\n }\n }\n return cnt;\n }\n};\n```
5
0
['Two Pointers', 'C++']
1
valid-triangle-number
Java using two pointer | Easy and Clean code
java-using-two-pointer-easy-and-clean-co-xsr9
\nclass Solution {\n public int triangleNumber(int[] a) {\n Arrays.sort(a);\n int n=a.length;\n int count=0;\n for(int i=n-1;i>=1
rohitkumarsingh369
NORMAL
2021-07-16T06:21:29.467606+00:00
2021-07-16T06:59:21.354543+00:00
820
false
```\nclass Solution {\n public int triangleNumber(int[] a) {\n Arrays.sort(a);\n int n=a.length;\n int count=0;\n for(int i=n-1;i>=1;i--){\n int left=0,right=i-1;\n while(left<right){\n if(a[left]+a[right]>a[i]){\n count+=right-left;\n right--;\n }\n else\n left++;\n }\n }\n return count;\n }\n}\n```
5
0
['Java']
0
valid-triangle-number
[C++] Easy, Clean Solution in O(n^2)
c-easy-clean-solution-in-on2-by-rsgt24-4hg2
Solution:\n\nclass Solution {\npublic:\n int triangleNumber(vector<int>& nums) {\n sort(nums.begin(), nums.end());\n int ans = 0;\n for(
rsgt24
NORMAL
2021-07-15T07:39:03.507141+00:00
2021-07-15T07:45:18.692635+00:00
597
false
**Solution:**\n```\nclass Solution {\npublic:\n int triangleNumber(vector<int>& nums) {\n sort(nums.begin(), nums.end());\n int ans = 0;\n for(int i = 2; i < nums.size(); i++){\n int l = 0, r = i - 1;\n while(l < r){\n if(nums[l] + nums[r] > nums[i]){\n ans += r - l;\n r--;\n }\n else\n l++;\n }\n }\n return ans;\n }\n};\n```\n\n**Time Complexity:** `O(n^2)`\n\n**Feel free to share your ideas or any improvements as well.**
5
0
['C', 'Sorting']
0
valid-triangle-number
c++, O(n^2)
c-on2-by-dayao-mw4p
\nclass Solution {\npublic:\n int triangleNumber(vector<int>& nums) {\n sort(nums.begin(), nums.end());\n int res = 0;\n for (int i = nu
dayao
NORMAL
2019-10-06T08:49:24.094906+00:00
2019-10-06T08:49:24.094943+00:00
596
false
```\nclass Solution {\npublic:\n int triangleNumber(vector<int>& nums) {\n sort(nums.begin(), nums.end());\n int res = 0;\n for (int i = nums.size() - 1; i > 1; i--) {\n int l = 0;\n int r = i - 1;\n while (l < r) {\n if (nums[l] + nums[r] > nums[i]) {\n res += r - l;\n r--;\n } else {\n l++;\n }\n }\n }\n return res;\n }\n};\n```
5
0
[]
1
valid-triangle-number
Python, Straightforward with Explanation
python-straightforward-with-explanation-6t4cu
Sort the array. For every pair of sticks u, v with stick u occuring before v (u <= v), we want to know how many w occuring after v have w < u + v.\n\nFor every
awice
NORMAL
2017-06-11T19:12:51.916000+00:00
2017-06-11T19:12:51.916000+00:00
2,730
false
Sort the array. For every pair of sticks u, v with stick u occuring before v (u <= v), we want to know how many w occuring after v have w < u + v.\n\nFor every middle stick B[j] = v, we can use two pointers: one pointer i going down from j to 0, and one pointer k going from the end to j. This is because if we have all w such that w < u + v, then decreasing u cannot make this set larger.\n\nLet's look at an extension where our sorted array is grouped into counts of it's values. For example, instead of dealing with A = [2,2,2,2,3,3,3,3,3,4,4,4], we should deal with only B = [2, 3, 4] and keep a sidecount of C[2] = 4, C[3] = 5, C[4] = 3. We'll also keep a prefix sum P[k] = C[B[0]] + C[B[1]] + ... + C[B[k-1]] (and P[0] = 0.)\n\nWhen we are done setting our pointers and want to add the result, we need to add the result taking into account multiplicities (how many times each kind of triangle occurs.) When i == j or j == k, this is a little tricky, so let's break it down case by case.\n\n* When i < j, we have C[B[i]] * C[B[j]] * (P[k+1] - P[j+1]) triangles where the last stick has a value > B[j]. Then, we have another C[B[i]] * (C[B[j]] choose 2) triangles where the last stick has value B[j].\n* When i == j, we have (C[B[i]] choose 2) * (P[k+1] - P[j+1]) triangles where the last stick has value > B[j]. Then, we have another (C[B[i]] choose 3) triangles where the last stick has value B[j].\n\n```\ndef triangleNumber(self, A):\n C = collections.Counter(A)\n C.pop(0, None)\n B = sorted(C.keys())\n P = [0]\n for x in B:\n P.append(P[-1] + C[x])\n \n ans = 0\n for j, v in enumerate(B):\n k = len(B) - 1\n i = j\n while 0 <= i <= j <= k:\n while k > j and B[i] + B[j] <= B[k]:\n k -= 1\n if i < j:\n ans += C[B[i]] * C[B[j]] * (P[k+1] - P[j+1])\n ans += C[B[i]] * C[B[j]] * (C[B[j]] - 1) / 2\n else:\n ans += C[B[i]] * (C[B[i]] - 1) / 2 * (P[k+1] - P[j+1])\n ans += C[B[i]] * (C[B[i]] - 1) * (C[B[i]] - 2) / 6\n i -= 1\n return ans\n```
5
2
[]
1
valid-triangle-number
Brute-Better-Optimal || Beats 99.13% 🔥 || Java, C++ || Explanation & Code || Two-Pointers
brute-better-optimal-beats-9913-java-c-e-1y5o
Intuition\n- This problem asks to find the number of valid triangles which can be formed using array elements as length of sides of triangles.\n- We can solve t
girish13
NORMAL
2024-02-18T11:19:08.312809+00:00
2024-02-18T11:32:36.484893+00:00
208
false
# Intuition\n- This problem asks to find the number of valid triangles which can be formed using array elements as length of sides of triangles.\n- We can solve this problem using three approaches, each approach giving us a better time complexity.\n\n\n# Brute Force Approach\n\n1. Sort the input array `nums` in ascending order.\n2. Initialize a variable `ans` to store the count of valid triangles and get the length of the array `nums` as `n`.\n3. Iterate over the array from left to right.\n4. Choose a triplet everytime from the array and check whether it satisfies the triangle property.\n5. If the property is satisfied increment the count.\n\n#### Code\n```java []\nclass Solution {\n public int triangleNumber(int[] nums) {\n Arrays.sort(nums);\n int ans = 0, n = nums.length;\n for(int i = 0; i < n - 2; i++){\n for(int j = i + 1; j < n - 1; j++){\n for(int k = j + 1; k < n; k++){\n if(nums[i] + nums[j] > nums[k]) ans++;\n else break;\n }\n }\n }\n return ans;\n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n int triangleNumber(vector<int>& nums) {\n sort(nums.begin(), nums.end());\n int ans = 0, n = nums.size();\n for(int i = 0; i < n - 2; i++){\n for(int j = i + 1; j < n - 1; j++){\n for(int k = j + 1; k < n; k++){\n if(nums[i] + nums[j] > nums[k]) ans++;\n else break;\n }\n }\n }\n return ans;\n }\n};\n```\n\n#### Complexity\n- Time complexity: $$O(n^3)$$\n- Space complexity: $$O(1)$$\n\n\n# Better Approach : Using Binary Search\n\n1. Sort the input array `nums` in ascending order.\n2. Initialize a variable `ans` to store the count of valid triangles and get the length of the array `nums` as `n`.\n3. Using two nested loops to iterate over pairs of indices (i, j) in the sorted array. The outer loop (i) goes from 0 to n-3, and the inner loop (j) goes from i+1 to n-2.\n4. The elements `nums[i]` and `nums[j]` represents two sides of triangle.\n5. Now, to find the valid third side, we will use binary search. \n6. Inside the nested loops, initialize `low` to `j+1` and `high` to `n-1`. These variables will be used to search for the right endpoint of a valid triangle.\n7. Now, calculate the maximum possible value for the third side of the triangle using the current elements at indices i and j. The condition `nums[i] + nums[j] - 1` represents the triangle inequality.\n8. Initialize `ind` to `-1`. This variable will be used to store the index of the right endpoint of the triangle in the array.\n9. Perform a binary search between low and high to find the rightmost index (`ind`) where `nums[ind]` is less than or equal to max.\n10. If a valid index (`ind`) is found, update the `ans` by adding the count of valid triangles formed with the current pair of indices (i, j).\n\n#### Code\n\n```Java []\nclass Solution {\n public int triangleNumber(int[] nums) {\n Arrays.sort(nums);\n int ans = 0, n = nums.length;\n for(int i = 0; i < n - 2; i++){\n for(int j = i + 1; j < n - 1; j++){\n int low = j + 1, high = n - 1;\n int max = nums[i] + nums[j] - 1;\n int ind = -1;\n while(low <= high){\n int mid = low + (high - low) / 2;\n if(nums[mid] <= max){\n ind = mid;\n low = mid + 1;\n }\n else high = mid - 1;\n }\n if(ind != -1) ans += (ind - j);\n }\n }\n return ans;\n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n int triangleNumber(vector<int>& nums) {\n sort(nums.begin(), nums.end());\n int ans = 0, n = nums.size();\n for(int i = 0; i < n - 2; i++){\n for(int j = i + 1; j < n - 1; j++){\n int low = j + 1, high = n - 1;\n int max = nums[i] + nums[j] - 1;\n int ind = -1;\n while(low <= high){\n int mid = low + (high - low) / 2;\n if(nums[mid] <= max){\n ind = mid;\n low = mid + 1;\n }\n else high = mid - 1;\n }\n if(ind != -1) ans += (ind - j);\n }\n }\n return ans;\n }\n};\n```\n\n#### Complexity\n\n- Time complexity: $$O(n^2logn)$$\n- Space complexity: $$O(1)$$\n\n# Optimal Approach : Using Two-Pointer Technique\n1. Sort the input array `nums` in ascending order.\n2. Initialize a variable `ans` to store the count of valid triangles and get the length of the array `nums` as `n`.\n3. The loop starts from index `2` as we want to create triangles with three distinct indices (0, 1, and i). This avoids redundancy by considering unique combinations.\n4. Initialize two pointers `l = 0` and `r = n - 1`. `l` and `r` represents the first smallest and second smallest side of the possible triangle(s).\n5. If the sum of elements at `l` and `r` is greater than the element at index `i`, it means a valid triangle can be formed. Increment `ans` by the number of valid triangles that can be formed with the current `l` and `r` indices, i.e. all possible elements between l and r can form a triangle with `nums[i]` as largest side. So, we do `ans += r - l`. Now, decrement the right pointer (`r`) to explore other possible triangles with the current `l` index.\n6. If the sum is not greater than the element at index `i`, increment the left pointer (`l`) to explore larger values for the smallest side of triangle.\n7. Return the `ans` that stores count of valid triangles.\n\n\n#### Code\n\n```java []\nclass Solution {\n public int triangleNumber(int[] nums) {\n Arrays.sort(nums);\n int ans = 0, n = nums.length;\n for(int i = 2; i < n; i++){\n int l = 0, r = i - 1;\n while(l < r){\n if(nums[l] + nums[r] > nums[i]){\n ans += (r - l);\n r--;\n }\n else l++;\n }\n }\n return ans;\n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n int triangleNumber(vector<int>& nums) {\n sort(nums.begin(), nums.end());\n int ans = 0, n = nums.size();\n for(int i = 2; i < n; i++){\n int l = 0, r = i - 1;\n while(l < r){\n if(nums[l] + nums[r] > nums[i]){\n ans += (r - l);\n r--;\n }\n else l++;\n }\n }\n return ans;\n }\n};\n```\n\n\n#### Complexity\n\n- Time complexity: $$O(n^2)$$\n- Space complexity: $$O(1)$$\n\n\nPlease upvote (\uD83D\uDC4D) if you understood & liked the approach and explanation \uD83D\uDE0A
4
0
['Two Pointers', 'Binary Search', 'Greedy', 'Sorting', 'C++', 'Java']
0
valid-triangle-number
Full Explanation + Python 2 line
full-explanation-python-2-line-by-speedy-yx22
Solution 1 :\n## What Q asked to do :\n\nnums = [0,0,10,15,17,19,20,22,25,26,30,31,37] (sorted version)\n\nIf nums[i] is not 0 as with 0 length a triangle is no
speedyy
NORMAL
2023-05-25T15:06:33.518247+00:00
2023-05-25T19:06:13.261082+00:00
737
false
## Solution 1 :\n## What Q asked to do :\n```\nnums = [0,0,10,15,17,19,20,22,25,26,30,31,37] (sorted version)\n\nIf nums[i] is not 0 as with 0 length a triangle is not possible :\n_________________________________________________________________\n\nfor a triangle we need 3 length and if a+b>c and a+c>b and b+c>a BUT since we are \'sorting\'\nwe need to check only one condition, "a+b>c"\n\n nums[2] + nums[3] = 10 + 15 = 25. \n Now with this summation of these TWO FIXED VALUE we will compare it with other values :\n \nnums = [0,0, 10,15, 17,19,20,22, 25,26,30,31,37] (sorted version)\n |___| |__________| |\n | | |_____ We stop here as it defies the rule "a+b>c"\nFixed Value ---| These 4 values (25>25 -- False)\nSummation = 25 are less than 25\n and satisfy the \n rule a+b>c\n\nSince the list is sorted, we can find the FIRST VALUE WHICH IS EQUAL OR GREATER THAN THE \nSUMMATION with lower_bound IN CPP and bisect_left in Python.\n\nWe checked for 10,15,17 10,15,19 10,15,20 ...... what about for 10,17,19 10,17,20?\n\nI believe you got the idea now.\n```\n```CPP []\nclass Solution \n{\npublic:\n int triangleNumber(vector<int>& nums) \n {\n sort(begin(nums), end(nums));\n int lb, count = 0, ni = nums.size()-2, nj = nums.size()-1;\n for(int i=0; i<ni; i++)\n {\n for(int j=i+1; j<nj ;j++)\n {\n lb = lower_bound(nums.begin()+j+1, nums.end(), nums[i]+nums[j]) - nums.begin();\n count += lb - j -1;\n }\n }\n return count;\n }\n};\n```\n```Python []\nclass Solution:\n def triangleNumber(self, nums: List[int]) -> int:\n nums.sort()\n return sum( bisect_left(nums, nums[i]+nums[j]) - j-1 for i in range(len(nums)-2) if nums[i]!=0 for j in range(i+1, len(nums)-1) )\n```\n```\nTime complexity : O(n^2 logn) as for every O(n^2) we did logn operation\nSpace complexity : O(1)\n```\n\n## Modification in solution 1\n```\nnums = [0,0, 10,15, 17,19,20,22, 25,26,30,31,37] (sorted version)\n |___| |__________| |\n | |_____ We stop here.\n 25 \n\nnums = [0,0, 10,15,17,19,20,22, 25,26,30,31,37] (sorted version)\n |_____| |\n | |_____ For 27 start from here.\n 27\n\nIf for the summation of 25, 17,19,20,22 are true, then for 27 19,20,22 already true as 27>25\n |_________|\nso start from previous inside the loop of \'j\'. for every \'i\', lb = i+2.\nNow the lower_bound won\'t even run O(n) inside the nested loop till j stops, so TC is O(n^2) \n\nfor testcases : nums = [1,2,3,4,5]\nfor i = 0, j = 1 : bisect_left/lower_bound will return 1 for searching 1+2 = 3\nsince the index of 3 is 2, then j will be 2 also, but we don\'t want to start our\nlower_bound/bisect_left at the same index of j, so I added (lb == j) which will handle this. \n``` \n```CPP []\nclass Solution \n{\npublic:\n int triangleNumber(vector<int>& nums) \n {\n sort(begin(nums), end(nums));\n int lb = 0, count = 0, ni = nums.size()-2, nj = nums.size()-1;\n for(int i=0; i<ni; i++)\n {\n if(nums[i] == 0) continue;\n lb = i+2;\n for(int j=i+1; j<nj; j++)\n {\n lb = lower_bound(begin(nums)+lb+(lb==j), end(nums), nums[i]+nums[j]) - begin(nums);\n count += lb - j-1;\n }\n }\n return count;\n }\n};\n```\n```CPP []\nclass Solution \n{\npublic:\n int triangleNumber(vector<int>& nums) \n {\n sort(begin(nums), end(nums));\n int lb = 0, count = 0, ni = nums.size()-2, nj = nums.size()-1;\n for(int i=0; i<ni; i++)\n {\n if(nums[i] == 0) continue;\n lb = i+2;\n for(int j=i+1; j<nj; j++)\n {\n // without lower bound\n while(lb<nums.size() && nums[i]+nums[j]>nums[lb])\n lb++;\n count += lb - j-1;\n }\n }\n return count;\n }\n};\n```\n```Python []\nclass Solution:\n def triangleNumber(self, nums: List[int]) -> int:\n nums.sort()\n count = lb = 0\n for i in range(len(nums)-2):\n if nums[i] == 0: continue\n lb = i + 2\n for j in range(i+1, len(nums)-1):\n lb = bisect_left(nums, nums[i]+nums[j], lb+(lb==j))\n count += lb - j - 1\n \n return count\n```\n```\nTime Complexity : O(n^2) which i explained why.\nSpace Complexity : O(1)\n```\n## If the post was helpful to you, an upvote will really make me happy:)
4
0
['C++', 'Python3']
0
valid-triangle-number
C++ Solution
c-solution-by-pranto1209-056c
Code\n\nclass Solution {\npublic:\n int triangleNumber(vector<int>& nums) {\n sort(nums.begin(), nums.end());\n int ans = 0;\n for(int k
pranto1209
NORMAL
2023-04-30T15:23:48.829663+00:00
2023-04-30T15:23:48.829708+00:00
267
false
# Code\n```\nclass Solution {\npublic:\n int triangleNumber(vector<int>& nums) {\n sort(nums.begin(), nums.end());\n int ans = 0;\n for(int k = nums.size() - 1; k > 1; k--) {\n int i = 0, j = k-1;\n while(i < j) {\n if(nums[i] + nums[j] > nums[k]) {\n ans += j - i;\n j--;\n } \n else i++;\n }\n }\n return ans;\n }\n};\n```
4
0
['C++']
0
valid-triangle-number
Simple C++ Solution with comments
simple-c-solution-with-comments-by-divya-23dz
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
Divyanshu_singh_cs
NORMAL
2023-02-19T14:42:02.383185+00:00
2023-02-19T14:42:02.383228+00:00
1,457
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 int triangleNumber(vector<int>& nums) {\n int ans=0;\n int n = nums.size();\n//sorting the given array\n sort(nums.begin(),nums.end());\n//iterating from end to 2nd element\n for(int i=n-1;i>=2;i--){\n int low=0;\n int high=i-1;\n//setting high as previous of greater element\n while(low<high){\n\n if(nums[low]+nums[high]>nums[i]){\n//if element at low and high index is greater than largest element\n ans += (high-low);\n//then setting ans as high-low i.e, all elemnt between this range is \n//counted\n high--;\n }\n else{\n low++;\n }\n }\n }\n return ans;\n//at last we return the answer\n }\n};\n```
4
0
['C++']
1
valid-triangle-number
C++ || Binary search || Easy approach
c-binary-search-easy-approach-by-mrigank-pqnw
Here is my c++ code for this problem.\n\n# Complexity\n- Time complexity:O(NNlogN)\n\n- Space complexity:O(1)\n\n# Code\n\nclass Solution {\npublic:\n int tr
mrigank_2003
NORMAL
2022-12-17T06:30:44.057320+00:00
2022-12-17T06:30:44.057357+00:00
991
false
Here is my c++ code for this problem.\n\n# Complexity\n- Time complexity:O(N*N*logN)\n\n- Space complexity:O(1)\n\n# Code\n```\nclass Solution {\npublic:\n int triangleNumber(vector<int>& nums) {\n sort(nums.begin(), nums.end());\n int ans=0;\n for(int i=0; i<nums.size(); i++){\n for(int j=i+1; j<nums.size(); j++){\n int num=nums[i]+nums[j];\n int st=j+1, en=nums.size()-1;\n while(st<=en){\n int mid=st+(en-st)/2;\n if(nums[mid]<num){\n st=mid+1;\n }\n else{en=mid-1;}\n }\n //cout<<st<<endl;\n ans+=en-j;\n }\n }\n return ans;\n }\n};\n```
4
0
['Binary Search', 'Greedy', 'C++']
0