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
make-a-square-with-the-same-color
Beats 100% | Python | Easy to Understand | Complex to Write 🌚🕺🦹‍♂️
beats-100-python-easy-to-understand-comp-22pv
IntuitionFOR THE LACKWITS!!! There are only 9 cells. Square is made up of 4 cells. There are only 4 squares. So, why not hard code it?!!ApproachComplexity Time
aman-sagar
NORMAL
2025-01-27T17:29:34.781555+00:00
2025-01-27T17:29:34.781555+00:00
40
false
# Intuition **FOR THE LACKWITS!!!** There are only 9 cells. Square is made up of 4 cells. There are only 4 squares. So, why not hard code it?!! # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: O(1) <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: O(1) <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```python3 [] class Solution: def canMakeSquare(self, grid: List[List[str]]) -> bool: count_black_00 = 0 count_black_01 = 0 count_black_10 = 0 count_black_11 = 0 if grid[0][0] == "B": count_black_00 += 1 if grid[0][1] == "B": count_black_00 += 1 count_black_01 += 1 if grid[0][2] == "B": count_black_01 += 1 if grid[1][0] == "B": count_black_00 += 1 count_black_10 += 1 if grid[1][1] == "B": count_black_10 += 1 count_black_11 += 1 count_black_00 += 1 count_black_01 += 1 if grid[1][2] == "B": count_black_11 += 1 count_black_01 += 1 if grid[2][0] == "B": count_black_10 += 1 if grid[2][1] == "B": count_black_11 += 1 count_black_10 += 1 if grid[2][2] == "B": count_black_11 += 1 white_00 = 4 - count_black_00 white_01 = 4 - count_black_01 white_10 = 4 - count_black_10 white_11 = 4 - count_black_11 return 1 in (count_black_00, count_black_01, count_black_10, count_black_11, white_00, white_01, white_10, white_11) or 0 in (count_black_00, count_black_01, count_black_10, count_black_11, white_00, white_01, white_10, white_11) ```
1
0
['Array', 'Matrix', 'Enumeration', 'Python3']
1
make-a-square-with-the-same-color
0ms 100% beat in java very easiest code 😊.
0ms-100-beat-in-java-very-easiest-code-b-delo
Code
Galani_jenis
NORMAL
2025-01-08T11:43:54.375573+00:00
2025-01-08T11:43:54.375573+00:00
114
false
![94da60ee-7268-414c-b977-2403d3530840_1725903127.9303432.png](https://assets.leetcode.com/users/images/7a567181-0007-4cec-aebc-82d3126d9742_1736336518.5675416.png) # Code ```java [] class Solution { public boolean canMakeSquare(char[][] grid) { byte countB = 0, countW = 0; for (int i = 0; i <= 1; i++) { for (int j = 0; j <= 1; j++) { if (grid[i][j] == 'B') { countB++; }else { countW++; } } if (countB > 2 || countW > 2) { return true; } } countB = 0; countW = 0; for (int i = 0; i <= 1; i++) { for (int j = 1; j <= 2; j++) { if (grid[i][j] == 'B') { countB++; }else { countW++; } } if (countB > 2 || countW > 2) { return true; } } countB = 0; countW = 0; for (int i = 1; i <= 2; i++) { for (int j = 0; j <= 1; j++) { if (grid[i][j] == 'B') { countB++; }else { countW++; } } if (countB > 2 || countW > 2) { return true; } } countB = 0; countW = 0; for (int i = 1; i <= 2; i++) { for (int j = 1; j <= 2; j++) { if (grid[i][j] == 'B') { countB++; }else { countW++; } } if (countB > 2 || countW > 2) { return true; } } return false; } } ```
1
0
['Java']
0
make-a-square-with-the-same-color
Easy Solution in C
easy-solution-in-c-by-sathurnithy-kbjo
Code
Sathurnithy
NORMAL
2025-01-05T13:55:01.964327+00:00
2025-01-05T13:55:01.964327+00:00
21
false
# Code ```c [] bool canMakeSquare(char** grid, int gridSize, int* gridColSize) { for(int i=0; i<2; i++){ for(int j=0; j<2; j++){ int gridSumWhite = (grid[i][j] == 'W' ? 1:0) + (grid[i][j+1] == 'W' ? 1:0) + (grid[i+1][j] == 'W' ? 1:0) + (grid[i+1][j+1] == 'W' ? 1:0); if(gridSumWhite >= 3 || gridSumWhite <= 1) return true; } } return false; } ```
1
0
['C']
0
make-a-square-with-the-same-color
C
c-by-pavithrav25-m8yn
IntuitionApproachComplexity Time complexity: Space complexity: Code
pavithrav25
NORMAL
2025-01-02T16:15:35.614695+00:00
2025-01-02T16:15:35.614695+00:00
29
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```c [] bool canMakeSquare(char** grid, int gridSize, int* gridColSize) { int n = gridSize; int m = (*gridColSize); for (int i = 0; i < n - 1; i++) { for (int j = 0; j < m - 1; j++) { int b = 0, w = 0; for (int m1 = 0; m1 < 2; m1++) { for (int m2 = 0; m2 < 2; m2++) { if (grid[i + m1][j + m2] == 'W') w++; else b++; } } if (b >= 3 || w >= 3) return 1; } } return 0; } ```
1
0
['C']
0
make-a-square-with-the-same-color
Simple Kotlin solution
simple-kotlin-solution-by-tamhuynhit-twwd
Intuition\nCheck each 2x2 square, if it has 3 \'B\' or 3 \'W\' then it\'s valid and return True immediately.\n\nThere is special cases where there is an already
tamhuynhit
NORMAL
2024-08-24T06:35:19.096910+00:00
2024-08-24T06:35:19.096931+00:00
4
false
# Intuition\nCheck each 2x2 square, if it has 3 \'B\' or 3 \'W\' then it\'s valid and return True immediately.\n\nThere is special cases where there is an already full \'B\'/\'W\' 2x2 square in the grid, so changing any other cell around it still make it valid.\n\n# Approach\nCheck every 2x2 square\nUse a variable to count number of \'B\' and \'W\' cells, \'B\' will increase the count, \'W\' will decrease the count. (You can use 2 variables if you want)\n\n- If `abs(count)` is 2, means there are 3 cells with the same color and 1 cell is different (+1 three times and -1 one time) => It\'s a valid square\n- If `abs(count)` is 4, means all cells have the same color => It\'s also a valid square\n\n\n# Complexity\n- Time complexity:\n$$O(n)$$ - n is the size of the matrix\n\n- Space complexity:\n$$O(1)$$\n\n# Code\n```kotlin []\nclass Solution {\n fun canMakeSquare(grid: Array<CharArray>): Boolean {\n for (i in 0..1) {\n for (j in 0..1) {\n if (isValidSquare(grid, i, j))\n return true\n }\n }\n\n return false\n }\n\n private fun isValidSquare(grid: Array<CharArray>, x: Int, y: Int): Boolean {\n var countBalance = 0\n for (i in y until y + 2) {\n for (j in x until x + 2) {\n grid[i][j].also {\n if (it == \'B\')\n countBalance++\n else\n countBalance--\n }\n }\n }\n\n return abs(countBalance).let { it == 2 || it == 4 }\n }\n}\n```
1
0
['Array', 'Kotlin']
0
make-a-square-with-the-same-color
Check color count in all 2x2 grids
check-color-count-in-all-2x2-grids-by-an-qm3m
Intuition\nWe can check how many possible 2x2 grids can be made of 3x3 grid and then check the the B & W count in each block.\n\n# Approach\n4 such 2x2 grids ca
ankit88
NORMAL
2024-06-22T04:56:21.284021+00:00
2024-06-22T04:56:21.284051+00:00
21
false
# Intuition\nWe can check how many possible 2x2 grids can be made of 3x3 grid and then check the the B & W count in each block.\n\n# Approach\n4 such 2x2 grids can be made. Left-Top, Right-Top, Left-Bottom, Right-Bottom.\n* We iterate over 3x3 grid and just check in each grid how many black boxes are there.(We just need to check as remaining boxes will be of white color.\n* The only way in which we can\'t get all blocks of same color in 2x2 grid is when all 4 grids contain 2 boxes of each color. So if we swap any 1 box, we will still only get 3 boxes of same color, but 1 will still be different.\n\n# Complexity\n- Time complexity: O(1)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public boolean canMakeSquare(char[][] grid) {\n // There can be 4 possible 2x2 blocks\n // We will look at each 2x2 block and see if any of the 2x2 block has 3 or more of same color.\n // in[][] BlackWhiteCount = new int[4][2];\n // Total black colors\n int block1=0,block2=0,block3=0,block4=0;\n for(int i=0;i<3;i++){\n for(int j=0;j<3;j++){\n //Block 1 - left top\n if(grid[i][j] == \'B\'){\n if(i<2 && j<2){\n block1++;\n }\n //Block 2 - right top\n if(i>0 && j<2){\n block2++;\n }\n // Block 3 - left bot\n if(i<2 && j>0){\n block3++;\n }\n // Block 4 - right bot\n if(i>0 && j>0){\n block4++;\n }\n }\n }\n }\n if(block1==2 && block2==2 && block3==2 && block4==2) {\n return false;\n }\n return true;\n \n }\n}\n```
1
0
['Java']
1
make-a-square-with-the-same-color
Fashionable Approach
fashionable-approach-by-baghyawati-senu
Complexity\n- Time complexity: O(1)\n\n- Space complexity: O(1)\n\n# Code\n\nclass Solution:\n def canMakeSquare(self, g: List[List[str]]) -> bool:\n
Baghyawati
NORMAL
2024-05-08T11:42:38.219046+00:00
2024-05-08T11:42:38.219105+00:00
52
false
# Complexity\n- Time complexity: $$O(1)$$\n\n- Space complexity: $$O(1)$$\n\n# Code\n```\nclass Solution:\n def canMakeSquare(self, g: List[List[str]]) -> bool:\n return any((c:=Counter(g[i][j:j+2]+g[i+1][j:j+2]))[\'W\']<2 or c[\'B\']<2 for i in range(2) for j in range(2))\n```
1
0
['Array', 'Python3']
1
make-a-square-with-the-same-color
BEST C++ SOLUTION ✅✅
best-c-solution-by-rishu_raj5938-unv7
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
Rishu_Raj5938
NORMAL
2024-05-03T04:22:00.891277+00:00
2024-05-03T04:22:00.891308+00:00
5
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 bool canMakeSquare(vector<vector<char>>& grid) {\n \n int b = 0;\n int w = 0;\n\n if(grid[1][1] == \'W\') w++;\n else b++;\n\n if(grid[0][0] == \'W\') w++;\n else b++;\n if(grid[0][1] == \'W\') w++;\n else b++;\n if(grid[1][0] == \'W\') w++;\n else b++;\n\n if(b>2 || w>2) return true;\n\n b = 0;\n w = 0;\n\n if(grid[1][1] == \'W\') w++;\n else b++;\n\n if(grid[0][1] == \'W\') w++;\n else b++;\n if(grid[0][2] == \'W\') w++;\n else b++;\n if(grid[1][2] == \'W\') w++;\n else b++;\n \n if(b>2 || w > 2) return true; \n\n w = 0;\n b = 0;\n\n if(grid[1][1] == \'W\') w++;\n else b++;\n\n if(grid[1][2] == \'W\') w++;\n else b++;\n if(grid[2][2] == \'W\') w++;\n else b++;\n if(grid[2][1] == \'W\') w++;\n else b++;\n \n if(b>2 || w > 2) return true; \n\n w = 0;\n b = 0;\n\n if(grid[1][1] == \'W\') w++;\n else b++;\n\n if(grid[2][0] == \'W\') w++;\n else b++;\n if(grid[1][0] == \'W\') w++;\n else b++;\n if(grid[2][1] == \'W\') w++;\n else b++;\n \n if(b>2 || w > 2) return true; \n\n return false;\n } \n};\n```
1
0
['C++']
0
make-a-square-with-the-same-color
Simple and intuitive thought. Time Complexity O(N) and Space Complexity O(1)
simple-and-intuitive-thought-time-comple-zuwo
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
ankurjeesingh310
NORMAL
2024-04-30T19:57:18.692083+00:00
2024-04-30T19:57:18.692114+00:00
266
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public boolean canMakeSquare(char[][] grid) {\n int white = 0;\n int black = 0;\n for(int i = 0; i <= 1; i++){\n if(grid[i][0] == \'W\') white++;\n else black++;\n if(grid[i][1] == \'W\') white++;\n else black++;\n }\n if(black >= 3 || white >= 3){\n return true;\n }\n white = 0; black = 0;\n for(int i = 0; i <= 1; i++){\n if(grid[i][1] == \'W\') white++;\n else black++;\n if(grid[i][2] == \'W\') white++;\n else black++;\n } \n if(black >= 3 || white >= 3){\n return true;\n }\n white = 0; black = 0;\n for(int i = 1; i <= 2; i++){\n if(grid[i][0] == \'W\') white++;\n else black++;\n if(grid[i][1] == \'W\') white++;\n else black++;\n }\n if(black >= 3 || white >= 3){\n return true;\n }\n white = 0; black = 0;\n for(int i = 1; i <= 2; i++){\n if(grid[i][1] == \'W\') white++;\n else black++;\n if(grid[i][2] == \'W\') white++;\n else black++;\n } \n if(black >= 3 || white >= 3){\n return true;\n } \n return false; \n }\n}\n```
1
0
['Java']
0
make-a-square-with-the-same-color
Check Four Squares - Fastest way ( 39 ms )
check-four-squares-fastest-way-39-ms-by-e61h7
javascript\nvar canMakeSquare = function(grid) {\n if (checkSquare(0, 0) >= 3) return true\n if (checkSquare(1, 0) >= 3) return true\n if (checkSquare(
zemamba
NORMAL
2024-04-29T14:46:53.140990+00:00
2024-04-29T14:46:53.141015+00:00
62
false
```javascript\nvar canMakeSquare = function(grid) {\n if (checkSquare(0, 0) >= 3) return true\n if (checkSquare(1, 0) >= 3) return true\n if (checkSquare(0, 1) >= 3) return true\n if (checkSquare(1, 1) >= 3) return true\n return false\n\n function checkSquare(a, b) {\n black = 0, white = 0\n grid[a+0][b+0] == \'B\' ? black ++ : white ++\n grid[a+1][b+0] == \'B\' ? black ++ : white ++\n grid[a+0][b+1] == \'B\' ? black ++ : white ++\n grid[a+1][b+1] == \'B\' ? black ++ : white ++\n return Math.max(black, white)\n }\n};\n```
1
0
['JavaScript']
0
make-a-square-with-the-same-color
Beat 100% easy condition based solution
beat-100-easy-condition-based-solution-b-qyrs
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
Rsharma_09
NORMAL
2024-04-28T14:20:05.906343+00:00
2024-04-28T14:20:05.906430+00:00
161
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:O(1)\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 bool canMakeSquare(vector<vector<char>>& grid) {\n int b=0;\n int w=0;\n \n for(int i=0;i<=1;i++){\n for(int j=0;j<=1;j++){\n if(grid[i][j]==\'W\'){\n w++;\n }\n else{\n b++;\n }\n }\n }\n if(b>=3 || w>=3){\n return true;\n }\n b=0;\n w=0;\n for(int i=0;i<=1;i++){\n for(int j=1;j<=2;j++){\n if(grid[i][j]==\'W\'){\n w++;\n }\n else{\n b++;\n }\n }\n }\n if(b>=3 || w>=3){\n return true;\n }\n b=0;\n w=0;\n \n for(int i=1;i<=2;i++){\n for(int j=0;j<=1;j++){\n if(grid[i][j]==\'W\'){\n w++;\n }\n else{\n b++;\n }\n }\n }\n if(b>=3 || w>=3){\n return true;\n }\n \n b=0;\n w=0;\n \n for(int i=1;i<=2;i++){\n for(int j=1;j<=2;j++){\n if(grid[i][j]==\'W\'){\n w++;\n }\n else{\n b++;\n }\n }\n }\n if(b>=3 || w>=3){\n return true;\n }\n \n return false;\n \n \n }\n};\n```
1
0
['Matrix', 'C++']
0
make-a-square-with-the-same-color
Simple Python solution
simple-python-solution-by-antarab-o57q
\nclass Solution:\n def canMakeSquare(self, grid: List[List[str]]) -> bool:\n import numpy as np\n matrix = np.array(grid)\n for i in ra
antarab
NORMAL
2024-04-27T21:12:56.930633+00:00
2024-04-27T21:12:56.930677+00:00
370
false
```\nclass Solution:\n def canMakeSquare(self, grid: List[List[str]]) -> bool:\n import numpy as np\n matrix = np.array(grid)\n for i in range(0, len(matrix[0])):\n for j in range(0, len(matrix)):\n if i<2 and j<2:\n res=matrix[i:i+2,j:j+2]\n temp=[]\n for a in res:\n temp.extend(a)\n if temp.count(\'W\')<=1 or temp.count(\'B\')<=1:\n return True\n return False\n```
1
0
['Matrix', 'Python3']
1
make-a-square-with-the-same-color
[Python] check 4 squares
python-check-4-squares-by-pbelskiy-nrqn
\nclass Solution:\n def canMakeSquare(self, grid: List[List[str]]) -> bool:\n \n def check(y, x):\n b = w = 0\n \n
pbelskiy
NORMAL
2024-04-27T20:13:21.100639+00:00
2024-04-27T20:13:21.100670+00:00
18
false
```\nclass Solution:\n def canMakeSquare(self, grid: List[List[str]]) -> bool:\n \n def check(y, x):\n b = w = 0\n \n for dy, dx in ((x, y), (x + 1, y), (x, y + 1), (x + 1, y +1)):\n if grid[dy][dx] == \'B\':\n b += 1\n else:\n w += 1\n \n return b >= 3 or w >= 3\n\n for y in range(2):\n for x in range(2):\n if check(y, x):\n return True\n \n return False\n```
1
0
['Python']
0
make-a-square-with-the-same-color
Python3 || 1 line Solution
python3-1-line-solution-by-gbaian10-qwdc
\n# Code\npython\nclass Solution:\n def canMakeSquare(self, grid: List[List[str]]) -> bool:\n return any([grid[i][j], grid[i+1][j], grid[i][j+1], grid
gbaian10
NORMAL
2024-04-27T18:41:08.525520+00:00
2024-04-27T18:45:49.361275+00:00
156
false
\n# Code\n```python\nclass Solution:\n def canMakeSquare(self, grid: List[List[str]]) -> bool:\n return any([grid[i][j], grid[i+1][j], grid[i][j+1], grid[i+1][j+1]].count("B") != 2 for i in range(2) for j in range(2))\n \n```
1
0
['Python3']
0
make-a-square-with-the-same-color
|Brute Force || General Solution || C++
brute-force-general-solution-c-by-sujalg-85ya
\n\n# Code\n\n\nclass Solution {\npublic:\n bool hasValidSquare(vector<vector<char>>& grid) {\n for (int i = 0; i < 2; ++i) {\n for (int j
sujalgupta09
NORMAL
2024-04-27T18:39:15.216490+00:00
2024-04-27T18:39:15.216518+00:00
112
false
\n\n# Code\n```\n\nclass Solution {\npublic:\n bool hasValidSquare(vector<vector<char>>& grid) {\n for (int i = 0; i < 2; ++i) {\n for (int j = 0; j < 2; ++j) {\n if (grid[i][j] == grid[i+1][j] && grid[i][j] == grid[i][j+1] && grid[i][j] == grid[i+1][j+1]) {\n return true; // Found a valid 2x2 square\n }\n }\n }\n return false; // No valid 2x2 square found\n }\n\n bool canMakeSquare(vector<vector<char>>& grid) {\n // Check if there is already a valid 2x2 square\n if (hasValidSquare(grid)) {\n return true;\n }\n\n // Try changing the color of each cell and check if it creates a valid square\n for (int i = 0; i < 3; ++i) {\n for (int j = 0; j < 3; ++j) {\n char originalColor = grid[i][j];\n grid[i][j] = (originalColor == \'B\') ? \'W\' : \'B\'; // Change color\n if (hasValidSquare(grid)) {\n return true; // Changing color of this cell creates a valid square\n }\n grid[i][j] = originalColor; // Reset color\n }\n }\n\n return false; // No valid square can be created by changing one cell\n }\n};\n```
1
0
['C++']
0
make-a-square-with-the-same-color
Easy Java Solution || 0ms exec time
easy-java-solution-0ms-exec-time-by-kari-uujx
\n\n# Complexity\n- Time complexity:O(1)\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
karishmaagrawal
NORMAL
2024-04-27T17:33:34.790142+00:00
2024-04-27T17:33:34.790160+00:00
97
false
\n\n# Complexity\n- Time complexity:O(1)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public boolean canMakeSquare(char[][] grid) {\n for(int row=0;row<2;row++){\n for(int col=0;col<2;col++){\n int count=0;\n if(grid[row][col]!=grid[row+1][col])\n count++;\n if(grid[row][col]!=grid[row][col+1]) \n count++;\n if(grid[row][col]!=grid[row+1][col+1])\n count++;\n if(count<=1 || count==3) \n return true;\n }\n }\n return false;\n }\n}\n//check right, left and diagonal box to check if they r same otherwise just try to \n```
1
0
['Java']
2
make-a-square-with-the-same-color
C 0ms
c-0ms-by-fredo30400-dkm7
Code\n\nbool canMakeSquare(char** grid, int gridSize, int* gridColSize) {\n for(int i=0;i<2;i++){\n for(int j=0;j<2;j++){\n int cnt = 0;\n
fredo30400
NORMAL
2024-04-27T16:59:25.039297+00:00
2024-04-27T16:59:25.039316+00:00
50
false
# Code\n```\nbool canMakeSquare(char** grid, int gridSize, int* gridColSize) {\n for(int i=0;i<2;i++){\n for(int j=0;j<2;j++){\n int cnt = 0;\n if (grid[j][i]==\'W\'){cnt++;}\n if (grid[j+1][i]==\'W\'){cnt++;}\n if (grid[j+1][i+1]==\'W\'){cnt++;}\n if (grid[j][i+1]==\'W\'){cnt++;}\n if (cnt!=2){return true;}\n }\n }\n return false;\n}\n```
1
0
['C']
1
make-a-square-with-the-same-color
📌📌✅ Beats 100.00% of users with Java💥💥
beats-10000-of-users-with-java-by-abinay-sizs
Brute Force Approach\n\n\n\n# Code\n\nclass Solution {\n public boolean canMakeSquare(char[][] grid) {\n int w=0,i,j,r=grid.length,c=grid[0].length;\n
Abinayaprakash
NORMAL
2024-04-27T16:20:52.494387+00:00
2024-04-27T16:20:52.494416+00:00
19
false
# Brute Force Approach\n\n![upvote.PNG](https://assets.leetcode.com/users/images/bb3b70f6-4cd3-4183-817b-156398661aeb_1714234847.4938195.png)\n\n# Code\n```\nclass Solution {\n public boolean canMakeSquare(char[][] grid) {\n int w=0,i,j,r=grid.length,c=grid[0].length;\n int b=0;\n for(i=0;i<=1;i++){\n for(j=0;j<=1;j++){\n \n if(grid[i][j]==\'W\'){\n w++;\n }else{\n b++;\n }\n \n if(grid[i][j+1]==\'W\'){\n w++;;\n \n }else{\n b++;\n }\n if(grid[i+1][j]==\'W\'){\n w++;\n }else{\n b++;\n }\n if(grid[i+1][j+1]==\'W\'){\n w++;\n }else{\n b++;\n }\n\n if(w==4 ||((b==1) && (w==3) ) || b==4 ||((w==1) &&(b==3))){\n return true;\n }\n w=0;\n b=0;\n \n }\n \n }\n return false;\n \n \n \n }\n}\n```
1
0
['Java']
0
make-a-square-with-the-same-color
[C++] Simple Check on 4 Sub-Squares, 6ms, 19.4MB
c-simple-check-on-4-sub-squares-6ms-194m-xfrv
This problem is rather easy to pin down to a few base cases - basically we want that either the first, second, third or fourth possible inner square have an amo
Ajna2
NORMAL
2024-04-27T16:19:16.306590+00:00
2024-04-28T19:24:55.137373+00:00
28
false
This problem is rather easy to pin down to a few base cases - basically we want that either the first, second, third or fourth possible inner square have an amount of a specific `!= 2`, since that is the only case in which we cannot achieve a `4` changing AT MOST one other element.\n\nWe can check that rather brute-forcey:\n\n# Complexity\n- Time complexity: $$O(1)$$\n- Space complexity: $$O(1)$$\n\n# Code\n```cpp\nclass Solution {\npublic:\n bool canMakeSquare(vector<vector<char>>& grid) {\n bool first = (grid[0][0] == \'W\') + (grid[0][1] == \'W\') + (grid[1][0] == \'W\') + (grid[1][1] == \'W\') != 2;\n bool second = (grid[0][1] == \'W\') + (grid[0][2] == \'W\') + (grid[1][1] == \'W\') + (grid[1][2] == \'W\') != 2;\n bool third = (grid[1][0] == \'W\') + (grid[1][1] == \'W\') + (grid[2][0] == \'W\') + (grid[2][1] == \'W\') != 2;\n bool fourth = (grid[1][1] == \'W\') + (grid[1][2] == \'W\') + (grid[2][1] == \'W\') + (grid[2][2] == \'W\') != 2;\n return first || second || third || fourth;\n }\n};\n```\n\nOther solutions basically boil down to finding if either letter would basically own a major vertical or horizontal line in the middle (where the rest is of the other letter) or if we have a situation where a letter owns only both diagonals like here:\n\n```cpp\nWRW\nRWR\nWRW\n//or\nRWR\nWRW\nRWR\n```\nBut they are still unnecessarily complicated.\n\nWe can make our solution even more efficient (albeit at the cost of possible lesser readability), by leveraging the lazy evaluation of the OR operator:\n\n# Complexity\n- Time complexity: $$O(1)$$\n- Space complexity: $$O(1)$$\n\n# Code\n```cpp\nclass Solution {\npublic:\n bool canMakeSquare(vector<vector<char>>& grid) {\n return (grid[0][0] == \'W\') + (grid[0][1] == \'W\') + (grid[1][0] == \'W\') + (grid[1][1] == \'W\') != 2 ||\n (grid[0][1] == \'W\') + (grid[0][2] == \'W\') + (grid[1][1] == \'W\') + (grid[1][2] == \'W\') != 2 ||\n (grid[1][0] == \'W\') + (grid[1][1] == \'W\') + (grid[2][0] == \'W\') + (grid[2][1] == \'W\') != 2 ||\n (grid[1][1] == \'W\') + (grid[1][2] == \'W\') + (grid[2][1] == \'W\') + (grid[2][2] == \'W\') != 2;\n }\n};\n```
1
0
['C++']
0
make-a-square-with-the-same-color
[C++][Time & Space = O(1)][Detailed Array Directional Solution]
ctime-space-o1detailed-array-directional-btwd
Intuition\n\n- Think about currentCell as one corner of square (2 X 2)\n- Consider all possible 2 X 2 square can be made from that current cell\n- Now apply log
karnalrohit
NORMAL
2024-04-27T16:10:37.986855+00:00
2024-04-27T16:10:37.986875+00:00
55
false
# Intuition\n\n- Think about currentCell as one corner of square (2 X 2)\n- Consider all possible 2 X 2 square can be made from that current cell\n- Now apply logic on all possible square that any square have all value as same or not.\n\n# Approach\n\n- Take currentCell as one cell of square\n- Now from oneCell you need to find all neighbour value [total will be 8 if it is center of 3 X 3 Grid]\n - If neighbour cell present keep the same value else assign some dummy value\n - All possible neighbour can be for currentCell -> TopLeft, Top, TopRight, Left, Right, B0ttomLeft, Bottom, BottomRight\n\n- Now you have all neighbour value, now you need to validate any of four square(2 x 2) can be made from current cell have same value ?\n - Square 1 -> TopLeft, Top, Left, Current Cell\n - Square 2 -> Top, CurrentCell, TopRight, Right\n - Square 3 -> left, currentCell, BottomLeft, Bottom\n - Square 4 -> currentCell, right, Bottom, BottomRight\n\n- So check if any square exist with current cell value as \'B\' or else value as \'W\'. (given that we can flip value in question). if exist then return true else iterate further.\n\n# Complexity\n- Time complexity:\nO(1)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution {\npublic:\nbool canMake(vector<vector<char>>& grid, int row, int col){\n char topLeft = (row > 0 && col > 0) ? grid[row-1][col-1] : \'P\';\n char top = (row > 0) ? grid[row-1][col] : \'Q\';\n char topRight = (row > 0 && col < 2) ? grid[row-1][col+1] : \'R\';\n char left = (col > 0) ? grid[row][col-1] : \'S\';\n char right = (col < 2) ? grid[row][col+1] : \'T\';\n char bottomLeft = (row < 2 && col > 0) ? grid[row+1][col-1] : \'U\';\n char bottom = (row < 2) ? grid[row+1][col] : \'V\';\n char bottomRight = (row < 2 && col < 2) ? grid[row+1][col+1] : \'X\';\n char currentChar = grid[row][col] == \'B\' ? \'W\' : \'B\';\n\n // cout << row <<" " << col<< " "<<topLeft << " " << top << " " << topRight << " " << left << " " << right << " " << bottomLeft << " " << bottom << " " << bottomRight << endl;\n if(topLeft == currentChar && top == currentChar && left ==currentChar){\n return true;\n }\n if(topRight == currentChar && top == currentChar && right == currentChar){\n return true;\n }\n if(bottomLeft == currentChar && bottom == currentChar && left == currentChar){\n return true;\n }\n if(bottomRight == currentChar && bottom == currentChar && right == currentChar){\n return true;\n }\n \n currentChar = grid[row][col];\n if(topLeft == currentChar && top == currentChar && left ==currentChar){\n return true;\n }\n if(topRight == currentChar && top == currentChar && right == currentChar){\n return true;\n }\n if(bottomLeft == currentChar && bottom == currentChar && left == currentChar){\n return true;\n }\n if(bottomRight == currentChar && bottom == currentChar && right == currentChar){\n return true;\n }\n return false;\n}\nbool canMakeSquare(vector<vector<char>>& grid) {\n \n\n for(int row = 0; row<3; row++){\n for(int col = 0; col < 3; col++){\n char currenChar = grid[row][col];\n if(canMake(grid, row, col)){\n return true;\n }\n\n }\n }\n return false;\n \n}\n};\n```
1
1
['C++']
0
make-a-square-with-the-same-color
✅Beats 100.00% 🔥 || Java || C++ || C# || Easy Explanation || Beginner Friendly🔥🔥🔥
beats-10000-java-c-c-easy-explanation-be-pgsn
\n# Intuition\nThe problem aims to determine whether it is possible to form a square using the given grid of characters. A square can be formed if there exists
Sayan98
NORMAL
2024-04-27T16:07:29.375701+00:00
2024-04-27T16:14:48.534470+00:00
76
false
![image.png](https://assets.leetcode.com/users/images/6574a62e-069d-48c9-91d8-58ea8ad162d6_1714234014.0509677.png)\n# Intuition\nThe problem aims to determine whether it is possible to form a square using the given grid of characters. A square can be formed if there exists a 2x2 subgrid in the given grid where all the characters are the same.\n\n# Approach\nThe approach is to iterate through the **grid** and check for each 2x2 **subgrid** if all the characters in that **subgrid** are the same. If such a **subgrid** is found, the function returns **true**, indicating that a square can be formed. If no such subgrid is found after iterating through the entire grid, the function returns **false**.\n\n# Complexity\n- Time complexity: **O(mn)**\nwhere m and n are the dimensions of the input grid.\n\n- Space complexity: **O(1)**\nUses only a constant amount of extra space to store temporary variables during the iteration process.\n\n```Java []\nclass Solution {\n public boolean canMakeSquare(char[][] grid) {\n for (var i = 0; i < grid.length - 1; i++)\n for (var j = 0; j < grid[0].length - 1; j++)\n if( (grid[i][j] == grid[i + 1][j] && grid[i][j] == grid[i][j + 1]) ||\n (grid[i][j] == grid[i + 1][j + 1] && grid[i][j] == grid[i][j + 1]) ||\n (grid[i][j] == grid[i + 1][j] && grid[i][j] == grid[i + 1][j + 1]) ||\n (grid[i][j + 1] == grid[i + 1][j + 1] && grid[i][j + 1] == grid[i + 1][j]))\n return true; \n return false;\n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n bool canMakeSquare(vector<vector<char>>& grid) {\n for (int i = 0; i < grid.size() - 1; i++)\n for (int j = 0; j < grid[0].size() - 1; j++)\n if( (grid[i][j] == grid[i + 1][j] && grid[i][j] == grid[i][j + 1]) ||\n (grid[i][j] == grid[i + 1][j + 1] && grid[i][j] == grid[i][j + 1]) ||\n (grid[i][j] == grid[i + 1][j] && grid[i][j] == grid[i + 1][j + 1]) ||\n (grid[i][j + 1] == grid[i + 1][j + 1] && grid[i][j + 1] == grid[i + 1][j]))\n return true; \n return false;\n }\n};\n```\n```C# []\npublic class Solution {\n public bool CanMakeSquare(char[][] grid) {\n \n for (var i = 0; i < grid.Length - 1; i++)\n for (var j = 0; j < grid[0].Length - 1; j++)\n if( (grid[i][j] == grid[i + 1][j] && grid[i][j] == grid[i][j + 1]) ||\n (grid[i][j] == grid[i + 1][j + 1] && grid[i][j] == grid[i][j + 1]) ||\n (grid[i][j] == grid[i + 1][j] && grid[i][j] == grid[i + 1][j + 1]) ||\n (grid[i][j + 1] == grid[i + 1][j + 1] && grid[i][j + 1] == grid[i + 1][j]))\n return true; \n return false;\n }\n}\n```\n![image.png](https://assets.leetcode.com/users/images/6477b249-5d63-4702-9a28-9eb847c82dab_1714234028.8381793.png)\n
1
0
['Math', 'C++', 'Java', 'C#']
0
make-a-square-with-the-same-color
Java Clean Solution
java-clean-solution-by-shree_govind_jee-f49k
Complexity\n- Time complexity:O(2*2)\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# Co
Shree_Govind_Jee
NORMAL
2024-04-27T16:07:05.668913+00:00
2024-04-27T16:07:05.668948+00:00
250
false
# Complexity\n- Time complexity:$$O(2*2)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:$$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public boolean canMakeSquare(char[][] grid) {\n int black=0, white=0;\n for(int i=0; i<=1; i++){\n for(int j=0; j<=1; j++){\n if(grid[i][j]==\'B\'){\n black++;\n }else{\n white++;\n }\n \n if(grid[i+1][j]==\'B\')black++;\n else white++;\n \n if(grid[i+1][j+1]==\'B\')black++;\n else white++;\n \n if(grid[i][j+1]==\'B\')black++;\n else white++;\n \n// Result case\n if(black==4||white==4||(black==1&&white==3)||(black==3&&white==1)){\n return true;\n }\n// reset the case for next round\n black=0;\n white=0;\n }\n }\n return false;\n }\n}\n```
1
0
['Array', 'Math', 'Matrix', 'Java']
0
make-a-square-with-the-same-color
BEAT 100% with JAVA
beat-100-with-java-by-hoang_soict-lcm1
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
hoang_soict
NORMAL
2024-04-27T16:01:44.574632+00:00
2024-04-27T16:01:44.574661+00:00
186
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```\npublic class Solution {\n public static boolean canMakeSquare(char[][] grid) {\n for (int i = 0; i <= 1; i++) {\n for (int j = 0; j <= 1; j++) {\n if (check(grid, i, j)) {\n return true;\n }\n }\n }\n return false;\n }\n\n private static boolean check(char[][] grid, int row, int col) {\n int white = 0, black = 0;\n for (int i = row; i < row + 2; i++) {\n for (int j = col; j < col + 2; j++) {\n if (grid[i][j] == \'W\') {\n white++;\n } else if (grid[i][j] == \'B\') {\n black++;\n }\n }\n }\n return (white == 4 || black == 4) || (white == 1 && black == 3) || (white == 3 && black == 1);\n }\n}\n```
1
0
['Java']
0
make-a-square-with-the-same-color
Simple C++ code, no hardcoding.
simple-c-code-no-hardcoding-by-coolpeng0-dzgg
IntuitionI saw that as long all of the rows or all of the columns have alternating cells, then you cannot make a 2x2 matching area. No matter whether they start
coolpeng0
NORMAL
2025-04-08T00:45:43.942141+00:00
2025-04-08T00:45:43.942141+00:00
4
false
# Intuition I saw that as long all of the rows or all of the columns have alternating cells, then you cannot make a 2x2 matching area. No matter whether they start with white or black, there are 2 white cells and 2 black cells in each 2x2 area when the cells are alternating in each line. I'm pretty sure this solution is correct when the matrix is larger than 3x3 too. # Approach I used two loops, one for the rows and one for the columns. Each of them will complete (i == 6 or j == 6) if the cells are not alternating, i.e. if all of the cells minus the last row or column does not have a matching cell in front of it. You could probably optimize this by returning false early when one of the loops finishes completely. # Complexity - Time complexity: *O(N)*, where N is the number of cells in the matrix. In the worse case, the whole matrix will be traversed twice. If the matrix size if fixed to 3x3 cells, then it will be *O(1)* because each check will only go through 6 iterations for each loop, like below. - Space complexity: *O(1)*. No extra space is used. # Code ```cpp [] class Solution { public: bool canMakeSquare(vector<vector<char>>& grid) { int i, j; for (i = 0; i < 6 && grid[i / 3][i % 3] != grid[i / 3 + 1][i % 3]; i++); for (j = 0; j < 6 && grid[j % 3][j / 3] != grid[j % 3][j / 3 + 1]; j++); return i != 6 && j != 6; } }; ```
0
0
['C++']
1
make-a-square-with-the-same-color
Simple Swift Solution
simple-swift-solution-by-felisviridis-2h2k
Code
Felisviridis
NORMAL
2025-04-03T08:01:50.051312+00:00
2025-04-03T08:01:50.051312+00:00
1
false
![Screenshot 2025-04-03 at 11.00.26 AM.png](https://assets.leetcode.com/users/images/14b7e63e-5552-4b64-83b5-8dbc4e7e5229_1743667267.2295299.png) # Code ```swift [] class Solution { func canMakeSquare(_ grid: [[Character]]) -> Bool { for a in 0...1 { for b in 0...1 { var fill = 0 for i in 0...1 { for j in 0...1 { fill += grid[a + i][b + j] == "B" ? 0 : 1 } } if fill != 2 { return true } } } return false } } ```
0
0
['Array', 'Swift', 'Matrix']
0
make-a-square-with-the-same-color
CPP beats 100%
cpp-beats-100-by-hareeshghk-2iuf
IntuitionWe just need to check 4 squares. Luckily start position points for squares are same as direction we need to go from starting point. So used same direti
hareeshghk
NORMAL
2025-03-29T19:29:16.477711+00:00
2025-03-29T19:29:16.477711+00:00
2
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> We just need to check 4 squares. Luckily start position points for squares are same as direction we need to go from starting point. So used same diretionb 2D array for both. # Approach <!-- Describe your approach to solving the problem. --> In each square calculate whites. whites can 0,1,2,3,4. Problem is only when whites 2. remaining 4 cases you can change atmost one colour and make it a square of same colours. you just need to find one square where whites is not equals 2. In a 2x2 sqare whites 0 - all are already black whites 1 - change this one white to black then all are black whites 2 - NOTHING CAN BE DONE whites 3 - change 4th black to white then all are white whites 4 - all are already white # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> O(1) - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> O(1) # Code ```cpp [] class Solution { public: bool canMakeSquare(vector<vector<char>>& grid) { vector<vector<int>> dirs {{0,0}, {0,1}, {1,0}, {1,1}}; for (auto pos : dirs) { int numWhites = 0; for (auto dir : dirs) { if (grid[pos[0]+dir[0]][pos[1]+dir[1]] == 'W') { numWhites++; } } if (numWhites != 2) { return true; } } return false; } }; ```
0
0
['C++']
0
make-a-square-with-the-same-color
Runtime 100% beats, memory 100% beats solution in Kotlin
runtime-100-beats-memory-100-beats-solut-zc6u
IntuitionI found four possible square and solved the problemComplexity Time complexity: O(1) Space complexity: O(1) Code
ahmadali_ok
NORMAL
2025-03-27T06:50:37.569965+00:00
2025-03-27T06:50:37.569965+00:00
1
false
# Intuition I found four possible square and solved the problem # Complexity - Time complexity: O(1) - Space complexity: O(1) # Code ```kotlin [] class Solution { fun canMakeSquare(grid: Array<CharArray>): Boolean { var bHelper = 0 if (grid[0][0] == 'B') bHelper++ if (grid[0][1] == 'B') bHelper++ if (grid[1][0] == 'B') bHelper++ if (grid[1][1] == 'B') bHelper++ if (bHelper != 2) return true bHelper = 0 if (grid[0][1] == 'B') bHelper++ if (grid[0][2] == 'B') bHelper++ if (grid[1][1] == 'B') bHelper++ if (grid[1][2] == 'B') bHelper++ if (bHelper != 2) return true bHelper = 0 if (grid[1][0] == 'B') bHelper++ if (grid[1][1] == 'B') bHelper++ if (grid[2][0] == 'B') bHelper++ if (grid[2][1] == 'B') bHelper++ if (bHelper != 2) return true bHelper = 0 if (grid[1][1] == 'B') bHelper++ if (grid[1][2] == 'B') bHelper++ if (grid[2][1] == 'B') bHelper++ if (grid[2][2] == 'B') bHelper++ if (bHelper != 2) return true return false } } ```
0
0
['Kotlin']
0
make-a-square-with-the-same-color
Java; math approach; 0ms beats 100%; 41.4 MB beats 97%
java-math-approach-0ms-beats-100-414-mb-6y8x9
IntuitionThe first thing I thought was that I must have only 1 element of a color on a 2x2 "subsquare" (it implies we will have 3 elements of the other). If the
osmarcf
NORMAL
2025-03-19T23:45:54.537274+00:00
2025-03-19T23:45:54.537274+00:00
4
false
# Intuition The first thing I thought was that I must have only 1 element of a color on a 2x2 "subsquare" (it implies we will have 3 elements of the other). If there's only 1, then I can already return "true". If not, I have to check the other subsquares. For this specific problem, we have only 4 subsquares. Basically, we have to count each 4 elements (on each subsquare) if there's 0 or 1 of one color. # Approach So, how to check if each subsquare has only 1 element of one color? In my first tries, I had a character counting W's and B's. But then I thought on a boolean approach. What if W's were 0 (false) and B's were 1? Then I'd have a problem to count them! Anyway, going back to a counting approach W's and B's, We need to just check if we have: 0, 1, 3 or 4 of an element. Just a brief explanation about those values: - 0 and 4: if we already have an subsquare complete: 0 would mean we have 4 W's (and 0 B's); 4 would mean we have 4 B's (and 0 W's); - 1 and 3: we have 1 element, so it can be switched. If it's 1, then we have 1 B and 3 W's; otherwise, if it's a 3, we have 1 W and 3 B's; - ...and what about 2? Then we can't switch only 1 element to reach the objective. So, I could just turn W to 0 and B to 1 and sum. But then I thought about a way to ease the count: leveraging char type, we can sum directly the grid items! Here is the plot twist: decrease 'B' from each grid item, then we will have 0 ('B' - 'B' = 0) or 21 ('W' - 'B' = 21) instead a 1. So our grid would be filled up with 0's or 21's! Then, we sum subsquares, and later just check against 0, 1, 3 and 4 (times 21). If we don't return on that check (the for loop checking the count), we didn't find any subsquare possible to change, then we can return false. I hope you liked this! If you have any suggestions I'd like to hear it! # Complexity - Time complexity: O(n²) - Space complexity: O(n) # Code ```java [] class Solution { public boolean canMakeSquare(char[][] grid) { for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { grid[i][j] -= 'B'; } } int[] subsquares = { grid[0][0] + grid[0][1] + grid[1][0] + grid[1][1], // Subsquare 0, 0 to 1, 1 grid[0][1] + grid[0][2] + grid[1][1] + grid[1][2], // Subsquare 0, 1 to 1, 2 grid[1][0] + grid[1][1] + grid[2][0] + grid[2][1], // Subsquare 1, 0 to 2, 1 grid[1][1] + grid[1][2] + grid[2][1] + grid[2][2] // Subsquare 1, 1 to 2, 2 }; for (int count : subsquares) { if (count == 0 || count == 21 || count == 63 || count == 84) { return true; } } return false; } } ```
0
0
['Java']
0
make-a-square-with-the-same-color
Easy to understand solution in Java. Beats 100 %
easy-to-understand-solution-in-java-beat-lglk
Complexity Time complexity: O(1) Space complexity: O(1) Code
Khamdam
NORMAL
2025-03-16T06:18:31.115225+00:00
2025-03-16T06:18:31.115225+00:00
6
false
# Complexity - Time complexity: O(1) - Space complexity: O(1) # Code ```java [] class Solution { public boolean canMakeSquare(char[][] grid) { return isValid(grid, 0, 0) || isValid(grid, 0, 1) || isValid(grid, 1, 0) || isValid(grid, 1, 1); } private boolean isValid(char[][] grid, int x, int y) { int whiteCount = 0; int blackCount = 0; char[] colours = new char[] { grid[x][y], grid[x][y + 1], grid[x + 1][y], grid[x + 1][y + 1] }; for (char c : colours) { if (c == 'W') { whiteCount++; } else { blackCount++; } } return whiteCount >= 3 || blackCount >= 3; } } ```
0
0
['Array', 'Matrix', 'Java']
0
make-a-square-with-the-same-color
Simple Counting
simple-counting-by-beken-waf6
IntuitionSimple CountingApproachSimple CountingComplexity Time complexity:O(1) Space complexity:O(1) Code
beken
NORMAL
2025-02-22T15:36:04.112398+00:00
2025-02-22T15:36:04.112398+00:00
7
false
# Intuition Simple Counting # Approach Simple Counting # Complexity - Time complexity: O(1) - Space complexity: O(1) # Code ```java [] class Solution { public boolean canMakeSquare(char[][] grid) { for(int y = 0; y < grid.length-1; y++) { for(int x = 0; x < grid[0].length-1; x++) { if(isSquare(grid,y,x)) return true; } } return false; } boolean isSquare(char[][] grid, int y, int x){ /* E, S & SE need to be of max 1 color diff. */ char colorCurrent = grid[y][x]; int otherColorCount = 0; if(grid[y][x+1] != colorCurrent) otherColorCount++; if(grid[y+1][x] != colorCurrent) otherColorCount++; if(grid[y+1][x+1] != colorCurrent) otherColorCount++; return (otherColorCount <=1 || otherColorCount == 3); } } ```
0
0
['Array', 'Matrix', 'Java']
0
make-a-square-with-the-same-color
Brute Force Solution, T = O(1) and S = O(1)
brute-force-solution-t-o1-and-s-o1-by-pu-iej8
IntuitionIf the no. of 'B' or 'W' is greater than 2 in any of the square then return true.ApproachIn all the squares we compare if the no. of B or W is greater
PuruMohite
NORMAL
2025-02-20T16:38:08.154172+00:00
2025-02-20T16:38:08.154172+00:00
3
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> If the no. of 'B' or 'W' is greater than 2 in any of the square then return true. # Approach <!-- Describe your approach to solving the problem. --> In all the squares we compare if the no. of B or W is greater than 2. If for a square it is true than we return true, else after checking all the squares we return false. # Algorithm 1. Visit each element. 2. For an element check if its top, left and top-left elements exist. 2.1 If it does then check if at least two elements are equal to the current visited element OR None of the element are equal to it then return true.(Note: If any of the two conditions are satisfied it implies that the square has 3 same colors) 3. If you have visited all the elements and have not returned true then return false. # Complexity - Time complexity: $$O(1)$$ <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: $$O(1)$$ <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] class Solution { public: bool canMakeSquare(vector<vector<char>>& grid) { //Brute Force solution //T=O(1) and S=O(1) for(int i=0; i<3; i++){ for(int j=0; j<3; j++){ if(i && j){ int count1 = 0; int count2 = 0; if(grid[i][j] == grid[i-1][j-1]) count1++; else count2++; if(grid[i][j] == grid[i-1][j]) count1++; else count2++; if(grid[i][j] == grid[i][j-1]) count1++; else count2++; if(count1 >= 2 || count2>2) return true; } } } return false; } }; ```
0
0
['C++']
0
make-a-square-with-the-same-color
Simple Java solution -> 0 ms Beats 100.00%
simple-java-solution-0-ms-beats-10000-by-jdkf
IntuitionApproachComplexity Time complexity: O(1) Space complexity: O(1) Code
DevelopersUsername
NORMAL
2025-02-10T08:10:18.195107+00:00
2025-02-10T08:10:18.195107+00:00
3
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: O(1) - Space complexity: O(1) # Code ```java [] class Solution { public boolean canMakeSquare(char[][] grid) { int center = getColor(grid, 1, 1); int lu = center + getColor(grid, 0, 0) + getColor(grid, 0, 1) + getColor(grid, 1, 0); int ru = center + getColor(grid, 0, 1) + getColor(grid, 0, 2) + getColor(grid, 1, 2); int ld = center + getColor(grid, 1, 0) + getColor(grid, 2, 0) + getColor(grid, 2, 1); int rd = center + getColor(grid, 2, 1) + getColor(grid, 1, 2) + getColor(grid, 2, 2); return canMake(lu) || canMake(ru) || canMake(ld) || canMake(rd); } private static int getColor(char[][] grid, int row, int col) { return grid[row][col] == 'W' ? 1 : 0; } private static boolean canMake(int count) { return count >= 3 || count == 0 || count == 1; } } ```
0
0
['Java']
0
make-a-square-with-the-same-color
Java solution
java-solution-by-java_developer-6u7p
null
Java_Developer
NORMAL
2025-02-02T21:36:40.274630+00:00
2025-02-02T21:36:40.274630+00:00
10
false
```java [] class Solution { public boolean canMakeSquare(char[][] grid) { for (int r = 0; r < 2; r++) { for (int c = 0; c < 2; c++) { int whiteTiles = 0; whiteTiles += grid[r][c] == 'W' ? 1 : 0; whiteTiles += grid[r][c + 1] == 'W' ? 1 : 0; whiteTiles += grid[r + 1][c] == 'W' ? 1 : 0; whiteTiles += grid[r + 1][c + 1] == 'W' ? 1 : 0; if (whiteTiles == 2) { continue; } return true; } } return false; } } ```
0
0
['Java']
0
make-a-square-with-the-same-color
Java&JS&TS Solution (JW)
javajsts-solution-jw-by-specter01wj-awhw
IntuitionApproachComplexity Time complexity: Space complexity: Code
specter01wj
NORMAL
2025-01-28T07:19:58.492614+00:00
2025-01-28T07:19:58.492614+00:00
6
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```java [] public boolean canMakeSquare(char[][] grid) { // Loop through all possible 2x2 squares in the 3x3 grid for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { // Count the occurrences of 'B' and 'W' in the current 2x2 square int countB = 0; int countW = 0; for (int x = i; x < i + 2; x++) { for (int y = j; y < j + 2; y++) { if (grid[x][y] == 'B') { countB++; } else { countW++; } } } // Check if the current 2x2 square can be made uniform by changing at most one cell if (countB >= 3 || countW >= 3) { return true; } } } return false; } ``` ```javascript [] var canMakeSquare = function(grid) { // Loop through all possible 2x2 squares in the 3x3 grid for (let i = 0; i < 2; i++) { for (let j = 0; j < 2; j++) { // Count the occurrences of 'B' and 'W' in the current 2x2 square let countB = 0; let countW = 0; for (let x = i; x < i + 2; x++) { for (let y = j; y < j + 2; y++) { if (grid[x][y] === 'B') { countB++; } else { countW++; } } } // Check if the current 2x2 square can be made uniform by changing at most one cell if (countB >= 3 || countW >= 3) { return true; } } } return false; }; ``` ```typescript [] function canMakeSquare(grid: string[][]): boolean { // Loop through all possible 2x2 squares in the 3x3 grid for (let i = 0; i < 2; i++) { for (let j = 0; j < 2; j++) { // Count the occurrences of 'B' and 'W' in the current 2x2 square let countB = 0; let countW = 0; for (let x = i; x < i + 2; x++) { for (let y = j; y < j + 2; y++) { if (grid[x][y] === 'B') { countB++; } else { countW++; } } } // Check if the current 2x2 square can be made uniform by changing at most one cell if (countB >= 3 || countW >= 3) { return true; } } } return false; }; ```
0
0
['Array', 'Matrix', 'Enumeration', 'Java', 'TypeScript', 'JavaScript']
0
make-a-square-with-the-same-color
100% Beat || Rust
100-beat-rust-by-nocabris-3t1k
Intuitionsplit the 3x3 matrix in 4 2x2 matrices and just count if we got more than 3 'W' or less than 2 'W'ApproachComplexityCode
nocabris
NORMAL
2025-01-23T13:35:34.380731+00:00
2025-01-23T13:35:34.380731+00:00
5
false
# Intuition split the 3x3 matrix in 4 2x2 matrices and just count if we got more than 3 'W' or less than 2 'W' # Approach <!-- Describe your approach to solving the problem. --> # Complexity # Code ```rust [] impl Solution { pub fn can_make_square(grid: Vec<Vec<char>>) -> bool { for i in 0..4 { let mut count_w = 0; if grid[i/2][i%2] == 'W' {count_w += 1}; if grid[i/2][(i%2)+1] == 'W' {count_w += 1}; if grid[(i/2)+1][i%2] == 'W' {count_w += 1}; if grid[(i/2)+1][(i%2)+1] == 'W' {count_w += 1}; if(count_w > 2 || count_w < 2) {return true}; } return false; } } ```
0
0
['Rust']
0
make-a-square-with-the-same-color
Solution in C
solution-in-c-by-praveenkesava-rnos
IntuitionApproachComplexity Time complexity: Space complexity: Code
praveenkesava
NORMAL
2025-01-21T09:53:06.216265+00:00
2025-01-21T09:53:06.216265+00:00
4
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```c [] bool canMakeSquare(char** grid, int gridSize, int* gridColSize) { *gridColSize = 3; for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { int w = 0, b = 0; if (grid[i][j] == 'W') w++; else b++; if (grid[i][j + 1] == 'W') w++; else b++; if (grid[i + 1][j] == 'W') w++; else b++; if (grid[i + 1][j + 1] == 'W') w++; else b++; if (w >= 3 || b >= 3) return true; } } return false; } ```
0
0
['C']
0
make-a-square-with-the-same-color
Typescript ✅ 100%
typescript-100-by-kay-79-0fan
Code
Kay-79
NORMAL
2025-01-18T17:41:57.456816+00:00
2025-01-18T17:41:57.456816+00:00
3
false
# Code ```typescript [] function canMakeSquare(grid: string[][]): boolean { for (let i = 0; i < 2; i++) { for (let j = 0; j < 2; j++) { let countW = 0; let countB = 0; grid[i][j] === "B" ? countB++ : countW++; grid[i][j + 1] === "W" ? countW++ : countB++; grid[i + 1][j] === "B" ? countB++ : countW++; grid[i + 1][j + 1] === "W" ? countW++ : countB++; if (countB !== 2) return true; } } return false; } ```
0
0
['TypeScript']
0
make-a-square-with-the-same-color
scala oneliner
scala-oneliner-by-vititov-w75a
null
vititov
NORMAL
2025-01-18T16:08:50.227687+00:00
2025-01-18T16:08:50.227687+00:00
1
false
```scala [] object Solution { def canMakeSquare(grid: Array[Array[Char]]): Boolean = ( for{i <- grid.indices.init; j <- grid.head.indices.init} yield { Iterator(grid(i)(j), grid(i)(j+1), grid(i+1)(j), grid(i+1)(j+1)) .map(_.compare('B').sign).sum} ).filterNot(_ == 2).nonEmpty } ```
0
0
['Scala']
0
make-a-square-with-the-same-color
CPP
cpp-by-algoace_84-dr89
IntuitionApproachComplexity Time complexity: Space complexity: Code
Chandan_84
NORMAL
2025-01-15T17:32:16.457393+00:00
2025-01-15T17:32:16.457393+00:00
2
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] class Solution { public: bool canMakeSquare(vector<vector<char>>& grid) { for(int i=0; i<2; i++){ for(int j=0; j<2; j++){ int cntB = 0, cntW = 0; for(int a = i; a < i+2; a++){ for(int b = j; b < j+2; b++){ if(grid[a][b] == 'W') cntW++; else cntB++; } } if(cntB >= 3 || cntW >= 3) return true; } } return false; } }; ```
0
0
['C++']
0
make-a-square-with-the-same-color
make-a-square-with-the-same-color in c
make-a-square-with-the-same-color-in-c-b-r6wk
IntuitionApproachComplexity Time complexity: Space complexity: Code
Udaya_V
NORMAL
2025-01-15T09:56:48.907320+00:00
2025-01-15T09:56:48.907320+00:00
5
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```c [] bool canMakeSquare(char** grid, int gridSize, int* gridColSize) { *gridColSize = 3; for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { int w = 0, b = 0; if (grid[i][j] == 'W') w++; else b++; if (grid[i][j + 1] == 'W') w++; else b++; if (grid[i + 1][j] == 'W') w++; else b++; if (grid[i + 1][j + 1] == 'W') w++; else b++; if (w >= 3 || b >= 3) return true; } } return false; } ```
0
0
['C']
0
make-a-square-with-the-same-color
Make-a-square-with-the-same-color (In Java)
make-a-square-with-the-same-color-in-jav-83g4
Code
nishanthinimani525
NORMAL
2025-01-12T16:18:55.355338+00:00
2025-01-12T16:18:55.355338+00:00
7
false
# Code ```java [] class Solution { public boolean canMakeSquare(char[][] grid) { for(int i=0;i<2;i++){ for(int j=0;j<2;j++){ int w = 0, b=0; if(grid[i][j] == 'B'){ b++; } else{ w++; } if(grid[i][j+1]=='B'){ b++; } else{ w++; } if(grid[i+1][j]=='B'){ b++; } else{ w++; } if(grid[i+1][j+1]=='B'){ b++; } else{ w++; } if(w>=3 || b>=3){ return true; } } } return false; } } ```
0
0
['Java']
0
make-a-square-with-the-same-color
Make a square with the Same Color - python3 solution
make-a-square-with-the-same-color-python-25a8
IntuitionApproachComplexity Time complexity: Space complexity: Code
ChaithraDee
NORMAL
2025-01-12T15:35:56.338476+00:00
2025-01-12T15:35:56.338476+00:00
7
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> O(1) - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> O(1) # Code ```python3 [] class Solution: def canMakeSquare(self, grid: List[List[str]]) -> bool: for i in range(0, 2): for j in range(0, 2): sub = [ grid[i][j], grid[i][j + 1], grid[i + 1][j], grid[i + 1][j + 1]] print(sub) if sub.count('W') == 3 or sub.count('B') == 3: return True if sub.count('W') == 4 or sub.count('B') == 4: return True return False ```
0
0
['Python3']
0
make-a-square-with-the-same-color
Check Balanced Square probability in Grid Matrix
check-balanced-square-probability-in-gri-hpkw
IntuitionApproachI divided the 3x3 grid into four 2x2 subgrids and checked if any of them already contain all cells of the same color or can be made uniform by
traezeeofor
NORMAL
2025-01-12T09:31:59.098524+00:00
2025-01-12T09:31:59.098524+00:00
2
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach I divided the 3x3 grid into four 2x2 subgrids and checked if any of them already contain all cells of the same color or can be made uniform by changing at most one cell. I checked for conditions where three cells are the same color, and one is different, as well as when all four cells are the same. If any of these conditions hold, I return true; otherwise, I return false. # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```typescript [] function canMakeSquare(grid: string[][]): boolean { const g1 = [grid[0][0], grid[0][1], grid[1][0], grid[1][1]]; const g2 = [grid[0][1], grid[0][2], grid[1][1], grid[1][2]]; const g3 = [grid[1][0], grid[1][1], grid[2][0], grid[2][1]]; const g4 = [grid[1][1], grid[1][2], grid[2][1], grid[2][2]]; const arr = [g1, g2, g3, g4]; if ( arr.some( (ar) => (ar.filter((a) => a === "B").length === 3 && ar.filter((a) => a === "W").length === 1) || (ar.filter((a) => a === "W").length === 3 && ar.filter((a) => a === "B").length === 1) ) ) { return true; } else if ( arr.some( (ar) => ar.filter((a) => a === "B").length === 4 || ar.filter((a) => a === "W").length === 4 ) ) { return true; } else { return false; } }; ```
0
0
['TypeScript']
0
make-a-square-with-the-same-color
Can make the grid larger size(not only 3*3)
can-make-the-grid-larger-sizenot-only-33-54p1
IntuitionApproachComplexity Time complexity: Space complexity: Code
linda2024
NORMAL
2025-01-10T23:03:44.766708+00:00
2025-01-10T23:03:44.766708+00:00
4
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```csharp [] public class Solution { public bool CanMakeSquare(char[][] grid) { int[] dir = new int[]{0, 0, 1, 1, 0}; for(int i = 0; i < 2; i++) { for(int j = 0; j < 2; j++) { int sum = 0; for(int p = 0; p < 4; p++) { int newX = i + dir[p], newY = j + dir[p+1]; sum += (grid[newX][newY] == 'W' ? 1 : 0); } if(sum != 2) return true; } } return false; } } ```
0
0
['C#']
0
make-a-square-with-the-same-color
C++ | Easy to understand
c-easy-to-understand-by-aman786-lbee
Complexity Time complexity: O(1) Space complexity: O(1) Code
Aman786
NORMAL
2025-01-10T18:36:49.500037+00:00
2025-01-10T18:36:49.500037+00:00
1
false
# Complexity - Time complexity: $$O(1)$$ <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: $$O(1)$$ <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] class Solution { public: bool canMakeSquare(vector<vector<char>>& grid) { int n = grid.size(), m=grid[0].size(); for(int i=0; i<grid.size(); i++){ for(int j=0; j<grid[0].size(); j++){ char color = grid[i][j]; int diffCol = 0; if(i+1<n and j+1<m){ if(i+1<n and grid[i+1][j]!=color) diffCol++; if(j+1<m and grid[i][j+1]!=color) diffCol++; if(i+1<n and j+1<m and grid[i+1][j+1]!=color) diffCol++; if(diffCol<=1 or diffCol>=3) return true; } } } return false; } }; ```
0
0
['C++']
0
make-a-square-with-the-same-color
Make a square with same color Solution in C
make-a-square-with-same-color-solution-i-f2dk
IntuitionApproachComplexity Time complexity: O(n) Space complexity: O(1) Code
Darsan20
NORMAL
2025-01-07T17:15:35.541004+00:00
2025-01-07T17:15:35.541004+00:00
5
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: O(n) - Space complexity: O(1) # Code ```c [] bool canMakeSquare(char** grid, int gridSize, int* gridColSize) { *gridColSize = 3; for (int i=0;i<2;i++) { for (int j=0;j<2;j++) { int w=0,b=0; if (grid[i][j] == 'W') w++; else b++; if (grid[i][j+1] == 'W') w++; else b++; if (grid[i+1][j] == 'W') w++; else b++; if (grid[i+1][j+1] == 'W') w++; else b++; if (w>=3 || b>=3) return true; } } return false; } ```
0
0
['C']
0
make-a-square-with-the-same-color
3127. Make a Square with the Same Color
3127-make-a-square-with-the-same-color-b-c31q
IntuitionApproachComplexity Time complexity: Space complexity: Code
G8xd0QPqTy
NORMAL
2025-01-07T07:07:45.405019+00:00
2025-01-07T07:07:45.405019+00:00
4
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```python3 [] class Solution: def canMakeSquare(self, grid: List[List[str]]) -> bool: for i in range(2): # Loop through the first two rows and columns for j in range(2): # Count the number of 'B' and 'W' in the 2x2 block starting at (i, j) colors = [grid[i][j], grid[i][j+1], grid[i+1][j], grid[i+1][j+1]] if colors.count('B') >= 3 or colors.count('W') >= 3: return True return False ```
0
0
['Python3']
0
make-a-square-with-the-same-color
Easy Solution in Java
easy-solution-in-java-by-sathurnithy-zavo
Code
Sathurnithy
NORMAL
2025-01-05T14:00:55.939227+00:00
2025-01-05T14:00:55.939227+00:00
7
false
# Code ```java [] class Solution { public boolean canMakeSquare(char[][] grid) { for(int i=0; i<2; i++){ for(int j=0; j<2; j++){ int gridSumWhite = (grid[i][j] == 'W' ? 1:0) + (grid[i][j+1] == 'W' ? 1:0) + (grid[i+1][j] == 'W' ? 1:0) + (grid[i+1][j+1] == 'W' ? 1:0); if(gridSumWhite >= 3 || gridSumWhite <= 1) return true; } } return false; } } ```
0
0
['Java']
0
make-a-square-with-the-same-color
super easy solution / python / beats 100% ദ്ദി(˵ •̀ ᴗ - ˵ ) ✧
super-easy-solution-python-beats-100-ddi-951s
Code
Orin_M
NORMAL
2025-01-05T10:41:47.022188+00:00
2025-01-05T10:41:47.022188+00:00
2
false
![image.png](https://assets.leetcode.com/users/images/b7d99f47-8527-48e8-9de0-fd97247ed51c_1736073423.4443333.png) # Code ```python [] class Solution(object): def canMakeSquare(self, grid): """ :type grid: List[List[str]] :rtype: bool """ for r in range(2): for c in range(2): # til 2, bcz we don't want it to escape the range # x is str array for a 2 x 2 square where grid[r][c] is in top left corner x = [i for i in grid[r][c]+grid[r][c+1]+grid[r+1][c]+grid[r+1][c+1]] # conditions under which it is possible to create a 2 x 2 square of the same color. if x.count('B') == 3 or x.count('B') == 4 or x.count('W') == 3 or x.count('W') == 4: return True return False ```
0
0
['Python']
0
make-a-square-with-the-same-color
Easy Java Solution 100% beating in time-complexity 🧑‍💻
easy-java-solution-100-beating-in-time-c-r0ro
Intuition Identify Squares: The core idea is to efficiently check for existing squares or potential squares within the grid. Color Dominance: Focus on the major
yuvsingh7650
NORMAL
2025-01-04T12:57:10.363061+00:00
2025-01-04T12:57:10.363061+00:00
5
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> - **Identify Squares**: The core idea is to efficiently check for existing squares or potential squares within the grid. - **Color Dominance**: Focus on the majority color within each 2x2 sub-grid. If a sub-grid has three or four of the same color, it either forms a square or can be easily transformed into one by changing a single color. P.S. By the way, you can simplify this code to make it run in `O(1)` time complexity by writing all the possibilities for this 3x3 matrix using if-else statements, but this code below works for all square-matrices of any order. # Approach <!-- Describe your approach to solving the problem. --> 1. **Iterate through the Grid**: Use nested loops to examine each 2x2 sub-grid within the matrix. 2. **Count Colors**: For each sub-grid, count the occurrences of 'W' (white) and 'B' (black). 3. **Check for Potential Squares**: If the count of either 'W' or 'B' is 3 or 4 within a sub-grid, return `true` as it represents a potential square. # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> $$O(n^2)$$ - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> $$O(1)$$ # Code ```java [] class Solution { public int w(char a){ return (a=='W')?1:0; //returns 1 if character is 'W' } public int b(char a){ return (a=='B')?1:0; //returns 1 if character is 'B' } public boolean canMakeSquare(char[][] grid) { int n = grid.length; //same limits for i and j coz it's a square-matrix (square 2d array) of order 3x3 //limits set to n-1 for i and j, because while checking inside the loop we have to add +1 to both i and j for checking a complete square for(int i = 0; i < n-1; i++){ for(int j = 0; j < n-1; j++){ if(w(grid[i][j]) + w(grid[i][j+1]) + w(grid[i+1][j]) + w(grid[i+1][j+1]) >= 3){//already a square or can change 1 element to 'W' return true; //if the sum is either 3 or 4, then return true, coz 1 element can be changed to 'W' (for 3) or it's already a square (for 4) } if(b(grid[i][j]) + b(grid[i][j+1]) + b(grid[i+1][j]) + b(grid[i+1][j+1]) >= 3){//already a square or can change 1 element to 'B' return true; //if the sum is either 3 or 4, then return true, coz 1 element can be changed to 'B' (for 3) or it's already a square (for 4) //same as for white one } } } return false; //return false if we can't find a square or we can't make it a square by changing one element } } ```
0
0
['Java']
0
make-a-square-with-the-same-color
<<easy c++ solution -beats 100%>>
easy-c-solution-beats-100-by-shaivya2918-n9nm
IntuitionApproachComplexity Time complexity: Space complexity: Code
shaivya291872
NORMAL
2024-12-24T10:19:28.699009+00:00
2024-12-24T10:19:28.699009+00:00
4
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] class Solution { public: bool canMakeSquare(vector<vector<char>>& grid) { if(grid[1][1]=='W') { for(int i=0;i<grid.size()-1;i++){ for(int j=0;j<grid[0].size()-1;j++){ int black =0; if(grid[i][j]=='B') black++; if(grid[i+1][j]=='B') black++; if(grid[i+1][j+1]=='B')black++; if(grid[i][j+1]=='B')black++; if(black <=1 ||black==3)return true; } }} if(grid[1][1]=='B') { for(int i=0;i<grid.size()-1;i++){ for(int j=0;j<grid[0].size()-1;j++){ int black =0; if(grid[i][j]=='W') black++; if(grid[i+1][j]=='W')black++; if(grid[i+1][j+1]=='W')black++; if(grid[i][j+1]=='W')black++; if(black <=1 || black==3)return true; } } } return false; } }; ```
0
0
['C++']
0
make-a-square-with-the-same-color
Easy solution || java || 100% beat
easy-solution-java-100-beat-by-subhash_k-k63f
IntuitionApproachComplexity Time complexity: Space complexity: Code
Subhash_kumar143
NORMAL
2024-12-21T08:28:53.713891+00:00
2024-12-21T08:28:53.713891+00:00
7
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```java [] class Solution { public boolean canMakeSquare(char[][] grid) { for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { // Check the 2x2 submatrix starting at (i, j) int blackCount = 0; int whiteCount = 0; // Count 'B' and 'W' in this submatrix for (int x = i; x < i + 2; x++) { for (int y = j; y < j + 2; y++) { if (grid[x][y] == 'B') blackCount++; else whiteCount++; } } // If at most one cell needs to be changed, return true if (blackCount >= 3 || whiteCount >= 3) return true; } } // If no 2x2 submatrix can be formed, return false return false; } } ```
0
0
['Java']
0
make-a-square-with-the-same-color
Java | Easy Solution | O(1) | 0ms | Beats 100%
java-easy-solution-o1-0ms-beats-100-by-a-uh5t
ApproachDivide the 3x3 grid into 4 possible 2x2 sub-grids: Top-left: (0,0), (0,1), (1,0), (1,1) Top-right: (0,1), (0,2), (1,1), (1,2) Bottom-left: (1,0), (1,1),
arti8190
NORMAL
2024-12-15T10:18:45.806207+00:00
2024-12-15T10:18:45.806207+00:00
8
false
\n# Approach\n\n**Divide the 3x3 grid into 4 possible 2x2 sub-grids:**\n\n* Top-left: (0,0), (0,1), (1,0), (1,1)\n* Top-right: (0,1), (0,2), (1,1), (1,2)\n* Bottom-left: (1,0), (1,1), (2,0), (2,1)\n* Bottom-right: (1,1), (1,2), (2,1), (2,2)\n\n**Check if one of these 2x2 grids can be converted to a single-color grid:**\n\n1. For each 2x2 sub-grid, the function checkGrid(rs, re, cs, ce, grid) counts the number of \'B\' (black) and \'W\' (white) cells.\n2. If all cells are already the same color (b == 0 or w == 0), or if at most one change can make all cells the same (i.e., 3 of one color, 1 of another), then the sub-grid can be converted, and checkGrid returns true.\n\n**Return the result:**\n\n1. If any of the 4 possible sub-grids can be made to have all cells of the same color, the function returns true. Otherwise, it returns false.\n\n# Complexity\n\n## Time complexity:\n* The program checks 4 sub-grids, and each check takes constant time O(1).\n* Total time complexity: O(1).\n\n## Space complexity:\n* O(1)\n\n# Code\n```java []\nclass Solution {\n public boolean canMakeSquare(char[][] grid) {\n if(checkGrid(0, 1, 0, 1, grid)) return true;\n else if(checkGrid(1, 2, 0, 1, grid)) return true;\n else if(checkGrid(0, 1, 1, 2, grid)) return true;\n else if(checkGrid(1, 2, 1, 2, grid)) return true;\n else return false;\n }\n \n private boolean checkGrid(int rs, int re, int cs, int ce, char[][] grid){\n int b = 0;\n int w = 0;\n for(int i=rs; i<=re; i++){\n for(int j=cs; j<=ce; j++){\n if(grid[i][j] == \'W\') w++;\n else b++;\n }\n }\n return b != w;\n }\n}\n```
0
0
['Java']
0
make-a-square-with-the-same-color
Easiest Solution Beats 100%
easiest-solution-beats-100-by-mayankbish-16br
null
MayankBisht8630
NORMAL
2024-12-11T09:55:27.047137+00:00
2024-12-11T09:55:27.047137+00:00
6
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```java []\nclass Solution {\n public boolean canMakeSquare(char[][] grid) {\n int black=0, white=0;\n for(int i=0; i<=1; i++){\n for(int j=0; j<=1; j++){\n if(grid[i][j]==\'B\'){\n black++;\n }else{\n white++;\n }\n \n if(grid[i+1][j]==\'B\')black++;\n else white++;\n \n if(grid[i+1][j+1]==\'B\')black++;\n else white++;\n \n if(grid[i][j+1]==\'B\')black++;\n else white++;\n \n// Result case\n if(black==4||white==4||(black==1&&white==3)||(black==3&&white==1)){\n return true;\n }\n// reset the case for next round\n black=0;\n white=0;\n }\n }\n return false;\n }\n}\n```
0
0
['Java']
0
make-a-square-with-the-same-color
Easy & Simple Solution to Check If Same Color 2x2 Square Is Possible
easy-simple-solution-to-check-if-same-co-455h
null
hassan21kh1996
NORMAL
2024-12-10T17:17:22.257336+00:00
2024-12-10T17:17:22.257336+00:00
3
false
# Intuition\nWe need to check all 2x2 subgrids within the 3x3 grid to see if it\'s possible to make a uniform 2x2 square (all \'B\' or all \'W\') by changing at most one cell. If a subgrid contains 3 or more cells of the same color, we can change the remaining cell to make it uniform.\n\n# Approach\n1. **Iterate through possible 2x2 subgrids:** The 3x3 grid has 4 possible 2x2 subgrids.\n2. **Count the black (\'B\') cells:** For each subgrid, count how many black cells are present.\n1. **Check the condition:** If the number of black cells is not equal to 2 (meaning there are at least 3 black or 3 white cells), we can make the subgrid uniform by changing one cell.\n1. **Return** True if any subgrid satisfies the condition, otherwise return False.\n\n# Complexity\n- **Time complexity:O(1)**\nWe only need to check 4 subgrids, each of fixed size 2x2, so the time complexity is constant.\n\n- **Space complexity:O(1)**\nThe space complexity is constant since we only use a few variables for counting.\n\n# Code\n```python3 []\nclass Solution:\n def canMakeSquare(self, grid: List[List[str]]) -> bool:\n for r in range(2):\n for c in range(2):\n black = sum(grid[r+i][c+j] == \'B\' for i in range(2) for j in range(2))\n if black != 2 :\n return True\n return False\n```
0
0
['Python3']
0
make-a-square-with-the-same-color
Beats 100% - Super Simple Solution
beats-100-super-simple-solution-by-brend-gbof
null
brendanc490
NORMAL
2024-12-10T02:11:47.192402+00:00
2024-12-10T02:11:47.192402+00:00
4
false
# Intuition\nIn order to make a 2X2 square of all the same color, we need at least 3 of the tiles to be the same color in the 2x2 area. Here are the cases:\n\nO O\nO X\n\nO X\nO O\n\nO O\nX O\n\nX O\nO O\n\nYou might notice a pattern here, which is that they all form an L like shape. Therefore, we just need to look for one of these L\'s in the input matrix.\n\n# Approach\n1. Loop through each cell in the matrix.\n2. If we have two elements in a row with the same color,\n - Check if the row below has a tile of the same color adjacent to either of the two elements from step 2\n - Check if the row above has a tile of the same color adjacent to either of the two elements from step 2\n\nNote that the inner loop starts at 1 and not 0, since we are checking the previous element to find our matching pair.\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n\n# Code\n```python []\nclass Solution(object):\n def canMakeSquare(self, grid):\n """\n :type grid: List[List[str]]\n :rtype: bool\n """\n\n for i in range(3):\n for j in range(1,3):\n if grid[i][j] == grid[i][j-1]:\n if i > 0 and (grid[i-1][j] == grid[i][j] or grid[i][j] == grid[i-1][j-1]):\n return True\n elif i < 2 and (grid[i+1][j] == grid[i][j] or grid[i][j] == grid[i+1][j-1]):\n return True\n\n return False\n \n```
0
0
['Python']
0
make-a-square-with-the-same-color
Understandable Python for 0ms (beside 17.41Mb)
understandable-python-for-0ms-beside-174-2m7s
Intuition\n Describe your first thoughts on how to solve this problem. \n\nYou only have to check the 4 2x2 square and count the number of color\n\n# Approach\n
Clums
NORMAL
2024-12-05T12:38:42.263908+00:00
2024-12-05T12:38:42.263953+00:00
4
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nYou only have to check the 4 2x2 square and count the number of color\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\nTo simplify it you see that it\'s about any color and it needs at most 1 move (cause with 2 it\'s always true)\nMoreover, you can understand pretty easily that with 1 diferent block than the others it\'s easy : you change only one block. If they are all the same the job is already done. If they are 2 white and 2 black then it\'s impossible for this 2x2 matrix (cause you will have 3 same blocks and 1 different). With 3 sames it\'s the same with 1 different block.\nSo you understand that the problem is easily solvable by checking the number of \'B\' or \'W\' is different of 2 in which case, the problem is solved.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n0.00 ms\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n17.41Mb (too much ngl)\n# Code\n\nYou create a list of 4 array to store the 4 2x2 edged matrices and you perform your code.\nThen you use the function any that returns True if any item of the list put in parameter is true.\nThe list you put in parameter is the result to the logic test of if number of \'B\' or \'W\' is different to 2 in each 2x2 matrix. \n\n```python3 []\nclass Solution:\n def canMakeSquare(self, grid: List[List[str]]) -> bool:\n arrs = [\n [\n grid[i][j]for i in [0,1] for j in [0,1]\n ],\n [\n grid[i][j]for i in [0,1] for j in [1,2]\n ],\n [\n grid[i][j]for i in [1,2] for j in [0,1]\n ],\n [\n grid[i][j]for i in [1,2] for j in [1,2]\n ]\n ]\n return any([a.count("W") != 2 for a in arrs])\n```
0
0
['Python3']
0
make-a-square-with-the-same-color
Solves for any size grid
solves-for-any-size-grid-by-rezaman-h0vd
Intuition\nFind any 2x2 squares that are majority the same color.\n\n# Approach\n- Split the grid into multiple 2x2 grids.\n- Supports arbitrarily sized square
rezaman
NORMAL
2024-12-03T19:21:18.787178+00:00
2024-12-03T19:23:44.833182+00:00
0
false
# Intuition\nFind any 2x2 squares that are majority the same color.\n\n# Approach\n- Split the grid into multiple 2x2 grids.\n- Supports arbitrarily sized square grid\n- Check each individual grid for majority same color\n\n\n# Complexity\n- Time complexity: N-squared\n\n- Space complexity: $$2n$$\n\n# Code\n```ruby []\n# @param {Character[][]} grid\n# @return {Boolean}\ndef can_make_square(grid)\n grids = make_2_by_2(grid)\n\n for grid in grids\n whites = grid.flatten.count(\'W\')\n blacks = grid.flatten.count(\'B\')\n\n return true if whites > 2 || blacks > 2\n end\n\n return false\nend\n\ndef make_2_by_2(grid)\n grids = []\n\n (0..(grid.length-2)).each do |row_ndx|\n (0..(grid[row_ndx].length-2)).each do |col_ndx|\n puts "row: #{row_ndx}, col: #{col_ndx}"\n grids << [grid[row_ndx].slice(col_ndx,2), grid[row_ndx+1].slice(col_ndx,2)]\n end\n end\n \n return grids\nend\n```
0
0
['Ruby']
0
make-a-square-with-the-same-color
Iterate & Split
iterate-split-by-rezaman-492b
Intuition\nFind any 2x2 squares that are majority the same color.\n\n# Approach\n- Split the grid into multiple 2x2 grids. \n- Check each individual grid for ma
rezaman
NORMAL
2024-12-03T19:16:18.374650+00:00
2024-12-03T19:16:18.374683+00:00
0
false
# Intuition\nFind any 2x2 squares that are majority the same color.\n\n# Approach\n- Split the grid into multiple 2x2 grids. \n- Check each individual grid for majority same color\n\n# Complexity\n- Time complexity: N-squared\n\n- Space complexity: $$2n$$\n\n# Code\n```ruby []\n# @param {Character[][]} grid\n# @return {Boolean}\ndef can_make_square(grid)\n grids = make_2_by_2(grid)\n\n for grid in grids\n whites = grid.flatten.count(\'W\')\n blacks = grid.flatten.count(\'B\')\n\n return true if whites > 2 || blacks > 2\n end\n\n return false\nend\n\ndef make_2_by_2(grid)\n row1 = grid[0]\n row2 = grid[1]\n row3 = grid[2]\n\n tl = [row1.slice(0,2), row2.slice(0,2)]\n tr = [row1.slice(1,2), row2.slice(1,2)]\n bl = [row2.slice(0,2), row3.slice(0,2)]\n br = [row2.slice(1,2), row3.slice(1,2)]\n \n return [tl, tr, bl, br]\nend\n```
0
0
['Ruby']
0
make-a-square-with-the-same-color
Submission beat 100% of other submissions' runtime.
submission-beat-100-of-other-submissions-xpui
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
Vishva-mitra
NORMAL
2024-11-26T10:41:31.344952+00:00
2024-11-26T10:41:31.344987+00:00
4
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```java []\nclass Solution {\n public boolean canMakeSquare(char[][] grid) {\n for (int i = 0; i < 2; i++) {\n for (int j = 0; j < 2; j++) {\n int countB = 0;\n int countW = 0;\n if(grid[i][j] == \'B\') {\n countB++;\n } else {\n countW++;\n }\n if(grid[i][j + 1] == \'B\') {\n countB++;\n } else {\n countW++;\n }\n if(grid[i + 1][j] == \'B\') {\n countB++;\n } else {\n countW++;\n }\n if(grid[i + 1][j + 1] == \'B\') {\n countB++;\n } else {\n countW++;\n }\n if (countB != countW) {\n return true;\n }\n }\n }\n return false; \n }\n}\n```
0
0
['Java']
0
make-a-square-with-the-same-color
[Java] ✅ 0MS ✅ 100% ✅ FASTEST ✅ BEST ✅ CLEAN CODE
java-0ms-100-fastest-best-clean-code-by-o3fq5
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n1. As you have 9 cells (W and B), you can make a special submatrix (2x2)
StefanelStan
NORMAL
2024-11-15T05:00:26.299422+00:00
2024-11-15T05:00:26.299452+00:00
6
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. As you have 9 cells (W and B), you can make a special submatrix (2x2) only if that matrix does not have 2 W or 2B. \n2. Any other combination (0-4, 1-3, 3-1, 4-0) will make a special submatrix.\n\n# Complexity\n- Time complexity:$$O(n *n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:$$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n public boolean canMakeSquare(char[][] grid) {\n boolean canMake = false;\n for (int i = 0; i < 2 && !canMake; i++) {\n for (int j = 0; j < 2; j++) {\n canMake = canMake || checkCells(grid, i, j);\n }\n }\n return canMake;\n }\n\n private boolean checkCells(char[][] grid, int i, int j) {\n int white = (grid[i][j] == \'W\' ? 1 : 0) + \n (grid[i][j + 1] == \'W\' ? 1 : 0) +\n (grid[i + 1][j] == \'W\' ? 1 : 0) +\n (grid[i + 1][j + 1] == \'W\' ? 1 : 0);\n return white != 2;\n }\n}\n```
0
0
['Java']
0
make-a-square-with-the-same-color
Build-up pairs of pairs of sum of consecutive Bs and are any not 2?
build-up-pairs-of-pairs-of-sum-of-consec-5ice
Count up consecutive pairs of Bs\n2. Transpose so that ...\n3. Sum up consecutive counts of Bs and ...\n4. Is there any sum that isnt 2 (which would be a 2x2 su
czrpb
NORMAL
2024-11-15T00:24:21.250773+00:00
2024-11-15T00:24:21.250807+00:00
0
false
1. Count up consecutive pairs of Bs\n2. Transpose so that ...\n3. Sum up consecutive counts of Bs and ...\n4. Is there any sum that isnt 2 (which would be a 2x2 sub-grid of half Bs, half Ws)\n\n# Code\n```racket []\n(define/contract (can-make-square grid (n 2) (m 2))\n (-> (listof (listof char?)) boolean?)\n\n (define transpose (curry apply map list))\n\n (define [build-pairs rows f]\n (map second\n (for/list ((row rows))\n (foldl [\u03BB (e a) (list e (f (first a) e (second a)))] (list (car row) \'()) (cdr row))\n )))\n\n ; new grid where we count the number of #\\Bs in all consecutative pairs in each row\n (define count-consecutive-Bs\n (build-pairs grid\n [match-lambda** ;(previous-letter current-letter acc)\n ([#\\B #\\B result] [cons 2 result])\n ([#\\W #\\W result] [cons 0 result])\n ([_ _ result] [cons 1 result])\n ]))\n\n (define count-consecutive-Bs-t (transpose count-consecutive-Bs))\n\n (define sum-pairs\n (flatten\n (build-pairs count-consecutive-Bs-t\n [\u03BB (a b r) (cons (+ a b) r)])))\n\n (for/or ((p sum-pairs))\n (not (= 2 p)))\n\n )\n\n```
0
0
['Racket']
0
make-a-square-with-the-same-color
3127. Make a Square with the Same Color
3127-make-a-square-with-the-same-color-b-1767
Complexity\nTime: O(N^2)\nSpace: O(1)\n\n# Code\npython []\nclass Solution(object):\n def canMakeSquare(self, grid):\n """\n :type grid: List[L
pasha_iden
NORMAL
2024-11-12T00:46:30.757208+00:00
2024-11-12T00:46:30.757242+00:00
3
false
# Complexity\nTime: $$O(N^2)$$\nSpace: $$O(1)$$\n\n# Code\n```python []\nclass Solution(object):\n def canMakeSquare(self, grid):\n """\n :type grid: List[List[str]]\n :rtype: bool\n """\n q=1\n for x in range(len(grid)-1):\n for y in range(len(grid[x])-1):\n if grid[x][y] == grid[x][y+1]:\n q += 1\n if grid[x][y] == grid[x+1][y]:\n q += 1\n if grid[x][y] == grid[x+1][y+1]:\n q += 1\n if q == 1 or q == 3 or q == 4:\n return True\n q=1\n return False\n```
0
0
['Python']
0
make-a-square-with-the-same-color
Does a 2x2 view not have 2 Bs?
does-a-2x2-view-not-have-2-bs-by-czrpb-ddih
Create a 2x2 lens\n2. Whip it thru the matrix; lets call these views\n3. Exit with #t if a view is found to not have 2 Bs\n\n# Code\nracket []\n(define/contract
czrpb
NORMAL
2024-11-11T23:00:49.301848+00:00
2024-11-11T23:00:49.301903+00:00
2
false
1. Create a 2x2 lens\n2. Whip it thru the matrix; lets call these *view*s\n3. Exit with `#t` if a *view* is found to not have 2 `B`s\n\n# Code\n```racket []\n(define/contract (can-make-square grid (n 2) (m 2))\n (-> (listof (listof char?)) boolean?)\n\n (define is-B? (curry char=? #\\B))\n\n (define [build-lens (n n) (m m)]\n (for*/list ((i (range n)) (j (range m)))\n (list i j)\n ))\n\n (define [lens->view matrix lens cell]\n (match-let (((list cr cc) cell))\n (for/list ((rc lens))\n (match-let (((list r c) rc))\n (list-ref (list-ref matrix (+ cr r)) (+ cc c))\n ))))\n\n (for*/or ((gr (range (- (length grid) n -1))) (gc (range (- (length (first grid)) m -1))))\n (let ((view (lens->view grid (build-lens) (list gr gc))))\n (not (= 2 (count is-B? view)))\n ))\n\n )\n\n```
0
0
['Racket']
0
make-a-square-with-the-same-color
Easy C++ Code (Beats 100%)
easy-c-code-beats-100-by-ai1a_2310812-nwv0
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
ai1a_2310812
NORMAL
2024-11-10T09:03:11.843378+00:00
2024-11-10T09:03:11.843405+00:00
0
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```cpp []\nclass Solution {\npublic:\n bool canMakeSquare(vector<vector<char>>& grid) \n {\n for(int i=0;i<grid.size()-1;i++)\n {\n for(int j=0;j<grid[i].size()-1;j++)\n {\n int w=0;\n int b=0;\n if(grid[i][j]==\'W\')\n {\n w++;\n }\n else\n {\n b++;\n }\n if(grid[i+1][j]==\'W\')\n {\n w++;\n }\n else\n {\n b++;\n }\n if(grid[i][j+1]==\'W\')\n {\n w++;\n }\n else\n {\n b++;\n }\n if(grid[i+1][j+1]==\'W\')\n {\n w++;\n }\n else\n {\n b++;\n }\n if(w==3 || b==3 || w==4 || b==4)\n {\n return 1;\n }\n }\n } \n return 0;\n }\n};\n```
0
0
['C++']
0
make-a-square-with-the-same-color
Simple solution using python
simple-solution-using-python-by-priya_re-8ydu
Time complexity of O(1):\nThere is a simple trick, if the 2x2 matrix contains equal number of "B" and "W" then we can\'t change the matrix as perfect square.\n\
Priya_Reka_S
NORMAL
2024-11-06T12:56:44.830133+00:00
2024-11-06T12:56:44.830166+00:00
4
false
Time complexity of O(1):\nThere is a simple trick, if the 2x2 matrix contains equal number of "B" and "W" then we can\'t change the matrix as perfect square.\n\n# Code\n```python3 []\nclass Solution:\n def canMakeSquare(self, grid: List[List[str]]) -> bool:\n l1=[grid[0][1],grid[0][0],grid[1][0],grid[1][1]]\n l2=[grid[0][1],grid[0][2],grid[1][1],grid[1][2]]\n l3=[grid[2][1],grid[2][2],grid[1][2],grid[1][1]]\n l4=[grid[2][1],grid[2][0],grid[1][0],grid[1][1]]\n l=[l1,l2,l3,l4]\n for i in l:\n if i.count(\'B\')!=i.count(\'W\'):\n return True\n else:\n return False\n\n \n```
0
0
['Python3']
0
make-a-square-with-the-same-color
Simple PHP solution
simple-php-solution-by-file2k-ym9e
Intuition\nCreate 2x2 squares array from 3x3 square. Loop thru 2x2 squares and check weather it\'s possible for any of them to have all 4 cells with the same co
file2k
NORMAL
2024-11-04T20:47:49.111193+00:00
2024-11-04T20:47:49.111220+00:00
3
false
# Intuition\nCreate 2x2 squares array from 3x3 square. Loop thru 2x2 squares and check weather it\'s possible for any of them to have all 4 cells with the same color. \n\n# Approach\nOuter loops with iterators "i" and "j" are used for navigating 2x2 squares. Inner loops with iterators "k" and "l" are used for navigating cells inside the current 2x2 square.\n\n\n# Code\n```php []\nclass Solution {\n\n /**\n * @param String[][] $grid\n * @return Boolean\n */\n function canMakeSquare($grid) {\n $squares = [];\n for ($i = 0; $i < 2; $i++) {\n for ($j = 0; $j < 2; $j++) {\n $square = [];\n \n for ($k = 0; $k < 2; $k++) {\n for ($l = 0; $l < 2; $l++) {\n $rowIdx = $i + $k;\n $columnIdx = $j + $l;\n $square[] = $grid[$rowIdx][$columnIdx];\n }\n }\n $squares[] = $square;\n }\n }\n \n foreach($squares as $square) {\n $vls = array_count_values($square);\n if ($vls[\'B\'] !== 2) {\n return true;\n }\n }\n return false;\n }\n}\n```
0
0
['PHP']
0
make-a-square-with-the-same-color
Java 0ms beats 100%, check all 2x2 subgrids and early return upon success
java-0ms-beats-100-check-all-2x2-subgrid-0sl3
Intuition\n Describe your first thoughts on how to solve this problem. \nIf a 2x2 subgrid has all one color, or 3 of one color, then we can have a 2x2 of 1 colo
texastim
NORMAL
2024-11-04T06:34:03.871096+00:00
2024-11-04T06:34:03.871158+00:00
3
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIf a 2x2 subgrid has all one color, or 3 of one color, then we can have a 2x2 of 1 color with at most one change. If 2x2 subgrid has 2 of each color, we can\'t.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nSystematically check all 2x2 subgrids, using a private method to count how many \'W\' cells there are (which also gives us the number of \'B\' cells).\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$ for an input grid of `n` cells since we check every 2x2 subgrid, which approaches `4n` accesses per cell as the grid increases in size.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(1)$$ since we just maintain a few variables\n\n# Code\n```java []\n// start 12:02 am\n// solve 12:25 am\n// time 23 minutes\n\nclass Solution {\n\n char[][] grid;\n\n public boolean canMakeSquare(char[][] grid) {\n this.grid = grid;\n for (int i = 0; i < 2; i++) {\n for (int j = 0; j < 2; j++) {\n if (canMakeSameColor(i, j)) { // we are looking southeast\n return true;\n }\n }\n }\n return false;\n }\n\n private boolean canMakeSameColor(int row, int col) {\n int countW = 0; // return true if this count is 0 or 4 (i.e., we change 0 cells) or 1 or 3 (we change 1 cell)\n countW += this.grid[row][col] == \'W\' ? 1 : 0;\n countW += this.grid[row + 1][col] == \'W\' ? 1 : 0;\n countW += this.grid[row][col + 1] == \'W\' ? 1 : 0;\n countW += this.grid[row + 1][col + 1] == \'W\' ? 1 : 0;\n return countW == 2 ? false : true;\n }\n}\n```
0
0
['Java']
0
make-a-square-with-the-same-color
Beat 100% with Cpp
beat-100-with-cpp-by-carfel14-09l1
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
carfel14
NORMAL
2024-11-03T03:42:27.874779+00:00
2024-11-03T03:42:27.874825+00:00
4
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```cpp []\nclass Solution {\npublic:\n bool canMakeSquare(vector<vector<char>>& grid) {\n for (int i = 0; i < 2; ++i){\n for (int j = 0; j < 2; ++j){\n // Traverse 2x2 square counting for white\n int white = 0;\n for (int m = 0; m <= 1; ++m){\n for (int n = 0; n <= 1; ++n){\n if(grid[i + m][j + n] == \'W\') white++;\n }\n }\n if (white != 2) return true;\n }\n }\n return false;\n }\n};\n```
0
0
['C++']
0
make-a-square-with-the-same-color
POO Solution in Python
poo-solution-in-python-by-astros-5x57
Intuition\nThe solution is overcomplicated, but it is elegant :-P\n\n# Code\npython3 []\nclass Colors:\n def __init__(self, white: int, black: int):\n
Astros
NORMAL
2024-10-30T13:15:08.628909+00:00
2024-10-30T13:15:08.628935+00:00
2
false
# Intuition\nThe solution is overcomplicated, but it is elegant :-P\n\n# Code\n```python3 []\nclass Colors:\n def __init__(self, white: int, black: int):\n self.white = white\n self.black = black\n \n def is_possible(self) -> bool:\n return self.white in [3, 4] or self.black in [3, 4]\n\nclass Solution:\n def canMakeSquare(self, grid: List[List[str]]) -> bool:\n \n for row in [0, 1]:\n for col in [0, 1]:\n colors = self.count(grid, row, col)\n if colors.is_possible():\n return True\n \n return False\n \n def count(self, grid: List[int], start_rows: int, start_cols: int) -> Colors:\n black, white = 0, 0\n\n for r in range(start_rows, start_rows + 2):\n for c in range(start_cols, start_cols + 2):\n if grid[r][c] == \'W\':\n white += 1\n else:\n black += 1\n\n return Colors(white=white, black=black)\n```
0
0
['Python3']
0
make-a-square-with-the-same-color
Easy
easy-by-shanku1999-q3ip
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
shanku1999
NORMAL
2024-10-23T09:46:53.971648+00:00
2024-10-23T09:46:53.971681+00:00
1
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```python3 []\nclass Solution:\n def canMakeSquare(self, grid: List[List[str]]) -> bool:\n for i in range(2):\n for j in range(2):\n if [grid[i][j],grid[i+1][j],grid[i][j+1],grid[i+1][j+1]].count("B")!=2:\n return True\n return False\n\n\n \n```
0
0
['Python3']
0
make-a-square-with-the-same-color
a new one
a-new-one-by-ianard-z332
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
IanArd
NORMAL
2024-10-21T19:15:33.480506+00:00
2024-10-21T19:15:33.480537+00:00
4
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```rust []\nimpl Solution {\n pub fn can_make_square(grid: Vec<Vec<char>>) -> bool {\n let cases = vec![\n [&grid[0][0..=1], &grid[1][0..=1]].concat(),\n [&grid[0][1..=2], &grid[1][1..=2]].concat(),\n [&grid[1][0..=1], &grid[2][0..=1]].concat(),\n [&grid[1][1..=2], &grid[2][1..=2]].concat()\n ];\n let cases: Vec<bool> = cases.iter()\n .map(|case| {\n let case: Vec<char> = case.iter()\n .filter_map(|c| {\n match *c == \'B\' {\n true => Some(\'B\'),\n false => None\n }\n })\n .collect();\n match case.len() == 1 || case.len() == 3 || case.len() == 0 || case.len() == 4 {\n true => true,\n false => false\n }\n })\n .collect();\n\n match cases.contains(&true) {\n true => true,\n false => false\n }\n }\n}\n```
0
0
['Rust']
0
make-a-square-with-the-same-color
Customizable Solution | C++
customizable-solution-c-by-joao_ferrao-f29a
Complexity\n- Time complexity: O(1)\n\n- Space complexity: O(1)\n\n# Code\nC++ []\nclass Solution {\npublic:\n bool canMakeSquare(vector<vector<char>>& grid)
Joao_Ferrao
NORMAL
2024-10-16T15:07:51.447908+00:00
2024-10-16T15:07:51.447935+00:00
0
false
# Complexity\n- Time complexity: O(1)\n\n- Space complexity: O(1)\n\n# Code\n```C++ []\nclass Solution {\npublic:\n bool canMakeSquare(vector<vector<char>>& grid) {\n const int squareLength = 2;\n for(int i = 0; i < squareLength; ++i){\n for(int j = 0; j < squareLength; ++j){\n int countWhiteSquares {};\n for(int k = 0; k < squareLength; ++k){\n if(grid[i][j + k] == \'W\') ++countWhiteSquares;\n if(grid[i + 1][j + k] == \'W\') ++countWhiteSquares;\n }\n\n if(countWhiteSquares != 2) return true;\n }\n }\n \n return false;\n }\n};\n```
0
0
['C++']
0
make-a-square-with-the-same-color
Brute Force Solution || JAVA
brute-force-solution-java-by-ashwinmurug-gufv
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
ashwinmurugan46
NORMAL
2024-10-16T04:53:28.418856+00:00
2024-10-16T04:53:28.418901+00:00
2
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```java []\nclass Solution {\n public boolean canMakeSquare(char[][] grid) {\n for (int i = 0; i < grid.length - 1; i++) {\n for (int j = 0; j < grid[0].length - 1; j++) {\n char[] col = { grid[i][j], grid[i][j + 1], grid[i + 1][j], grid[i + 1][j + 1] };\n int wc = 0, bc = 0;\n for (char ii : col) {\n if (ii == \'W\')\n wc++;\n else\n bc++;\n }\n if (bc >= 3 || wc >= 3)\n return true;\n\n }\n\n }\n return false;\n }\n}\n```
0
0
['Java']
0
make-a-square-with-the-same-color
C# simple solution
c-simple-solution-by-nzspider-ftiw
Code\ncsharp []\npublic class Solution {\n public bool CanMakeSquare(char[][] grid) {\n int row=3,col=3,r=0,c=0,b=0,w=0;\n var pos = new List<(
nzspider
NORMAL
2024-10-13T22:35:32.261739+00:00
2024-10-13T22:35:32.261838+00:00
7
false
# Code\n```csharp []\npublic class Solution {\n public bool CanMakeSquare(char[][] grid) {\n int row=3,col=3,r=0,c=0,b=0,w=0;\n var pos = new List<(int,int)>{(0,0),(0,1),(1,0),(1,1)};\n \n foreach(var (x, y) in pos){\n for(r=y;r<2+y;r++){\n for(c=x;c<2+x;c++){\n if(grid[r][c]==\'B\')b++;\n else if(grid[r][c]==\'W\')w++;\n }\n }\n if(b>2 || w>2)return true;\n b=0;\n w=0;\n }\n return false;\n }\n}\n```
0
0
['C#']
0
make-a-square-with-the-same-color
Python3 O(N ^ 4) Solution with counting (97.76% Runtime)
python3-on-4-solution-with-counting-9776-ogqy
Intuition\n Describe your first thoughts on how to solve this problem. \n\n\n\n# Approach\n Describe your approach to solving the problem. \n- Iteratively check
missingdlls
NORMAL
2024-10-10T11:51:09.848105+00:00
2024-10-10T11:51:09.848128+00:00
1
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n![image.png](https://assets.leetcode.com/users/images/07b4e686-1dc6-4264-a113-8877aa208ae2_1728560963.8037841.png)\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- Iteratively check 4 adjacent cells and see if it contains more then 3 black or white colors.\n\n# Complexity\n- Time complexity: O(N ^ 4)\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\nIf this solution is similar to yours or helpful, upvote me if you don\'t mind\n```python3 []\nclass Solution:\n def canMakeSquare(self, grid: List[List[str]]) -> bool:\n for i in range(len(grid)-1):\n for j in range(len(grid[0])-1):\n b=w=0\n for y in range(i,i+2):\n for x in range(j,j+2):\n if grid[y][x]=="B":\n b+=1\n else:\n w+=1\n\n if b>=3 or w>=3: \n return True\n return False\n```
0
0
['Array', 'Matrix', 'Counting', 'Python', 'Python3']
0
binary-tree-preorder-traversal
Accepted iterative solution in Java using stack.
accepted-iterative-solution-in-java-usin-9nab
Note that in this solution only right children are stored to stack.\n\n public List preorderTraversal(TreeNode node) {\n\t\tList list = new LinkedList();\n\t
pavel-shlyk
NORMAL
2014-12-29T15:03:10+00:00
2018-10-21T02:03:29.238021+00:00
77,976
false
Note that in this solution only right children are stored to stack.\n\n public List<Integer> preorderTraversal(TreeNode node) {\n\t\tList<Integer> list = new LinkedList<Integer>();\n\t\tStack<TreeNode> rights = new Stack<TreeNode>();\n\t\twhile(node != null) {\n\t\t\tlist.add(node.val);\n\t\t\tif (node.right != null) {\n\t\t\t\trights.push(node.right);\n\t\t\t}\n\t\t\tnode = node.left;\n\t\t\tif (node == null && !rights.isEmpty()) {\n\t\t\t\tnode = rights.pop();\n\t\t\t}\n\t\t}\n return list;\n }
347
7
[]
47
binary-tree-preorder-traversal
Very simple iterative Python solution
very-simple-iterative-python-solution-by-rhhu
Classical usage of stack's LIFO feature, very easy to grasp:\n\n \n def preorderTraversal(self, root):\n ret = []\n stack = [root]\n
clue
NORMAL
2015-01-27T04:17:27+00:00
2018-10-15T14:36:23.147933+00:00
36,928
false
Classical usage of stack's LIFO feature, very easy to grasp:\n\n \n def preorderTraversal(self, root):\n ret = []\n stack = [root]\n while stack:\n node = stack.pop()\n if node:\n ret.append(node.val)\n stack.append(node.right)\n stack.append(node.left)\n return ret
283
3
['Iterator', 'Python']
33
binary-tree-preorder-traversal
C++ Iterative, Recursive and Morris Traversal
c-iterative-recursive-and-morris-travers-5lbv
There are three solutions to this problem.\n\n 1. Iterative solution using stack --- O(n) time and O(n) space;\n 2. Recursive solution --- O(n) time and O(n) sp
jianchao-li
NORMAL
2015-05-21T16:31:34+00:00
2018-10-02T16:31:25.908094+00:00
27,836
false
There are three solutions to this problem.\n\n 1. Iterative solution using stack --- `O(n)` time and `O(n)` space;\n 2. Recursive solution --- `O(n)` time and `O(n)` space (function call stack);\n 3. Morris traversal --- `O(n)` time and `O(1)` space.\n\n**Iterative solution using stack**\n\n```cpp\nclass Solution {\npublic:\n vector<int> preorderTraversal(TreeNode* root) {\n vector<int> nodes;\n stack<TreeNode*> todo;\n while (root || !todo.empty()) {\n if (root) {\n nodes.push_back(root -> val);\n if (root -> right) {\n todo.push(root -> right);\n }\n root = root -> left;\n } else {\n root = todo.top();\n todo.pop();\n }\n }\n return nodes;\n }\n};\n```\n\n**Recursive solution**\n\n```cpp\nclass Solution {\npublic:\n vector<int> preorderTraversal(TreeNode* root) {\n vector<int> nodes;\n preorder(root, nodes);\n return nodes;\n }\nprivate:\n void preorder(TreeNode* root, vector<int>& nodes) {\n if (!root) {\n return;\n }\n nodes.push_back(root -> val);\n preorder(root -> left, nodes);\n preorder(root -> right, nodes);\n }\n};\n```\n\n**Morris traversal**\n\n```cpp\nclass Solution {\npublic:\n vector<int> preorderTraversal(TreeNode* root) {\n vector<int> nodes;\n while (root) {\n if (root -> left) {\n TreeNode* pre = root -> left;\n while (pre -> right && pre -> right != root) {\n pre = pre -> right;\n }\n if (!pre -> right) {\n pre -> right = root;\n nodes.push_back(root -> val);\n root = root -> left;\n } else {\n pre -> right = NULL;\n root = root -> right;\n }\n } else {\n nodes.push_back(root -> val);\n root = root -> right;\n }\n }\n return nodes;\n }\n};\n```
229
2
['Stack', 'Recursion', 'Binary Tree', 'Iterator', 'C++']
18
binary-tree-preorder-traversal
Solution
solution-by-deleted_user-v7rj
C++ []\nclass Solution {\npublic:\n vector<int> preorderTraversal(TreeNode* root) {\n vector<int> preorder;\n stack<TreeNode*> stack;\n
deleted_user
NORMAL
2023-01-09T16:00:31.516361+00:00
2023-03-07T10:18:41.372462+00:00
15,432
false
```C++ []\nclass Solution {\npublic:\n vector<int> preorderTraversal(TreeNode* root) {\n vector<int> preorder;\n stack<TreeNode*> stack;\n if (root == NULL)\n return preorder;\n stack.push(root);\n while(!stack.empty()) {\n TreeNode* curr = stack.top();\n stack.pop();\n preorder.push_back(curr->val);\n if (curr->right != NULL)\n stack.push(curr->right);\n if (curr->left != NULL)\n stack.push(curr->left);\n }\n return preorder;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:\n head = root\n stack = []\n res = []\n\n while head or stack:\n if head:\n res.append(head.val)\n if head.right:\n stack.append(head.right)\n head = head.left\n else:\n head = stack.pop()\n\n return res \n```\n\n```Java []\nclass Solution {\n List<Integer> preorderTraverse(TreeNode root,List<Integer> list) {\n\n if(root==null)\n return list;\n list.add(root.val);\n preorderTraverse(root.left,list);\n preorderTraverse(root.right,list);\n return list;\n }\n public List<Integer> preorderTraversal(TreeNode root) {\n List<Integer> list = new ArrayList<Integer>();\n list = preorderTraverse(root,list);\n return list;\n }\n}\n```\n
221
0
['C++', 'Java', 'Python3']
3
binary-tree-preorder-traversal
3 Different Solutions
3-different-solutions-by-fabrizio3-1xgm
Recursive method with List as returning value:\n\n \tpublic List preorderTraversal(TreeNode root) {\n \t\tList pre = new LinkedList();\n \t\tif(root==n
fabrizio3
NORMAL
2015-04-22T07:50:47+00:00
2018-10-19T02:07:21.808809+00:00
43,107
false
Recursive method with List as returning value:\n\n \tpublic List<Integer> preorderTraversal(TreeNode root) {\n \t\tList<Integer> pre = new LinkedList<Integer>();\n \t\tif(root==null) return pre;\n \t\tpre.add(root.val);\n \t\tpre.addAll(preorderTraversal(root.left));\n \t\tpre.addAll(preorderTraversal(root.right));\n \t\treturn pre;\n \t}\n\nRecursive method with Helper method to have a List as paramater, so we can modify the parameter and don't have to instantiate a new List at each recursive call:\n\n \tpublic List<Integer> preorderTraversal(TreeNode root) {\n \t\tList<Integer> pre = new LinkedList<Integer>();\n \t\tpreHelper(root,pre);\n \t\treturn pre;\n \t}\n \tpublic void preHelper(TreeNode root, List<Integer> pre) {\n \t\tif(root==null) return;\n \t\tpre.add(root.val);\n \t\tpreHelper(root.left,pre);\n \t\tpreHelper(root.right,pre);\n \t}\n\nIterative method with Stack:\n\n \tpublic List<Integer> preorderIt(TreeNode root) {\n \t\tList<Integer> pre = new LinkedList<Integer>();\n \t\tif(root==null) return pre;\n \t\tStack<TreeNode> tovisit = new Stack<TreeNode>();\n \t\ttovisit.push(root);\n \t\twhile(!tovisit.empty()) {\n \t\t\tTreeNode visiting = tovisit.pop();\n \t\t\tpre.add(visiting.val);\n \t\t\tif(visiting.right!=null) tovisit.push(visiting.right);\n \t\t\tif(visiting.left!=null) tovisit.push(visiting.left);\n \t\t}\n \t\treturn pre;\n \t}
220
4
['Recursion', 'Iterator', 'Java']
23
binary-tree-preorder-traversal
Python solutions (recursively and iteratively).
python-solutions-recursively-and-iterati-8emk
\n # recursively\n def preorderTraversal1(self, root):\n res = []\n self.dfs(root, res)\n return res\n \n def dfs(self,
oldcodingfarmer
NORMAL
2015-08-13T15:14:56+00:00
2018-09-24T23:32:41.072858+00:00
22,638
false
\n # recursively\n def preorderTraversal1(self, root):\n res = []\n self.dfs(root, res)\n return res\n \n def dfs(self, root, res):\n if root:\n res.append(root.val)\n self.dfs(root.left, res)\n self.dfs(root.right, res)\n \n # iteratively\n def preorderTraversal(self, root):\n stack, res = [root], []\n while stack:\n node = stack.pop()\n if node:\n res.append(node.val)\n stack.append(node.right)\n stack.append(node.left)\n return res
170
1
['Recursion', 'Python']
14
binary-tree-preorder-traversal
【Video】Recursive Solution and Stack Solution
video-recursive-solution-and-stack-solut-pygs
Intuition\nWe should know how to implement inorder, preorder and postorder.\n\n# Solution Video\n\nhttps://youtu.be/9dTgOlzLDa0\n\n\u25A0 Timeline\n0:09 Explain
niits
NORMAL
2024-12-07T03:51:56.880619+00:00
2024-12-07T03:51:56.880643+00:00
8,862
false
# Intuition\nWe should know how to implement inorder, preorder and postorder.\n\n# Solution Video\n\nhttps://youtu.be/9dTgOlzLDa0\n\n\u25A0 Timeline\n`0:09` Explain Recursive Solution\n`1:02` Coding for Recursive Solution\n`2:08` Time Complexity and Space Complexity for Recursive Solution\n`2:27` Explain Stack Solution\n`7:27` Coding for Stack Solution\n`8:46` Time Complexity and Space Complexity for Stack Solution\n\n### \u2B50\uFE0F\u2B50\uFE0F Don\'t forget to subscribe to my channel! \u2B50\uFE0F\u2B50\uFE0F\n\n**\u25A0 Subscribe URL**\nhttp://www.youtube.com/channel/UC9RMNwYTL3SXCP6ShLWVFww?sub_confirmation=1\n\nSubscribers: 8,338\nThank you for your support!\n\n---\n\n# Solution 1 - Recursive Solution\n\nTo be honest, we should know how to implement inorder, preorder and postorder.\n\n```\nclass TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\nresult = []\n\ndef inorder(root):\n if not root:\n return []\n\n inorder(root.left)\n result.append(root.val)\n inorder(root.right)\n return result\n\ndef preorder(root):\n if not root:\n return []\n\n result.append(root.val)\n preorder(root.left)\n preorder(root.right)\n return result\n\ndef postorder(root):\n if not root:\n return []\n\n postorder(root.left)\n postorder(root.right)\n result.append(root.val)\n return result\n```\n\nLet\'s focus on `result.append(root.val)`\n\n---\n\n\u2B50\uFE0F Points\n\nFor `Inorder`, we do something `between` left and right.\nFor `Preorder`, we do something `before` left and right.\nFor `Postorder`, we do something `after` left and right.\n\n---\n\nWe use preorder this time, so do something before left and right.\n\nhttps://youtu.be/bU_dXCOWHls\n\n---\n\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(h)$$\n\n```python []\nclass Solution:\n def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:\n res = []\n\n def preorder(node):\n if not node:\n return\n \n res.append(node.val)\n preorder(node.left)\n preorder(node.right)\n \n preorder(root)\n\n return res\n```\n```javascript []\nvar preorderTraversal = function(root) {\n const res = [];\n\n function preorder(node) {\n if (!node) {\n return;\n }\n\n res.push(node.val);\n preorder(node.left);\n preorder(node.right);\n }\n\n preorder(root);\n return res; \n};\n```\n```java []\nclass Solution {\n public List<Integer> preorderTraversal(TreeNode root) {\n List<Integer> res = new ArrayList<>();\n\n preorder(root, res);\n return res; \n }\n\n private void preorder(TreeNode node, List<Integer> res) {\n if (node == null) {\n return;\n }\n\n res.add(node.val);\n preorder(node.left, res);\n preorder(node.right, res);\n } \n}\n```\n```C++ []\nclass Solution {\npublic:\n vector<int> preorderTraversal(TreeNode* root) {\n vector<int> res;\n\n preorder(root, res);\n return res; \n }\n\nprivate:\n void preorder(TreeNode* node, std::vector<int>& res) {\n if (node == nullptr) {\n return;\n }\n\n res.push_back(node->val);\n preorder(node->left, res);\n preorder(node->right, res);\n } \n};\n```\n\n# Step by Step Algorithm\n\n### 1. **Initialization of the Result List**\n ```python\n res = []\n ```\n - **Explanation:** An empty list `res` is created to store the values of the nodes as they are visited in preorder (root, left, right) traversal order.\n\n### 2. **Definition of the Preorder Function**\n ```python\n def preorder(node):\n ```\n - **Explanation:** A helper function `preorder` is defined, which takes a `node` as its argument. This function will be used to perform the preorder traversal recursively.\n\n### 3. **Base Case: Check for Null Node**\n ```python\n if not node:\n return\n ```\n - **Explanation:** This checks if the current `node` is `None` (i.e., if there is no node to process). If the `node` is `None`, the function returns immediately, effectively ending the recursion for that branch of the tree.\n\n### 4. **Process the Current Node**\n ```python\n res.append(node.val)\n ```\n - **Explanation:** If the current `node` is not `None`, its value is added to the `res` list. This corresponds to visiting the root node in preorder traversal.\n\n### 5. **Recursive Call to Traverse the Left Subtree**\n ```python\n preorder(node.left)\n ```\n - **Explanation:** The `preorder` function is called recursively on the left child of the current `node`. This moves the traversal to the left subtree, continuing the preorder pattern.\n\n### 6. **Recursive Call to Traverse the Right Subtree**\n ```python\n preorder(node.right)\n ```\n - **Explanation:** After the left subtree has been fully traversed, the `preorder` function is called recursively on the right child of the current `node`. This ensures that the right subtree is visited after the left subtree, completing the preorder traversal for this node.\n\n### 7. **Initiating the Preorder Traversal**\n ```python\n preorder(root)\n ```\n - **Explanation:** The `preorder` function is initially called with the `root` node of the binary tree. This starts the recursive traversal process from the root of the tree.\n\n### 8. **Returning the Result List**\n ```python\n return res\n ```\n - **Explanation:** After the entire tree has been traversed, the `res` list, now containing all the node values in preorder order, is returned as the output of the `preorderTraversal` function.\n\n---\n\n# Solution 2 - Stack solution\n\nI explain stack solution with visualization in the video above.\n\n```python []\nclass Solution:\n def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:\n res = []\n\n if not root:\n return res\n \n st = [root]\n\n while st:\n node = st.pop()\n res.append(node.val)\n\n if node.right:\n st.append(node.right)\n \n if node.left:\n st.append(node.left)\n \n return res\n```\n```javascript []\nvar preorderTraversal = function(root) {\n const res = [];\n if (!root) return res;\n\n const stack = [root];\n\n while (stack.length > 0) {\n const node = stack.pop();\n res.push(node.val);\n\n if (node.right) {\n stack.push(node.right);\n }\n if (node.left) {\n stack.push(node.left);\n }\n }\n\n return res; \n};\n```\n```java []\nclass Solution {\n public List<Integer> preorderTraversal(TreeNode root) {\n List<Integer> res = new ArrayList<>();\n if (root == null) return res;\n\n Stack<TreeNode> stack = new Stack<>();\n stack.push(root);\n\n while (!stack.isEmpty()) {\n TreeNode node = stack.pop();\n res.add(node.val);\n\n if (node.right != null) {\n stack.push(node.right);\n }\n if (node.left != null) {\n stack.push(node.left);\n }\n }\n\n return res;\n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n vector<int> preorderTraversal(TreeNode* root) {\n vector<int> res;\n if (!root) return res;\n\n stack<TreeNode*> st;\n st.push(root);\n\n while (!st.empty()) {\n TreeNode* node = st.top();\n st.pop();\n res.push_back(node->val);\n\n if (node->right) {\n st.push(node->right);\n }\n if (node->left) {\n st.push(node->left);\n }\n }\n\n return res;\n } \n};\n```\n\n# Step by Step Algorithm\n\n### 1. **Initialization of the Result List**\n ```python\n res = []\n ```\n - **Explanation:** An empty list `res` is created to store the values of the nodes as they are visited in preorder (root, left, right) traversal order.\n\n### 2. **Check if the Root is Null**\n ```python\n if not root:\n return res\n ```\n - **Explanation:** This checks if the `root` node is `None` (i.e., the tree is empty). If the `root` is `None`, the function immediately returns the empty `res` list since there\'s nothing to traverse.\n\n### 3. **Initialization of the Stack**\n ```python\n st = [root]\n ```\n - **Explanation:** A stack `st` is initialized with the `root` node as its only element. The stack will be used to manage the traversal process, simulating the recursive call stack in an iterative manner.\n\n### 4. **Start of the While Loop**\n ```python\n while st:\n ```\n - **Explanation:** This `while` loop continues to run as long as there are nodes in the stack (`st`). It ensures that the entire tree is traversed.\n\n### 5. **Pop the Top Node from the Stack**\n ```python\n node = st.pop()\n ```\n - **Explanation:** The top node is popped from the stack, meaning it\'s removed from the stack and assigned to the variable `node`. This is the node that will be processed next.\n\n### 6. **Process the Current Node**\n ```python\n res.append(node.val)\n ```\n - **Explanation:** The value of the current `node` is added to the `res` list. This corresponds to visiting the root node in the preorder traversal.\n\n### 7. **Push the Right Child onto the Stack**\n ```python\n if node.right:\n st.append(node.right)\n ```\n - **Explanation:** If the current `node` has a right child, that right child is pushed onto the stack. This ensures that after the left subtree is processed, the traversal will move to the right subtree.\n\n### 8. **Push the Left Child onto the Stack**\n ```python\n if node.left:\n st.append(node.left)\n ```\n - **Explanation:** If the current `node` has a left child, that left child is pushed onto the stack. The left child is pushed after the right child so that it will be processed first (since the stack follows the Last-In-First-Out (LIFO) principle), ensuring the preorder sequence (root, left, right) is maintained.\n\n### 9. **End of the While Loop**\n - **Explanation:** The loop continues to run, processing each node in the stack in the order they were added, until the stack is empty. This ensures that all nodes are visited in the correct preorder sequence.\n\n### 10. **Return the Result List**\n ```python\n return res\n ```\n - **Explanation:** After the entire tree has been traversed and all node values have been added to `res`, the `res` list is returned as the final output of the `preorderTraversal` function.\n\n---\n\nThank you for reading my post.\n\u2B50\uFE0F Please upvote it and don\'t forget to subscribe to my channel!\n\n\u2B50\uFE0F Subscribe URL\nhttp://www.youtube.com/channel/UC9RMNwYTL3SXCP6ShLWVFww?sub_confirmation=1\n\n\u2B50\uFE0F Twitter\nhttps://twitter.com/CodingNinjaAZ\n\n### Related video.\n\nBinary Tree Inorder Traversal - LeetCode #94\n\nhttps://youtu.be/TKMxiXRzDZ0\n\n
98
1
['Stack', 'Tree', 'Depth-First Search', 'Binary Tree', 'C++', 'Java', 'Python3', 'JavaScript']
0
binary-tree-preorder-traversal
✅[C++] EASY|| Beats100% || 3 Approach With explaination✅
c-easy-beats100-3-approach-with-explaina-fxde
\uD83C\uDFA5\uD83D\uDD25 Exciting News! Join my Coding Journey! Subscribe Now! \uD83D\uDD25\uD83C\uDFA5\n\n\uD83D\uDD17 Link in the leetcode profile \n\nNew cod
vishnoi29
NORMAL
2023-01-09T00:29:48.816065+00:00
2023-06-14T02:11:40.159956+00:00
12,531
false
\uD83C\uDFA5\uD83D\uDD25 Exciting News! Join my Coding Journey! Subscribe Now! \uD83D\uDD25\uD83C\uDFA5\n\n\uD83D\uDD17 Link in the leetcode profile \n\nNew coding channel alert! \uD83D\uDE80\uD83D\uDCBB Subscribe to unlock amazing coding content and tutorials. Help me reach 1K subs to start posting more videos! Join now! \uD83C\uDF1F\uD83D\uDCAA\n\nThanks for your support! \uD83D\uDE4F\n# Intuition\n3 ways to solve this problem\n\n# Approach\n**1.Recursive approach**\n - Check if the current node is empty or Null.\n - Display the data part of the root (or current node)\n - Traverse the left subtree by recursively calling the preorder function.\n - Traverse the right subtree by recursively calling the preorder function.\n \n**2.Iterative approach**\n - Create an empty stack and push the root node to it.\n - Do the following while the stack is not empty\n 1. Pop the top item from the stack and display it.\n 2. Push the right child of the popped item to the stack.\n 3. Push the left child of the popped item to the stack.\n# Complexity\n - **Time complexity**:O(N)\n - **Space complexity**:O(H)H=height of binary tree\n\n **3.Morris traversal**\n - Initialize current as root\n - While current is not null:\n 1. If current does not have a left child:\n (i) Print current\'s data.\n (ii) Go to the right, i.e., current = current.right\n 2. Else:\n (i)Make current as the right child of the rightmost node in current\'s left subtree.\n (ii)Go to this left child, i.e., current = current.left.\n\n# Complexity\n- **Time complexity**:O(N)\n- **Space complexity**:O(1)\n\n\n \n![oms.png](https://assets.leetcode.com/users/images/f5a39b74-fd4e-4f2c-bfb2-7737e7f09f35_1673225202.6658852.png)\n\n# Code(Recursuve approach)\n```\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n * int val;\n * TreeNode *left;\n * TreeNode *right;\n * TreeNode() : val(0), left(nullptr), right(nullptr) {}\n * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}\n * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}\n * };\n */\nclass Solution {\npublic:\n vector<int>ans;\n vector<int> preorderTraversal(TreeNode* root) {\n if(root){\n ans.push_back(root->val);\n preorderTraversal(root->left);\n preorderTraversal(root->right);\n }\n return ans;\n }\n};\n```\n# Code(iterative approach)\n```\nclass Solution {\npublic:\n vector<int> preorderTraversal(TreeNode* root) {\n vector<int> ans;\n stack<TreeNode*>st;\n while (root || !st.empty()) {\n if (root) {\n ans.push_back(root -> val);\n if (root -> right) {\n st.push(root -> right);\n }\n root = root -> left;\n } else {\n root = st.top();\n st.pop();\n }\n }\n return ans;\n }\n};\n```\n# Code(Morris approach)\n```\nclass Solution {\npublic:\n vector<int> preorderTraversal(TreeNode* root) {\n vector<int> nodes;\n while (root) {\n if (root -> left) {\n TreeNode* pre = root -> left;\n while (pre -> right && pre -> right != root) {\n pre = pre -> right;\n }\n if (!pre -> right) {\n pre -> right = root;\n nodes.push_back(root -> val);\n root = root -> left;\n } else {\n pre -> right = NULL;\n root = root -> right;\n }\n } else {\n nodes.push_back(root -> val);\n root = root -> right;\n }\n }\n return nodes;\n }\n};\n```\n\nIf you really found my solution helpful **please upvote it**, as it motivates me to post such kind of codes.\n*Let me know in comment if i can do bette*r.\nLets connect on [LINKDIN](https://www.linkedin.com/in/mahesh-vishnoi-a4a47a193/).\n\n
97
2
['Stack', 'Recursion', 'C++']
4
binary-tree-preorder-traversal
Accepted code. Explaination with Algo.
accepted-code-explaination-with-algo-by-i69xy
Create an empty stack, Push root node to the stack.\n 2. Do following while stack is not empty.\n\n 2.1. pop an item from the stack and print it.\n \n 2.2. push
deepalaxmi
NORMAL
2014-08-23T21:24:07+00:00
2018-10-09T18:57:57.389248+00:00
15,584
false
1. Create an empty stack, Push root node to the stack.\n 2. Do following while stack is not empty.\n\n 2.1. pop an item from the stack and print it.\n \n 2.2. push the right child of popped item to stack.\n\n 2.3. push the left child of popped item to stack.\n\n \n\n\n> class Solution {\n> public:\n> vector<int> preorderTraversal(TreeNode *root) {\n> stack<TreeNode*> nodeStack;\n> vector<int> result;\n> //base case\n> if(root==NULL)\n> return result;\n> nodeStack.push(root);\n> while(!nodeStack.empty())\n> {\n> TreeNode* node= nodeStack.top();\n> result.push_back(node->val);\n> nodeStack.pop();\n> if(node->right)\n> nodeStack.push(node->right);\n> if(node->left)\n> nodeStack.push(node->left);\n> }\n> return result;\n> \n> }\n> };
78
0
[]
10
binary-tree-preorder-traversal
4 solutions in c++
4-solutions-in-c-by-gogo93-3vsc
\n // recursive, but it's trivial...\n vector preorderTraversal(TreeNode root) {\n vector v;\n preTraversal(root, v);\n return v;\n
gogo93
NORMAL
2015-08-20T07:25:45+00:00
2018-08-30T09:40:50.439971+00:00
9,756
false
\n // recursive, but it's trivial...\n vector<int> preorderTraversal(TreeNode* root) {\n vector<int> v;\n preTraversal(root, v);\n return v;\n }\n void preTraversal(TreeNode* root, vector<int>& v){\n if(!root) return;\n v.push_back(root->val);\n preTraversal(root->left, v);\n preTraversal(root->right, v);\n }\n \n \n // iterate, use stack to imitate recursive\n vector<int> preorderTraversal(TreeNode* root) {\n vector<int> v;\n if(!root) return v;\n TreeNode* temp = root;\n stack<TreeNode*> s;\n s.push(root);\n while(!s.empty()){\n temp = s.top();\n s.pop();\n v.push_back(temp->val);\n if(temp->right) s.push(temp->right);\n if(temp->left) s.push(temp->left);\n }\n }\n \n \n vector<int> preorderTraversal(TreeNode* root) {\n vector<int> v;\n if(!root) return v;\n TreeNode* temp = root;\n stack<TreeNode*> s;\n while(true){\n while(temp){\n v.push_back(temp->val);\n if(temp->right) s.push(temp->right);\n temp = temp->left;\n }\n if(s.empty()) break;\n temp = s.top();\n s.pop();\n };\n }\n \n // morris traversal\uff0c O(1) space\n vector<int> preorderTraversal(TreeNode* root) {\n vector<int> v;\n if(!root) return v;\n TreeNode* temp = root, *prev;\n while(temp){\n if(!temp->left){\n v.push_back(temp->val);\n temp = temp->right;\n }else{\n prev = temp->left;\n while(prev->right&&(prev->right != temp))\n prev = prev->right;\n if(!prev->right){\n v.push_back(temp->val);\n prev->right = temp;\n temp = temp->left;\n }else{\n prev->right = NULL;\n temp = temp->right;\n }\n }\n }\n }
60
0
['C++']
3
binary-tree-preorder-traversal
Preorder Traversal Java solution both iteration and recursion
preorder-traversal-java-solution-both-it-0aqe
// recursive\n public class Solution {\n public List<Integer> preorderTraversal(TreeNode root) {\n List<Integer> result = new ArrayList<Int
king_yl
NORMAL
2015-10-20T02:13:17+00:00
2015-10-20T02:13:17+00:00
10,588
false
// recursive\n public class Solution {\n public List<Integer> preorderTraversal(TreeNode root) {\n List<Integer> result = new ArrayList<Integer>();\n if (root != null){\n result.add(root.val);\n result.addAll(preorderTraversal(root.left));\n result.addAll(preorderTraversal(root.right));\n }\n return result;\n }\n }\n \n // iterative\n public class Solution {\n public List<Integer> preorderTraversal(TreeNode root) {\n List<Integer> result = new ArrayList<Integer>();\n if (root == null) return result;\n Stack<TreeNode> stack = new Stack<TreeNode>();\n stack.push(root);\n while (!stack.isEmpty()){\n TreeNode node = stack.pop();\n result.add(node.val);\n if (node.right != null) stack.push(node.right);\n if (node.left != null) stack.push(node.left);\n }\n return result;\n }\n }
60
0
['Java']
3
binary-tree-preorder-traversal
Python 3 || 1-10 lines, 3 versions w/example || T/S: 98% / 99%
python-3-1-10-lines-3-versions-wexample-uai3r
\nThe iterative version, with example:\n\nclass Solution:\n def preorderTraversal(self, root: TreeNode) -> list[int]:\n\n
Spaulding_
NORMAL
2023-01-09T01:19:38.642836+00:00
2024-05-22T21:09:30.701958+00:00
7,861
false
\nThe iterative version, with example:\n```\nclass Solution:\n def preorderTraversal(self, root: TreeNode) -> list[int]:\n\n # Ex: root = [1, 2,None, 3,4]\n if not root: return [] # __1\n stack, ans = [root], [] # /\n # 2\n while stack: # / \\\n node = stack.pop() # 3 4\n ans.append(node.val) #\n # node node.left node.right stack ans\n if node.right: # \u2013\u2013\u2013\u2013\u2013\u2013\u2013\u2013\u2013 \u2013\u2013\u2013\u2013\u2013\u2013\u2013\u2013\u2013 \u2013\u2013\u2013\u2013\u2013\u2013\u2013\u2013\u2013 \u2013\u2013\u2013\u2013\u2013\u2013 \u2013\u2013\u2013\u2013\u2013\u2013\n stack.append(node.right) # [1] []\n if node. left: # 1 2 None [2] [1]\n stack.append(node.left ) # 2 3 4 [4,3] [1,2]\n # 3 None None [4] [1,2,3]\n # 4 None None [4] [1,2,3,4]\n return ans \n```\n[https://leetcode.com/problems/binary-tree-preorder-traversal/submissions/577636662/](https://leetcode.com/problems/binary-tree-preorder-traversal/submissions/577636662/)\n\nI could be wrong, but I think that time complexity is *O*(*N*) and space complexity is *O*(*N*), in which *N* ~ count of nodes.\n\nThe recursive version:\n```\nclass Solution:\n def preorderTraversal(self, root: TreeNode) -> list[int]:\n\n def dfs(node):\n if not node: return\n\n ans.append(node.val)\n\n dfs(node.left)\n dfs(node.right)\n \n return \n \n ans = []\n \n dfs(root)\n\n return ans\n```\nAnd here\'s a one-liner:\n```\nclass Solution:\n def preorderTraversal(self, root: TreeNode) -> list[int]:\n\n return [] if not root else ([root.val]+\n self.preorderTraversal(root.left)+\n self.preorderTraversal(root.right))\n```\n\n
58
1
['Python', 'Python3']
2
binary-tree-preorder-traversal
Easy C++ solution using Stack
easy-c-solution-using-stack-by-yulingtia-mo3d
class Solution {\n public:\n vector<int> preorderTraversal(TreeNode *root) {\n if (root==NULL) {\n return vector<int>();\n }\n
yulingtianxia
NORMAL
2014-12-06T07:34:56+00:00
2018-10-17T15:12:18.679707+00:00
12,694
false
class Solution {\n public:\n vector<int> preorderTraversal(TreeNode *root) {\n if (root==NULL) {\n return vector<int>();\n }\n vector<int> result;\n stack<TreeNode *> treeStack;\n treeStack.push(root);\n while (!treeStack.empty()) {\n TreeNode *temp = treeStack.top();\n result.push_back(temp->val);\n treeStack.pop();\n if (temp->right!=NULL) {\n treeStack.push(temp->right);\n }\n if (temp->left!=NULL) {\n treeStack.push(temp->left);\n }\n }\n return result;\n }\n };
54
0
[]
8
binary-tree-preorder-traversal
Java Solution with Explanation
java-solution-with-explanation-by-sartha-qa38
\n\n# Approach and Explanation ( Recursive )\n Describe your approach to solving the problem. \n1. A preorder traversal is a traversal order in which the root n
Sarthak_Singh_
NORMAL
2023-01-09T04:16:13.742817+00:00
2023-01-09T04:44:42.444406+00:00
4,566
false
\n\n# Approach and Explanation ( Recursive )\n<!-- Describe your approach to solving the problem. -->\n1. A preorder traversal is a traversal order in which the root node is visited first, followed by the left subtree, and then the right subtree. `The traversal order for a node is: root, left, right.`\n\n2. The code first defines a List called result which will store the preorder traversal of the tree. It then calls a helper function traversal which takes in a TreeNode called root and the result List.\n\n3. The traversal function first checks if the root is null. If it is, it returns without doing anything. If the root is not null, it adds the root\'s value to the result List. It then calls itself recursively on the root\'s left child and then on the root\'s right child.\n\n4. This recursive function will continue until it reaches a leaf node (a node with no children), at which point it will start returning and adding the values of the nodes it traversed on the way back up the recursive stack to the result List.\n\n5. At the end of the function, the result List will contain the preorder traversal of the tree.\n\n\n# Code\n```\n/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n public List<Integer> preorderTraversal(TreeNode root) {\n // Create a list to store the traversal result\n\tList<Integer> result = new ArrayList<>();\n\t\n // Call helper method to perform the traversal\n\ttraversal(root, result);\n\t\n // Return the result\n\treturn result;\n }\n \n // Helper method to perform the preorder traversal\n public void traversal(TreeNode root, List<Integer> result) {\n // Return if the current node is null\n\tif(root == null) return;\n\t\n // Add the current node\'s value to the result list\n\tresult.add(root.val);\n\t\n // Recursively traverse the left and right subtrees\n\ttraversal(root.left, result);\n\ttraversal(root.right, result);\n }\n}\n```\n# Approach and Explanation ( Iterative )\n<!-- Describe your approach to solving the problem. -->\n\n1. This code is implementing the pre-order traversal of a binary tree. In a pre-order traversal, the root node is visited first, then the left subtree, and then the right subtree.\n\n2. The code is using a stack to store nodes as it traverses the tree. A stack is a Last-In-First-Out (LIFO) data structure, which means that the last element added to the stack will be the first one to be removed. This property is useful for implementing a tree traversal because it allows us to process the nodes in the correct order (i.e., root node before the child nodes).\n\n3. The algorithm works as follows:\n\n- Create an empty stack and an empty list to store the traversal.\n- Push the root node to the stack.\n- While the stack is not empty:\nPop the top element from the stack.\nAdd the popped element\'s value to the traversal list.\nPush the right child of the popped element to the stack.\nPush the left child of the popped element to the stack.\n- Return the traversal list.\n4. The reason why the right child is pushed to the stack before the left child is that we want to process the left subtree before the right subtree (since this is a pre-order traversal). Pushing the right child before the left child ensures that the left child will be processed first when it is popped from the stack.\n```\nclass Solution {\n // This method returns a list of integers representing the preorder traversal of a binary tree\n public List<Integer> preorderTraversal(TreeNode root) {\n // Create an empty ArrayList to store the preorder traversal\n ArrayList<Integer> result = new ArrayList<Integer>();\n // If the root is null, return the empty list\n if(root == null) \n return result;\n \n // Create a stack to store the nodes as we traverse the tree\n Stack<TreeNode> st = new Stack<TreeNode>();\n // Push the root node onto the stack\n st.push(root);\n \n // While the stack is not empty,\n while(!st.isEmpty()) {\n // Pop the top node from the stack\n TreeNode current = st.pop(); \n // Add the value of the node to the list\n result.add(current.val);\n \n // If the current node has a right child, push it onto the stack\n if(current.right != null) \n st.push(current.right);\n // If the current node has a left child, push it onto the stack\n if(current.left != null)\n st.push(current.left);\n }\n // Return the list of preorder traversal values\n return result;\n }\n}\n\n\n```\n
53
1
['Java']
2
binary-tree-preorder-traversal
132ms in JavaScript
132ms-in-javascript-by-linfongi-ktad
var preorderTraversal = function(root) {\n if (!root) return [];\n var result = [];\n var stack = [root];\n \n while(stack.length) {\n
linfongi
NORMAL
2015-05-21T01:03:21+00:00
2015-05-21T01:03:21+00:00
4,975
false
var preorderTraversal = function(root) {\n if (!root) return [];\n var result = [];\n var stack = [root];\n \n while(stack.length) {\n var node = stack.pop();\n result.push(node.val);\n if (node.right) stack.push(node.right);\n if (node.left) stack.push(node.left);\n }\n return result;\n };
48
1
['JavaScript']
4
binary-tree-preorder-traversal
3 Iterative Solutions: Stack And Morris Traversal (Complexity Explained)
3-iterative-solutions-stack-and-morris-t-ugod
1 Stack-based:\nStack-based: \njava\npublic class Solution {\n public List<Integer> preorderTraversal(TreeNode root) {\n List<Integer> res = new Array
vegito2002
NORMAL
2017-08-13T21:41:34.002000+00:00
2018-10-12T03:20:40.021825+00:00
3,635
false
### 1 Stack-based:\nStack-based: \n```java\npublic class Solution {\n public List<Integer> preorderTraversal(TreeNode root) {\n List<Integer> res = new ArrayList<>();\n if (root == null)\n return res;\n Stack<TreeNode> s = new Stack<>();\n s.push(root);\n while (!s.isEmpty()) {\n TreeNode cur = s.pop();\n res.add(cur.val);\n if (cur.right != null)\n s.push(cur.right);\n if (cur.left != null)\n s.push(cur.left);\n }\n return res;\n }\n}\n```\nPush right before left so that, due to the property of a stack, left is processed before right; This is the logic that echoes most throughout this problem's discussions, and is very easy to understand.\n\n### 2 Stack-based:\nSlight changes. \n```java\npublic class Solution {\n public List<Integer> preorderTraversal(TreeNode root) {\n List<Integer> res = new ArrayList<>();\n if (root == null)\n return res;\n Stack<TreeNode> s = new Stack<>();\n s.push(root);\n while (!s.isEmpty()) {\n TreeNode cur = s.pop();\n while (cur != null) {\n res.add(cur.val);\n s.push(cur.right);\n cur = cur.left;\n }\n }\n return res;\n }\n}\n```\nThis algorithm employs a technique I like to call "push horizontal" that is frequently used in the implementation of stack-based InOrder and PostOrder algorithm. Since PreOrder logic is generally easier than the other two, this approach is not as much used as that of solution 1. Note that here we push `cur.right` rather than `cur`. The `null` cases will handle themselves by the inner while loop.\n\n\n### 3 Morris Traversal\n```java\npublic class Solution {\n public List<Integer> preorderTraversal(TreeNode root) {\n List<Integer> res = new ArrayList<>();\n if (root == null)\n return res;\n TreeNode cur = root;\n while (cur != null) {\n if (cur.left == null) {\n res.add(cur.val);\n cur = cur.right;\n } else {\n TreeNode prev = cur.left;\n while (prev.right != null && prev.right != cur)\n prev = prev.right;\n if (prev.right == null) {\n res.add(cur.val);\n prev.right = cur;\n cur = cur.left;\n } else {\n prev.right = null;\n cur = cur.right;\n }\n }\n }\n return res;\n }\n}\n```\nA [**good explanation**](http://www.geeksforgeeks.org/inorder-tree-traversal-without-recursion-and-without-stack/) here gives implementation of Morris Traversal InOrder algorithm. The PreOrder algorithm can be achieved by tweaking the code very slightly: rather than visit `cur` when we **restore** the tree(which is generally the second time we are at node `cur`), we visit it the first time we encounter it, which is when we have to **modify**. \n\nThe space **complexity** for Morris Traversal is O(1) obviously. The time complexity is actually O(N) which is a little more subtle. The outer while loop is executed O(N) iterations obviously, depending on the position of `root` in the InOrder serialization of the tree. In each such iteration, we have to find the left predecessor for `cur`, which is the costly part. Trivially you would think that gives us `O(NlgN)` per height of the tree. But if you think aggregately, you will see these:\n* For each node, we do `find left predecessor` on it only twice.\n* Throughout these two `find left predecessor` inner while loops, each edge of the tree get traversed at most twice.\n\nYou might have to draw a tree and doodle some trace to convince yourself this. Since a tree has `N-1` edges, with `N` as the number of nodes, we know that the time complexity is O(N).
41
1
[]
6
binary-tree-preorder-traversal
Java recursive and iterative solutions.
java-recursive-and-iterative-solutions-b-qunu
\n // recursively\n public List<Integer> preorderTraversal1(TreeNode root) {\n List<Integer> ret = new ArrayList<>();\n dfs(root, ret);\
oldcodingfarmer
NORMAL
2016-05-05T15:16:15+00:00
2016-05-05T15:16:15+00:00
4,020
false
\n // recursively\n public List<Integer> preorderTraversal1(TreeNode root) {\n List<Integer> ret = new ArrayList<>();\n dfs(root, ret);\n return ret;\n }\n \n private void dfs(TreeNode root, List<Integer> ret) {\n if (root != null) {\n ret.add(root.val);\n dfs(root.left, ret);\n dfs(root.right, ret);\n }\n }\n \n // iteratively\n public List<Integer> preorderTraversal(TreeNode root) {\n List<Integer> ret = new ArrayList<>();\n Stack<TreeNode> stack = new Stack<>();\n stack.push(root);\n while (!stack.isEmpty()) {\n TreeNode node = stack.pop();\n if (node != null) {\n ret.add(node.val);\n stack.push(node.right);\n stack.push(node.left);\n }\n }\n return ret;\n }
33
0
['Recursion', 'Iterator', 'Java']
6
binary-tree-preorder-traversal
Preorder\u3001inorder\u3001postorder iterative solution by c++
preorderu3001inorderu3001postorder-itera-spe4
preorder:\n\n vector preorderTraversal(TreeNode root) {\n \tvector res;\n \tstd::stack temp;\n \twhile (root || !temp.empty()) {\n \t\twhile (roo
hustlx1
NORMAL
2016-05-03T13:22:17+00:00
2018-09-17T12:33:35.324240+00:00
4,216
false
preorder:\n\n vector<int> preorderTraversal(TreeNode* root) {\n \tvector<int> res;\n \tstd::stack<TreeNode*> temp;\n \twhile (root || !temp.empty()) {\n \t\twhile (root) {\n \t\t\ttemp.push(root);\n \t\t\tres.push_back(root->val);\n \t\t\troot = root->left;\n \t\t}\n \t\troot = temp.top();\n \t\ttemp.pop();\n \t\troot = root->right;\n \t}\n \treturn res;\n }\ninorder:\n\n vector<int> inorderTraversal(TreeNode* root) {\n \tvector<int> res;\n \tstd::stack<TreeNode*> temp;\n \twhile (root || !temp.empty()) {\n \t\twhile (root) {\n \t\t\ttemp.push(root);\n \t\t\troot = root->left;\n \t\t}\n \t\troot = temp.top();\n \t\ttemp.pop();\n \t\tres.push_back(root->val);\n \t\troot = root->right;\n \t}\n \treturn res;\n }\n\npostorder:\n\n vector<int> postorderTraversal(TreeNode* root) {\n \tvector<int> res;\n \tstd::stack<TreeNode*> temp;\n \twhile (root || !temp.empty()) {\n \t\twhile (root) {\n \t\t\ttemp.push(root);\n \t\t\tres.insert(res.begin(),root->val);\n \t\t\troot = root->right;\n \t\t}\n \t\troot = temp.top();\n \t\ttemp.pop();\n \t\troot = root->left;\n \t}\n \treturn res;\n }
31
0
[]
2
binary-tree-preorder-traversal
C++ Solution || 100% faster || Iterative Solution
c-solution-100-faster-iterative-solution-2rmz
\nclass Solution {\npublic:\n vector<int> preorderTraversal(TreeNode* root) {\n vector<int> preorder;\n stack<TreeNode*> stack;\n if (ro
AlankarSaxena2712
NORMAL
2021-07-13T11:12:58.592023+00:00
2021-07-13T11:13:29.709375+00:00
3,445
false
```\nclass Solution {\npublic:\n vector<int> preorderTraversal(TreeNode* root) {\n vector<int> preorder;\n stack<TreeNode*> stack;\n if (root == NULL)\n return preorder;\n stack.push(root);\n while(!stack.empty()) {\n TreeNode* curr = stack.top();\n stack.pop();\n preorder.push_back(curr->val);\n if (curr->right != NULL)\n stack.push(curr->right);\n if (curr->left != NULL)\n stack.push(curr->left);\n }\n return preorder;\n }\n};\n```
26
0
['Stack', 'C', 'Iterator', 'C++']
5
binary-tree-preorder-traversal
3 Simple Python solutions
3-simple-python-solutions-by-shraddhapp-ggnc
Solution 1: Preorder traversal with stack\n\n\nclass Solution:\n def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:\n ans = []\n
shraddhapp
NORMAL
2021-08-14T17:29:22.400501+00:00
2021-08-14T17:30:04.534860+00:00
3,067
false
##### Solution 1: Preorder traversal with stack\n\n```\nclass Solution:\n def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:\n ans = []\n stack = [root]\n \n while stack:\n temp = stack.pop()\n \n if temp:\n ans.append(temp.val)\n stack.append(temp.right) #as we are using stack which works on LIFO, we need to push right tree first so that left will be popped out\n stack.append(temp.left)\n \n return ans\n```\n\n\n##### Solution 2: With recursion for python beginners\n```\nclass Solution:\n def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:\n ans = []\n if not root:\n return ans\n \n def preorder(node):\n if node:\n ans.append(node.val)\n preorder(node.left)\n preorder(node.right)\n \n preorder(root)\n return ans\n```\n\n##### Solution 3: Short solution\n```\nclass Solution:\n def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:\n if not root:\n return []\n \n return [root.val] + self.preorderTraversal(root.left) + self.preorderTraversal(root.right)\n```
25
1
['Stack', 'Recursion', 'Python', 'Python3']
2
binary-tree-preorder-traversal
Python recursive and iterative solutions
python-recursive-and-iterative-solutions-z34v
Please see and vote for my solutions for these similar problems.\n94. Binary Tree Inorder Traversal\n144. Binary Tree Preorder Traversal\n145. Binary Tree Posto
otoc
NORMAL
2019-07-11T05:19:34.651622+00:00
2019-07-11T05:52:34.499313+00:00
3,457
false
Please see and vote for my solutions for these similar problems.\n[94. Binary Tree Inorder Traversal](https://leetcode.com/problems/binary-tree-inorder-traversal/discuss/332283/Python-recursive-and-iterative-solutions)\n[144. Binary Tree Preorder Traversal](https://leetcode.com/problems/binary-tree-preorder-traversal/discuss/332277/Python-recursive-and-iterative-solutions)\n[145. Binary Tree Postorder Traversal](https://leetcode.com/problems/binary-tree-postorder-traversal/discuss/332286/Python-recursive-and-iterative-solutions)\n\nRecursive solution:\n```\n def preorderTraversal(self, root: TreeNode) -> List[int]:\n def dfs(node):\n if not node:\n return\n pre_order.append(node.val)\n dfs(node.left)\n dfs(node.right)\n \n pre_order = []\n dfs(root)\n return pre_order\n```\n\nIterative solution:\n```\n def preorderTraversal(self, root: TreeNode) -> List[int]:\n if not root:\n return []\n pre_order = []\n stack = [root]\n while stack:\n top = stack.pop()\n pre_order.append(top.val)\n if top.right:\n stack.append(top.right)\n if top.left:\n stack.append(top.left)\n return pre_order\n```
25
0
[]
3
binary-tree-preorder-traversal
✅ 🔥 0 ms Runtime Beats 100% User🔥|| Code Idea ✅ || Algorithm & Solving Step ✅ ||
0-ms-runtime-beats-100-user-code-idea-al-5stm
\n\n\u2705 IF YOU LIKE THIS SOLUTION, PLEASE UPVOTE AT THE END \u2705 :\n# I prefer Iterative Approach:\n\n### Intuition:\nPreorder traversal of a binary tree
Letssoumen
NORMAL
2024-12-04T00:23:01.820310+00:00
2024-12-04T00:23:01.820350+00:00
4,096
false
![Screenshot 2024-12-04 at 5.47.19\u202FAM.png](https://assets.leetcode.com/users/images/e1057879-14a1-4b5f-b514-60e4a12f1e46_1733271480.7984586.png)\n\n\u2705 IF YOU LIKE THIS SOLUTION, PLEASE UPVOTE AT THE END \u2705 :\n# I prefer Iterative Approach:\n\n### **Intuition:**\nPreorder traversal of a binary tree visits nodes in the following order:\n1. **Root** node.\n2. **Left subtree**.\n3. **Right subtree**.\n\nThis traversal is useful when you need to create a prefix notation or evaluate expressions stored in trees.\n\n---\n\n### **Approach 1: Recursive Solution**\nA straightforward way to implement preorder traversal is by using recursion.\n\n---\n\n### **Algorithm:**\n1. Start with the root node.\n2. Visit the root.\n3. Recursively traverse the left subtree.\n4. Recursively traverse the right subtree.\n\n---\n\n### **Steps in Code (Python, C++, Java)**\n\n#### **Python - Recursive Approach:**\n\n```python\nclass Solution:\n def preorderTraversal(self, root: TreeNode) -> list[int]:\n result = []\n \n def dfs(node):\n if not node:\n return\n result.append(node.val) # Visit root\n dfs(node.left) # Traverse left subtree\n dfs(node.right) # Traverse right subtree\n \n dfs(root)\n return result\n```\n\n---\n\n#### **C++ - Recursive Approach:**\n\n```cpp\nclass Solution {\npublic:\n vector<int> preorderTraversal(TreeNode* root) {\n vector<int> result;\n dfs(root, result);\n return result;\n }\n \n void dfs(TreeNode* node, vector<int>& result) {\n if (!node) return;\n result.push_back(node->val); // Visit root\n dfs(node->left, result); // Traverse left subtree\n dfs(node->right, result); // Traverse right subtree\n }\n};\n```\n\n---\n\n#### **Java - Recursive Approach:**\n\n```java\nimport java.util.*;\nclass Solution {\n public List<Integer> preorderTraversal(TreeNode root) {\n List<Integer> result = new ArrayList<>();\n dfs(root, result);\n return result;\n }\n \n private void dfs(TreeNode node, List<Integer> result) {\n if (node == null) return;\n result.add(node.val); // Visit root\n dfs(node.left, result); // Traverse left subtree\n dfs(node.right, result); // Traverse right subtree\n }\n}\n```\n\n---\n\n### **Approach 2: Iterative Solution Using Stack**\nTo avoid recursion, we can use a stack to mimic the function call stack.\n\n---\n\n### **Algorithm:**\n1. Initialize a stack with the root node.\n2. While the stack is not empty:\n - Pop the node and visit it.\n - Push its right child (if any).\n - Push its left child (if any).\n3. Return the result.\n\n---\n\n#### **Python - Iterative Approach:**\n\n```python\nclass Solution:\n def preorderTraversal(self, root: TreeNode) -> list[int]:\n if not root:\n return []\n \n stack = [root]\n result = []\n \n while stack:\n node = stack.pop()\n result.append(node.val) # Visit node\n \n if node.right:\n stack.append(node.right) # Push right child\n if node.left:\n stack.append(node.left) # Push left child\n \n return result\n```\n\n---\n\n#### **C++ - Iterative Approach:**\n\n```cpp\n#include <vector>\n#include <stack>\nusing namespace std;\n\nclass Solution {\npublic:\n vector<int> preorderTraversal(TreeNode* root) {\n vector<int> result;\n if (!root) return result;\n \n stack<TreeNode*> s;\n s.push(root);\n \n while (!s.empty()) {\n TreeNode* node = s.top();\n s.pop();\n result.push_back(node->val); // Visit node\n \n if (node->right) s.push(node->right); // Push right child\n if (node->left) s.push(node->left); // Push left child\n }\n return result;\n }\n};\n```\n\n---\n\n#### **Java - Iterative Approach:**\n\n```java\nimport java.util.*;\n\nclass Solution {\n public List<Integer> preorderTraversal(TreeNode root) {\n List<Integer> result = new ArrayList<>();\n if (root == null) return result;\n \n Stack<TreeNode> stack = new Stack<>();\n stack.push(root);\n \n while (!stack.isEmpty()) {\n TreeNode node = stack.pop();\n result.add(node.val); // Visit node\n \n if (node.right != null) stack.push(node.right); // Push right child\n if (node.left != null) stack.push(node.left); // Push left child\n }\n \n return result;\n }\n}\n```\n\n---\n\n### **Time Complexity:**\n- **DFS (Recursive and Iterative)**: O(n), where n is the number of nodes in the tree. Each node is visited once.\n \n### **Space Complexity:**\n- **Recursive DFS**: O(h), where h is the height of the tree (due to the call stack).\n- **Iterative DFS**: O(h), where h is the height of the tree (due to the stack).\n\n### **Example Walkthrough:**\nFor the input `root = [1, null, 2, 3]`, the traversal proceeds as:\n1. Visit `1`\n2. Move to the right, visit `2`\n3. Move to the left, visit `3`\n\nOutput: `[1, 2, 3]`.\n\n\n\n![image.png](https://assets.leetcode.com/users/images/afd4681f-a28a-438d-bdc1-a6f9dc6c4e3a_1733271763.5887356.png)\n
23
1
['Stack', 'Tree', 'C++', 'Java', 'Python3']
0
binary-tree-preorder-traversal
C++ recursive simple solution || 0 ms, 100% faster
c-recursive-simple-solution-0-ms-100-fas-bht7
C++ :\n\n\nvoid preorderTraversalHelper(TreeNode* root, vector<int> &res) {\n\tif(root)\n\t{\n\t\tres.push_back(root -> val); \n\n\t\tif(root -> left)
TovAm
NORMAL
2021-10-07T10:54:16.705950+00:00
2021-10-07T10:54:16.705984+00:00
1,997
false
**C++ :**\n\n```\nvoid preorderTraversalHelper(TreeNode* root, vector<int> &res) {\n\tif(root)\n\t{\n\t\tres.push_back(root -> val); \n\n\t\tif(root -> left)\n\t\t\tpreorderTraversalHelper(root -> left, res);\n\n\t\tif(root -> right)\n\t\t\tpreorderTraversalHelper(root -> right, res);\n\t}\n\n\treturn;\n}\n\n\nvector<int> preorderTraversal(TreeNode* root) \n{ \n\tvector<int> res;\n\tpreorderTraversalHelper(root, res) ;\n\treturn res;\n}\n```\n\n**Like it ? please upvote !**
23
1
['Recursion', 'C', 'C++']
3
binary-tree-preorder-traversal
Easy C++ Solution with Explaination
easy-c-solution-with-explaination-by-lon-5jvg
AN UPVOTE WOULD BE HIGHLY APPRECIATED !!!\n\nOverload the comments section with doubts and praises if you have.!!!\n\nTime Complexity: O(n)\nSpace Complexity: O
Longhorn_65
NORMAL
2021-05-29T12:48:49.170617+00:00
2021-05-29T12:49:46.326568+00:00
1,155
false
**AN UPVOTE WOULD BE HIGHLY APPRECIATED !!!**\n\n*Overload the comments section with doubts and praises if you have.!!!*\n\nTime Complexity: O(n)\nSpace Complexity: O(n)\n\n```\nclass Solution {\npublic:\n// Declairing global variable *ans* so that we don\'t declare it again and again and affect the SC by some factors\n vector<int> ans;\n \n\t// Find the preorder sequence\n void preorder(TreeNode* root) {\n if(root==NULL) {\n return;\n }\n ans.push_back(root->val);\n preorder(root->left);\n preorder(root->right); \n }\n \n // Recieve the preorder sequence from *preorder()* and return it\n vector<int> preorderTraversal(TreeNode* root) {\n \n preorder(root);\n return ans;\n }\n};\n```
21
1
['C', 'C++']
2