Possible number of Rectangle and Squares with the given set of elements


Given ‘N’ number of sticks of length a1, a2, a3…an. The task is to count the number of squares and rectangles possible.

Note: One stick should be used only once i.e. either in any of the squares or rectangles.


Input: arr[] = {1, 2, 1, 2}
Output: 1
Rectangle with sides 1 1 2 2

Input: arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9}
Output: 0
No square or rectangle is possible

Approach: Below is the step by step algorithm to solve this problem :

  1. Initialize the number of sticks.
  2. Initialize all the sticks with it’s lengths in an array.
  3. Sort the array in an increasing order.
  4. Calculate the number of pairs of sticks with the same length.
  5. Divide the total number of pairs by 2, which will be the total possible rectangle and square.

Below is the implementation of above approach:

// C++ implementation of above approach
#include <bits/stdc++.h>
using namespace std;
// Function to find the possible
// rectangles and squares
int rectangleSquare(int arr[], int n)
    // sort all the sticks
    sort(arr, arr + n);
    int count = 0;
    // calculate all the pair of
    // sticks with same length
    for (int i = 0; i < n - 1; i++) {
        if (arr[i] == arr[i + 1]) {
    // divide the total number of pair
    // which will be the number of possible
    // rectangle and square
    return count / 2;
// Driver code
int main()
    // initialize all the stick lengths
    int arr[] = { 2, 2, 4, 4, 4, 4, 6, 6, 6, 7, 7, 9, 9 };
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << rectangleSquare(arr, n);
    return 0;

My Personal Notes

Recommended Posts:

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the “Improve Article” button below.

Article Tags :

Practice Tags :

Be the First to upvote.
Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.

Let’s block ads! (Why?)

from My Reading List: Read and Unread https://ift.tt/2Oke6hK


Please enter your comment!
Please enter your name here