Is Rectangle? | InterviewBit | Solution Explained

I present the solutions to Is Rectangle in Python3 using multiple approaches. Problem Link.

Logic

There’s just one key point to note: In a rectangle, of 4 sides, 2 pairs of 2 have to be equal OR all are equal. Take for example: 2, 2, 4, 4 case. Here, 2 simply represents the shorter side – and we need two of those. Similarly, 4 represents the longer side, and we need 2 of those too.

Is Rectangle: example test case
Is Rectangle: example test case

One interesting point is that all the sides can be same as well. That is, a case of 3, 3, 3, 3 is also a rectangle – since all squares are also rectangles.

Approach 1: Sort

class Solution:
    def solve(self, A, B, C, D):
        a = [A, B, C, D]
        a.sort()
        return int(a[0] == a[1] and a[2] == a[3])

Approach 2: Frequencies

We measure the frequencies of each count. If we have a side with odd count, it means we don’t have anything to pair it up with. So, we can return False.

 Is Rectangle: a sample case, since odd frequencies won't work
Is Rectangle: a sample case, since odd frequencies won’t work
from collections import Counter

class Solution:
    def solve(self, A, B, C, D):
        d = Counter([A, B, C, D])
        for v in d.values():
            if v & 1: return 0 # if some count of numbers is odd, then its an issue
        return 1

Avatar for Tanishq Chaudhary

Producing high-quality intuitive explanations of interview problems. Currently covering LeetCode and InterviewBit.

    Comments

    1. Please write the proof.

    2. This solution need an amendment for 2 digit number.

    3. Please write a Proof for this

    Leave a Reply

    Your email address will not be published. Required fields are marked *

    This site uses Akismet to reduce spam. Learn how your comment data is processed.