Given a list of 2D points points, each an [x, y] pair, that may contain duplicates, and an integer k, return the top k most frequent points.
If two points have the same frequency, the point closer to the origin (0, 0) ranks higher. If both frequency and distance are the same, the point with the smaller x-coordinate comes first. If the x-coordinates are also the same, the point with the smaller y-coordinate comes first.
Return the result sorted by these ranking criteria.
Function Signature
def top_k_points(points: list[list[int]], k: int) -> list[list[int]]:
Rules
-
Each element of
points
is a list of two integers
[x, y]
. Equal pairs are the same point, and every occurrence adds one to that point's frequency.
-
Distance to the origin is Euclidean distance. Comparing squared distances
x*x + y*y
gives the same order.
-
The output holds
k
distinct points, each as a two-element list
[x, y]
, ordered by frequency descending, then distance ascending, then x ascending, then y ascending.
Constraints
-
1 <= len(points) <= 10^5
-
-10^4 <= points[i][0], points[i][1] <= 10^4
-
1 <= k <=
the number of distinct points in
points
Examples
Input: points = [[1,2],[3,4],[1,2],[1,2],[3,4],[0,1]], k = 2
Output: [[1,2],[3,4]]
Point [1,2] appears 3 times, [3,4] twice and [0,1] once, so the two most frequent points are [1,2] and [3,4], in that order.
Input: points = [[1,0],[0,1],[1,0],[0,1],[-1,0]], k = 2
Output: [[0,1],[1,0]]
[1,0] and [0,1] both appear twice and both have squared distance 1, so the smaller x-coordinate puts [0,1] first. [-1,0] appears only once, so it ranks third even though its x-coordinate is the smallest.
Input: points = [[3,0],[3,0],[0,-2],[0,2],[1,1]], k = 3
Output: [[3,0],[1,1],[0,-2]]
[3,0] appears twice, so it ranks first even though it is the farthest point. The others appear once: [1,1] is closest with squared distance 2, and [0,-2] and [0,2] tie at 4 with the same x, so the smaller y puts [0,-2] in third place.