K Nearest Entries

Start Timer

0:00:00

Upvote
6
Downvote
Save question
Mark as completed
View comments (6)

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

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

Notes:
1. If k 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 N is not an entry in ints and there are two values equally close to N, 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]
.
.
.
.
.


Comments

Loading comments