K-D Tree - Problem

Implement a K-D Tree for 2D points that supports efficient spatial queries. A K-D Tree (k-dimensional tree) is a binary tree used for organizing points in k-dimensional space.

Your implementation should support:

  • Construction: Build the tree from a list of 2D points
  • Nearest Neighbor Search: Find the closest point to a given query point
  • Range Query: Find all points within a rectangular region

For this problem, implement the nearest neighbor search functionality. Given a list of 2D points and a query point, return the point from the list that has the minimum Euclidean distance to the query point.

Input & Output

Example 1 — Basic Nearest Neighbor
$ Input: points = [[2,3],[5,4],[9,6],[4,7],[8,1],[7,2]], query = [5,5]
Output: [5,4]
💡 Note: Calculate distances: (2,3)→3.6, (5,4)→1.0, (9,6)→4.1, (4,7)→2.2, (8,1)→5.7, (7,2)→3.6. Point (5,4) has minimum distance of 1.0
Example 2 — Query at Origin
$ Input: points = [[1,1],[3,3],[-1,-1],[2,-2]], query = [0,0]
Output: [-1,-1]
💡 Note: Distances from origin: (1,1)→1.41, (3,3)→4.24, (-1,-1)→1.41, (2,-2)→2.83. Both (1,1) and (-1,-1) have same distance 1.41, return first found
Example 3 — Single Point
$ Input: points = [[10,20]], query = [15,25]
Output: [10,20]
💡 Note: Only one point available, so (10,20) is the nearest neighbor by default with distance √((15-10)² + (25-20)²) = 7.07

Constraints

  • 1 ≤ points.length ≤ 104
  • points[i].length == 2
  • query.length == 2
  • -104 ≤ points[i][j], query[j] ≤ 104

Visualization

Tap to expand
INPUTALGORITHMRESULT(2,3)(5,4)(9,6)(4,7)(8,1)(7,2)Q(5,5)6 points + queryFind closest neighbor1Build K-D Tree2Split alternating X/Y3Search with pruning4Skip impossible branchesO(log n) average time(5,4)Closest Point Found!Distance: 1.0Comparisons: ~3 vs 6Key Insight:K-D Trees organize points by alternating coordinate splits, enabling spatial queriesto prune large regions and achieve logarithmic average-case performance.TutorialsPoint - K-D Tree Nearest Neighbor | Spatial Data Structure
Asked in
Google 15 Amazon 12 Microsoft 8 Apple 6
8.5K Views
Medium Frequency
~35 min Avg. Time
342 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen