
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check if any square (with one colored cell) can be divided into two equal parts in Python
Dividing a Square into two Equal Parts
In this article, we are given a square of size n*n with exactly one cell coloured. The task is to determine whether this square can be divided into two equal splits by making a single straight cut along the square, ensuring that the coloured cell lies entirely within one of the splits.
Two equal splits here indicate that both parts must contain the same number of cells, which is possible if the square side length is even. In this article we are not only checking whether the split is possible but also whether the position of the coloured cell allows such split without being intersected by the cut.
Scenario 1
Input: n = 4 a = 2 b = 3 Output: YES Explanation: Here, the square is 4*4, so it can be divided equally (even length). The horizontal cut between rows 2 and 3 creates two equal splits of 8 cells each. The coloured cell is at (2,3), which is in the upper half, so the cut does not intersect it. Hence the answer is "Yes".
Scenario 2
Input: n = 5 a = 3 b = 2 Output: NO Explanation: Here, the square is 5*5, which has an odd side length. An equal split into two parts is not possible because each half have a fractional number of cells. Therefore the answer is "No".
Program to Divide a Square into Equal Parts
In the following example, we are going to check whether in the given input any square can be divided into two equal parts:
def demo(n, a, b): if n % 2 != 0: return "NO" mid_row = n // 2 mid_col = n // 2 if a <= mid_row or a > mid_row: if a != mid_row: return "YES" if b <= mid_col or b > mid_col: if b != mid_col: return "YES" return "NO" print(demo(4, 2, 3)) print(demo(5, 3, 2))
Following is the output of the above program:
YES NO
Conclusion
By considering the middle row and column as the cut lines, we can solve the task efficiently in O(1) time complexity.