# Implement a k-nearest neighbors algorithm

Aced (formerly Exponent) publishes a public search API over its indexed pages; the guide is at https://www.aced.io/agents/agent-access.

Source: https://www.aced.io/questions/3489/implement-k-nearest-neighbors-algorithm
Source observed: 2026-11-04T22:03:14.769Z
Last checked: 2026-11-04T22:03:14.769+00:00
Indexed: 2026-11-06T09:01:25.344+00:00

---

# Implement a k-nearest neighbors algorithm

**Difficulty:** Easy  
**Interview categories:** Coding; Machine Learning  
**Roles:** Machine Learning Engineer; Software Engineer  
**Companies associated with this question:** Meta, Amazon, Pinterest  
**Reported activity:** 3 interviews; last asked 4 months ago  
**Community:** No answers contributed yet

## Problem

Implement the K-nearest neighbors (KNN) algorithm. Your `knn` function has four inputs:

1. `X_train`: a NumPy array of points already on the map.
2. `Y_train`: a NumPy array of labels for each point on the map, either `1` or `0`.
3. `X_new`: a NumPy array for the new point being added to the map and classified.
4. `k`: an integer specifying how many of the closest points to `X_new` to inspect when deciding its label.

KNN classifies a new data point using the most common category among its `k` closest points in the dataset. It determines closeness by calculating distances between points.

## Python example

```python
# Example
X_train = np.array([[1, 2], [2, 3], [3, 4], [6, 7], [7, 8], [8, 9]])
y_train = np.array([0, 0, 0, 1, 1, 1])
X_new = np.array([2, 2])  # The new point we want to classify
k = 3  # We'll look at the 3 closest points
knn(X_train, y_train, X_new, k)  # should return 0
```

The interactive coding area includes **Question**, **Solution**, **Mock Interview**, and **Community** tabs. The editor includes **Editor** and **Share** views, with **Output**, **Test Results**, and **Console** controls. Running code requires signing up: [Sign up to run code](https://www.aced.io/signup?src=lesson).

## Interview preparation

Use our [Model & Algorithm Fundamentals](https://www.tryexponent.com/courses/ml-engineer/ml-concepts-interviews/k-nearest-neighbors) module to study KNN for interviews. Detailed company statistics are available through [Upgrade](https://www.aced.io/upgrade?src=questions).

## Interview experience

One shared experience is associated with this question: [Meta · 4 months ago](https://www.aced.io/experiences/meta-facebook-senior-machine-learning-engineer-interview-9efbbd).

The contributor, a **Machine Learning Engineer at Senior / L5**, described an initial recruiter screen, a 45-minute pre-screen with a senior manager about past work and impact, and a full loop of five interviews. The loop included two coding rounds—one classic LeetCode-style round and one AI-coding round with data-processing and math-heavy prompts such as sparse-matrix-times-vector multiplication and KNN search—along with two design rounds and one behavioral round. The design rounds covered ML modeling for a computer-vision problem and system design resembling Google Street View. The contributor reported passing the loop and moving into offer negotiation.

## Related question

- [Implement a string sorting algorithm, treating digits as numbers.](https://www.aced.io/questions/2059/implement-string-sorting-algorithm-treating-digits-as-numbers)

## Related courses

### [Machine Learning Engineer Interview Prep](https://www.aced.io/courses/ml-engineer)

![Machine Learning Engineer Interview Prep](https://images.ctfassets.net/x78yjrjc11pq/6UfkHxUyLQVfDHSfLNQtWa/1be1539a65b4f6f15201f5b573c0a578/ML_Engineer_Interview_Prep_Course.jpeg?w=800&h=800&fm=webp&q=75)

Prepare for machine-learning roles at Meta, Google, Amazon, Apple, Microsoft, Nvidia, and other companies with mock interviews, frameworks, and advice from senior candidates. Topics include ML system design, core concepts, coding, and behavioral interviews.

### [Software Engineering Interview Prep](https://www.aced.io/courses/software-engineering)

![Software Engineering Interview Prep](https://images.ctfassets.net/x78yjrjc11pq/4VkuYewBHUFIVUS5oJDW5h/02e833439b1289f25f38f13f81cbdca3/adobe_stock_optimized.jpeg?w=800&h=800&fm=webp&q=75)

Prepare for software-engineering roles at Google, Amazon, Microsoft, Meta, Apple, and other companies with mock interviews, frameworks, and advice from senior candidates. Topics include data structures, algorithms, system design, people management, and behavioral interviews.

## Browse our interview preparation areas

We organize preparation across courses, interview loops, interview experiences, coding practice, coaching, and questions. We also provide mock interviews and coaching, resume review, salary negotiation, job referrals, resources, and pricing information.

---

[Read this page’s summary](https://www.aced.io/agents/api/public/v1/page-tldr?url=https%3A%2F%2Fwww.aced.io%2Fquestions%2F3489%2Fimplement-k-nearest-neighbors-algorithm&trace=t_679ff9ab98f3)

## Ask a follow-up about this page

Need a more specific answer? Ask the exact question you have. It returns a fresh, cited answer from Aced (formerly Exponent)’s knowledge base. No account or API key required.

Open this URL with your own question, URL-encoded. Include your question in q. All research inputs are optional; no account or setup.

`GET https://www.aced.io/agents/agent/faq?q={question}&trace=t_679ff9ab98f3`

[Tool guide and examples](https://www.aced.io/agents/agent-access) · [OpenAPI](https://www.aced.io/agents/api/public/v1/openapi.json) · [Page TLDR form](https://www.aced.io/agents/agent-tools/page-tldr?url=https%3A%2F%2Fwww.aced.io%2Fquestions%2F3489%2Fimplement-k-nearest-neighbors-algorithm). Opening a form does not execute a tool.