LeetCode 3127: Make a Square with the Same Color Solution
Master LeetCode problem 3127 (Make a Square with the Same Color), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
3127. Make a Square with the Same Color
Problem Explanation
Explanation
To solve this problem, we need to check if there is already a 2 x 2 square of the same color in the given 3 x 3 grid. If there is, we return true. If there isn't, we need to check if it is possible to change the color of at most one cell to create a 2 x 2 square of the same color.
We can iterate over all possible 2 x 2 squares in the grid and check if they are already of the same color. If they are, we return true. If not, we check if there is only one cell with a different color in the 2 x 2 square. If there is exactly one cell with a different color, we can change the color of that cell to create a 2 x 2 square of the same color. In all other cases, we return false.
- Time complexity: O(1) since we are always iterating over a fixed 3 x 3 grid.
- Space complexity: O(1) since we are not using any extra space.
Solution Code
class Solution {
public boolean make2x2Square(char[][] grid) {
int countB = 0, countW = 0;
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
if (grid[i][j] == 'B') countB++;
else countW++;
}
}
if (countB == 0 || countW == 0 || countB == 4 || countW == 4) return true;
if (countB == 1 || countW == 1) return true;
return false;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 3127 (Make a Square with the Same Color)?
This page provides optimized solutions for LeetCode problem 3127 (Make a Square with the Same Color) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 3127 (Make a Square with the Same Color)?
The time complexity for LeetCode 3127 (Make a Square with the Same Color) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 3127 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 3127 in Java, C++, or Python.