K Closest Points to Origin
Real-world version: Nearest Survey StakesThe statement here is our own: the same inputs, outputs and technique.
A survey crew has driven marker stakes across a flat site. Each stake is recorded as a pair [east, north], its offset in metres from the site benchmark, and either offset may be negative.
Given the array stakes and an integer k, return the k stakes nearest the benchmark measured in a straight line across the ground, ordered nearest first. Each returned stake keeps the [east, north] shape it arrived in.
Ties are settled so the answer is never ambiguous: among stakes the same distance from the benchmark, the smaller east offset comes first, and if the east offsets also match, the smaller north offset comes first. Two stakes may sit at the same spot, and a repeated pair is reported as many times as it was recorded.
Examples
Example 1
- Input
- stakes = [[3, 0], [2, 2], [-1, -1]], k = 2
- Output
- [[-1, -1], [2, 2]]
The stake at [-1, -1] stands about 1.41 m from the benchmark and the one at [2, 2] about 2.83 m, while [3, 0] stands 3 m away and is left out.
Example 2
- Input
- stakes = [[5, 0], [0, -5], [1, 7]], k = 2
- Output
- [[0, -5], [5, 0]]
The first two stakes both stand 5 m from the benchmark, so the smaller east offset of 0 is reported before the east offset of 5; the stake at [1, 7] is further out.
Example 3
- Input
- stakes = [[0, 0]], k = 1
- Output
- [[0, 0]]
The only stake is driven at the benchmark itself, 0 m away.
Constraints
- 1 <= k <= stakes.length <= 10^4
- -10^4 <= east, north <= 10^4
The signature
The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.
def nearest_stakes(stakes: list[list[int]], k: int) -> list[list[int]]:public int[][] nearestStakes(int[][] stakes, int k)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 13 test cases: 13 passed
- Passed: 3 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's
More on the same topics
- Kth Largest Element in an ArrayReal-world version: Kth Highest Daily SwingMedium
- Query Kth Smallest Trimmed NumberReal-world version: Kth Smallest Serial by Its TailMedium
- Sort an ArrayReal-world version: Tool Offset OrderingMedium
- Sell Diminishing-Valued Colored BallsReal-world version: Rare Poster RevenueMedium