VOOZH about

URL: https://www.geeksforgeeks.org/dsa/make-n-pairs-from-array-as-x-y-coordinate-point-that-are-enclosed-inside-a-minimum-area-rectangle/

⇱ Make N pairs from Array as (X, Y) coordinate point that are enclosed inside a minimum area rectangle - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Make N pairs from Array as (X, Y) coordinate point that are enclosed inside a minimum area rectangle

Last Updated : 23 Jul, 2025

Given a number N, and an array A[] of size 2N, the task is to make N pairs of these array elements and place them on an X-Y coordinate plane, such that they are enclosed inside a minimum area rectangle( with sides parallel to the X-axis and Y-axis) and print the area of the rectangle.

Examples:

Input: N = 4, A = {1, 4, 2, 5, 3, 6, 7, 8}
Output: 9
Explanation: One possible way of making N pairs to get minimum rectangle area is {(1, 5), (2, 7), (3, 6), (4, 8)}
The minimum area rectangle has been shown in the following diagram:

👁 Image

Note: There maybe other ways to make N pairs such that the area remains minimum, but the minimum area remains 9.

Input: N = 3, A = {1, 3, 1, 1, 2, 1}
Output: 0

Approach: The area of the rectangle with the bottom-left corner in (X1, Y1) and top-right corner in (X2, Y2) would be (X2 - X1)*(Y2 - Y1). Thus, the task can be presented as partitioning the array A into two N-sized partitions say X and Y, such that (Max(X) - Min(X)) * (Max(Y) - Min(Y)) is minimized. Here, X represents the X-coordinates of the pairs and Y represents the Y-coordinates.

After sorting A, the minimum would be A1, and the maximum would be A2N. Now, there can be the following two cases:

  • Both A1 and A2N are present in the same partition, say X.The area of the rectangle would be (A2N - A1) * (Max(Y) - Min(Y)). Then the task would be to minimize Max(Y) - Min(Y). Also, if i is the index of Min(Y) and j is the index of Max(Y), then j - i >= N - 1, as there has to be at least N elements in Y. Thus, it is optimal to use a segment of size N for Y(barring A1 and A2N, as they already have been taken),
  • A1 and A2N are present in different partitions. For this case, it would be optimal to use a prefix of size N, and a suffix of size N as the partitions, i.e placing the first N elements in one partition and the last N elements in the other.       

Follow the steps below to solve the problem:

  • Initialize a variable say, ans to store the minimum area of the rectangle.
  • Sort the array A[] in ascending order.
  • For the first case:
    • Update ans as (A[N - 1] - A[0]) * (A[2 * N - 1] - A[N]).
  • For the second case:
    • Iterate in the range [1, N-1] using the variable i: 
      • Update ans as the minimum of ans and (A[2 * N - 1] - A[0]) * (A[i + N - 1] - A[i]).
  • Finally, return ans.

Below is an implementation of the above code:


Output
9

Time Complexity: O(NLogN)
Auxiliary Space: O(1)


 

Comment
Article Tags:
Article Tags: