Leetcode 1637. Widest Vertical Area Between Two Points Containing No Points
Given n
points on a 2D plane, where points[i] = [xi, yi]
, return the widest vertical area between two points such that no points are inside the area. A vertical area is defined as an area of width w
where no points lie inside the area. Formally, a vertical area is defined by two parallel lines x = a
and x = b
where there are no points with x-coordinate
in the range (a, b)
, and a < b
.
Before diving into the solution, let’s clarify the problem requirements:
xi
and yi
?
-10^9 <= xi, yi <= 10^9
.[xi, yi]
is unique as implied by the problem statement.0
.To find the widest vertical area, we can leverage the following strategy:
import java.util.Arrays;
public class Solution {
public int maxWidthOfVerticalArea(int[][] points) {
// Edge case: when the number of points is less than 2
if (points.length < 2) {
return 0;
}
// Extracting the x-coordinates
int[] xCoords = new int[points.length];
for (int i = 0; i < points.length; i++) {
xCoords[i] = points[i][0];
}
// Sorting the x-coordinates
Arrays.sort(xCoords);
// Finding the maximum gap between consecutive x-coordinates
int maxGap = 0;
for (int i = 1; i < xCoords.length; i++) {
int gap = xCoords[i] - xCoords[i - 1];
if (gap > maxGap) {
maxGap = gap;
}
}
return maxGap;
}
public static void main(String[] args) {
Solution solution = new Solution();
int[][] points = { {8,7}, {9,9}, {7,4}, {9,7} };
System.out.println(solution.maxWidthOfVerticalArea(points)); // Output: 1
}
}
O(n log n)
time complexity where n
is the number of points.O(n)
, as we iterate through the sorted coordinates.Therefore, the overall time complexity is dominated by the sorting step and is O(n log n)
.
This solution effectively handles the problem by focusing on sorting the x-coordinates and then finding the maximum gap between successive coordinates. This approach ensures that we cover all potential vertical areas efficiently.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?