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 width of the widest vertical area between two points such that no points are inside the area.
A vertical area is an area of the plane where all points have different x-coordinates but have the same y-coordinate, and the width of a vertical area is the absolute difference between the x-coordinates of the two edges.
points
)?
points
array can have a size anywhere from 2 to 10^5 elements.Extract X-Coordinates: Focus on the x-coordinates since vertical areas are concerned with their differences.
Sort X-Coordinates: Sorting the list of x-coordinates allows us to easily calculate the differences between consecutive x-coordinates.
Compute Maximum Difference: Iterate through the sorted list of x-coordinates and compute the differences between consecutive elements, maintaining the maximum difference.
Here’s the possible C++ implementation of the solution:
#include <vector>
#include <algorithm>
class Solution {
public:
int maxWidthOfVerticalArea(std::vector<std::vector<int>>& points) {
// Extract x-coordinates
std::vector<int> xCoords;
for (const auto& point : points) {
xCoords.push_back(point[0]);
}
// Sort the x-coordinates
std::sort(xCoords.begin(), xCoords.end());
// Calculate the maximum difference between consecutive x-coordinates
int maxWidth = 0;
for (size_t i = 1; i < xCoords.size(); ++i) {
maxWidth = std::max(maxWidth, xCoords[i] - xCoords[i - 1]);
}
return maxWidth;
}
};
Thus, the overall time complexity is dominated by the sorting step, which results in (O(n \log n)).
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?