Interview Query

K Nearest Entries

1
Have you seen this question before?

Given a sorted list of integers ints with no duplicates, write an efficient function nearest_entries that takes in integers NN and kk and does the following:

Finds the element of the list that is closest to NN and returns that element along with the kk-next and kk-previous elements of the list.

Notes:
1. If kk is large enough to go out of the bounds of ints, return all entries up to that bound but do not throw an error. 2. If NN is not an entry in ints and there are two values equally close to NN, use the lower value as your starting point.

Examples:

Input:

#Example 1:
ints = [1,2,3,4,5,6,7,8,9]
N = 4
k = 2
def nearest_entries(ints, N, k) -> [2,3,4,5,6]

#Example 2:
ints = [1,3,4,6,8]
N = 5
k = 1
def nearest_entries(ints, N, k) -> [3,4,6]

#Example 3:
ints = [1,3,4,7,9,11,15,22,77]
N = 22
k = 4
def nearest_entries(ints, N,k) -> [7, 9, 11, 15, 22, 77]
Next question: Changing Composer
.....
Python 3.9.6
Loading editor
Use Shift + Enter to run code