Skip to main content

Find the Number of Ways to Place People II - Solution & Explanation

HardArrayMathGeometrySorting23 min readAsked at: Meta, Uber, Google
Practice this problem

Problem Statement

You are given a 2D array points of size n x 2 representing integer coordinates of some points on a 2D-plane, where points[i] = [xi, yi].

We define the right direction as positive x-axis (increasing x-coordinate) and the left direction as negative x-axis (decreasing x-coordinate). Similarly, we define the up direction as positive y-axis (increasing y-coordinate) and the down direction as negative y-axis (decreasing y-coordinate)

You have to place n people, including Alice and Bob, at these points such that there is exactly one person at every point. Alice wants to be alone with Bob, so Alice will build a rectangular fence with Alice's position as the upper left corner and Bob's position as the lower right corner of the fence (Note that the fence might not enclose any area, i.e. it can be a line). If any person other than Alice and Bob is either inside the fence or on the fence, Alice will be sad.

Return the number of pairs of points where you can place Alice and Bob, such that Alice does not become sad on building the fence.

Note that Alice can only build a fence with Alice's position as the upper left corner, and Bob's position as the lower right corner. For example, Alice cannot build either of the fences in the picture below with four corners (1, 1), (1, 3), (3, 1), and (3, 3), because:

  • With Alice at (3, 3) and Bob at (1, 1), Alice's position is not the upper left corner and Bob's position is not the lower right corner of the fence.
  • With Alice at (1, 3) and Bob at (1, 1), Bob's position is not the lower right corner of the fence.

 

Example 1:

Input: points = [[1,1],[2,2],[3,3]]
Output: 0
Explanation: There is no way to place Alice and Bob such that Alice can build a fence with Alice's position as the upper left corner and Bob's position as the lower right corner. Hence we return 0. 

Example 2:

Input: points = [[6,2],[4,4],[2,6]]
Output: 2
Explanation: There are two ways to place Alice and Bob such that Alice will not be sad:
- Place Alice at (4, 4) and Bob at (6, 2).
- Place Alice at (2, 6) and Bob at (4, 4).
You cannot place Alice at (2, 6) and Bob at (6, 2) because the person at (4, 4) will be inside the fence.

Example 3:

Input: points = [[3,1],[1,3],[1,1]]
Output: 2
Explanation: There are two ways to place Alice and Bob such that Alice will not be sad:
- Place Alice at (1, 1) and Bob at (3, 1).
- Place Alice at (1, 3) and Bob at (1, 1).
You cannot place Alice at (1, 3) and Bob at (3, 1) because the person at (1, 1) will be on the fence.
Note that it does not matter if the fence encloses any area, the first and second fences in the image are valid.

 

Constraints:

  • 2 <= n <= 1000
  • points[i].length == 2
  • -109 <= points[i][0], points[i][1] <= 109
  • All points[i] are distinct.

Approach Overview

Problem Overview: You are given coordinates of people on a 2D grid. Count how many ordered pairs can form the top-left and bottom-right corners of a rectangle such that no other person lies inside or on the boundary of that rectangle. The task is essentially checking geometric relationships between pairs of points while ensuring the rectangle they form is empty.

Approach 1: Brute Force Enumeration (O(n^3) time, O(1) space)

The most direct approach checks every pair of people as potential rectangle corners. For each pair (i, j), first verify that the coordinates form a valid top-left and bottom-right relationship: x[i] ≤ x[j] and y[i] ≥ y[j]. If the pair qualifies, iterate through all other points and check whether any point lies inside or on the rectangle defined by those two corners. If no such point exists, the pair contributes one valid configuration.

This method relies purely on enumeration using basic array iteration and simple geometry checks. While easy to reason about, it performs three nested scans and becomes slow when the number of points grows.

Approach 2: Optimized with Sorting and Sweep (O(n^2) time, O(1) space)

A key observation eliminates the need to check every interior point explicitly. Sort all coordinates by x in ascending order, and for ties sort by y in descending order. Fix a person i as the potential top-left corner, then scan candidates j > i as bottom-right corners.

During this scan maintain a variable maxY representing the highest y value encountered so far that is still below or equal to y[i]. When visiting a new point j, it forms a valid pair only if y[j] ≤ y[i] and y[j] > maxY. The first condition ensures the rectangle orientation is correct. The second guarantees no previously processed point lies inside the rectangle. Once counted, update maxY to y[j].

This works because sorting by x ensures every candidate lies to the right of i. Tracking the highest blocking y prevents counting rectangles that would contain another person. The approach combines sorting with controlled enumeration to remove the inner validation loop.

Recommended for interviews: Interviewers usually expect the sorted sweep approach. Starting with the brute force solution shows you understand the geometric constraints, but recognizing that sorting by x and tracking the next valid y eliminates the third loop demonstrates stronger algorithmic reasoning.

Approach 1: Brute Force Approach

The brute force approach involves checking all possible pairs of points to see if they can form a valid rectangle such that the rectangle does not contain any other points. We define Alice's position as the upper-left corner and Bob's position as the lower-right corner.

For every pair of points, we determine if the current point can serve as Alice's position and the other as Bob's position. We ensure the rectangle formed by these positions doesn't contain any other points.

This C program iteratively selects pairs of points and checks if they can represent valid positions for Alice and Bob. Additional checks are implemented to ensure that no other point falls inside the fenced area. The function finally returns the count of all such valid pairings.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

The time complexity is O(n^3) due to the need to check each point for inclusion in the rectangle formed by every pair of selected points. The space complexity is O(1) as no additional space, apart from counters, is used.

Try this approach in the editor →

Approach 2: Optimized Approach with Sorting

In this approach, we improve the performance by means of sorting. By sorting points based on their x and y coordinates, we can reduce the number of pairs we need to check. Specifically, for a given point, we only need to check those points that lie on its 'down-right'.

First, we sort the points based on their X-coordinates. With X being sorted, the position when scanning for 'up-left' and 'down-right' becomes clear. For each point, select pairs only involving those after this point in a sorted state.

This C solution sorts the points, then attempts to check minimal pairs possible by scanning newer positions that fall in the designated quadrant, significantly reducing the evaluations needed by eliminating pre-sorted areas of potential mismatch.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time complexity reduced to O(n^2 log n). Sorting takes O(n log n), and evaluating pair-specific scenarios occurs in O(n^2). Space remains at O(n) for pointers to store initial references.

Try this approach in the editor →

Approach 3: Sorting and Classification

First, we sort the array. Then, we can classify the results based on the properties of a triangle.

  • If the sum of the two smaller numbers is less than or equal to the largest number, it cannot form a triangle. Return "Invalid".
  • If the three numbers are equal, it is an equilateral triangle. Return "Equilateral".
  • If two numbers are equal, it is an isosceles triangle. Return "Isosceles".
  • If none of the above conditions are met, it is a scalene triangle. Return "Scalene".

The time complexity is O(1), and the space complexity is O(1).

Code

Python

Java

C++

Go

TypeScript

Rust

C#

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
Brute Force Approach

The time complexity is O(n^3) due to the need to check each point for inclusion in the rectangle formed by every pair of selected points. The space complexity is O(1) as no additional space, apart from counters, is used.

Optimized Approach with Sorting

Time complexity reduced to O(n^2 log n). Sorting takes O(n log n), and evaluating pair-specific scenarios occurs in O(n^2). Space remains at O(n) for pointers to store initial references.

Sorting and Classification—

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Brute Force Pair + Interior CheckO(n^3)O(1)Best for understanding the geometric constraints and validating logic on small inputs
Sorting + Controlled EnumerationO(n^2)O(1)Preferred solution for interviews and competitive programming with moderate input sizes

Video Solution

Find the Number of Ways to Place People II | Same as Part I | Leetcode 3027 | codestorywithMIK • codestorywithMIK • 4,868 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is Find the Number of Ways to Place People II easy or hard?
LeetCode classifies this problem as Hard because the geometric constraint is subtle and the naive solution is inefficient. Recognizing that sorting and maintaining a blocking y boundary eliminates the inner validation loop is the key difficulty.
Find the Number of Ways to Place People II Python/Java solution
Python and Java implementations typically follow the same pattern: sort the coordinate array, iterate each point as a potential top-left corner, and track a running maximum y value while scanning candidates to the right. The optimized implementation runs in O(n^2) time.
How to solve Find the Number of Ways to Place People II in O(n^2)?
First sort all points by x coordinate in ascending order and by y in descending order for ties. For each point treated as the top-left corner, scan points to the right and track the maximum y encountered that is still below the starting point. Count a pair only when the candidate's y is within bounds and larger than the current blocking value.
What is the best approach for Find the Number of Ways to Place People II?
The most effective approach sorts points by x ascending and y descending, then scans possible pairs while tracking the highest valid y encountered so far. This avoids checking every interior point explicitly and reduces the complexity to O(n^2) time with O(1) extra space.
Is Find the Number of Ways to Place People II asked at Google/Amazon/Meta?
Geometry and coordinate-pair counting problems like this frequently appear in interviews at companies such as Google, Amazon, and Meta. They test sorting strategies, spatial reasoning, and the ability to optimize naive enumeration approaches.
What data structure is used in Find the Number of Ways to Place People II?
The problem primarily uses arrays to store coordinates and relies on sorting combined with simple variable tracking during iteration. No advanced data structures are required beyond ordered traversal of the sorted points.
What is the time complexity of Find the Number of Ways to Place People II?
The brute force solution runs in O(n^3) time because it checks every pair and scans all remaining points for conflicts. The optimized solution sorts the points and performs a quadratic scan, resulting in O(n^2) time and constant extra space.

Ready to solve this problem?

Practice Find the Number of Ways to Place People II with our built-in code editor and test cases.

Practice on FleetCode