Grokking the Coding Interview: Patterns for Coding Questions

0% completed

Solution: 'K' Closest Numbers

Problem Statement

Given a sorted number array and two integers ‘K’ and ‘X’, find ‘K’ closest numbers to ‘X’ in the array. Return the numbers in the sorted order. ‘X’ is not necessarily present in the array.

Example 1:

Input: [5, 6, 7, 8, 9], K = 3, X = 7
Output: [6, 7, 8]

Example 2:

Input: [2, 4, 5, 6, 9], K = 3, X = 6
Output: [4, 5, 6]

Example 3:

Input: [2, 4, 5, 6, 9], K = 3, X = 10
Output: [5, 6, 9]

Constraints:

  • 1 <= k <= arr.length
  • 1 <= arr.length <= 10<sup>4</sup>
  • arr is sorted in ascending order.

.....

.....

.....

Like the course? Get enrolled and start learning!
Alex B

Alex B

· 2 years ago

Within one of the tests on Submit, we have the following:

Your Input [5,4,3,2,1] 3 3 Output ... Expected [2,3,4]

My implementation returned [4,3,2] due to an assumption from the constraints that: "arr is sorted in ascending order".

Show 1 reply