Junior — Senior
k elements closest to the specified index
livecode
Task condition
Given an array of integers sorted in non-decreasing order (duplicates allowed). Also known is the index of a certain element idx and a number k. It is required to implement a method that returns k elements from the array whose values differ from the value of the element at index `idx`` by the smallest absolute difference.
Examples:
arr = [1, 2, 2, 3, 4, 4, 5, 6], idx = 4, k = 2 → result = [4, 4]
arr = [1, 2, 3, 4, 5, 6], idx = 3, k = 2 → result = [4, 3] or [4, 5]
arr = [1, 2, 3, 4, 5, 6], idx = 0, k = 3 → result = [1, 2, 3]
arr = [1, 2, 2, 3, 3, 56, 78, 79, 79, 100], idx = 4, k = 3 → result = [3, 2, 3]