Find K Closest Elements in a Sorted Array
Updated
Problem statement
Given a sorted integer array arr, an integer k, and a target x, return the k closest values to x in ascending order.
A value a is closer than b when |a - x| < |b - x|. For equal distances, the smaller value is closer.
Function
findClosestElements(arr: int[], k: int, x: int) → List<Integer>Examples
Example 1
arr = [1,2,3,4,5]k = 4x = 3return = [1,2,3,4]The four smallest distances belong to 1, 2, 3, and 4.
Example 2
arr = [1,2,3,4,5]k = 4x = -1return = [1,2,3,4]The target lies left of the array, so the first four values are closest.
Constraints
arris non-empty and sorted in nondecreasing order.1 <= k <= arr.length.- All values and
xare signed integers.
More LinkedIn Onsite Interview questions
- Allocate Mailboxes with Squared DistanceONSITE INTERVIEW · Seen Nov 2026
- Find Leaves of a Binary TreeONSITE INTERVIEW · Seen Nov 2026
- Max Points on a LineONSITE INTERVIEW · Seen Nov 2026
- Explore an Unknown Grid and Find a PathONSITE INTERVIEW · Seen Nov 2026
- Fire Station Response BillONSITE INTERVIEW · Seen Nov 2026
- Roll a Weighted DieONSITE INTERVIEW · Seen Oct 2026
- Longest Binary Subarray With at Most K OnesONSITE INTERVIEW · Seen Oct 2026
- Kth Closest Element in a BSTONSITE INTERVIEW · Seen Oct 2026
- Longest Binary Window with at Most K OnesONSITE INTERVIEW · Seen Oct 2026
- LRU Cache OperationsONSITE INTERVIEW · Seen Oct 2026
Similar questions at other companies
- Count Winning Dice Face PairsGoogle · PHONE SCREEN · ONSITE INTERVIEWGoogle interview questions
- Search a Row- and Column-Sorted MatrixByteDance · ONSITE INTERVIEWByteDance interview questions
- 3Sum SmallerSalesforce · ONSITE INTERVIEWSalesforce interview questions
- K Smallest Squares from a Sorted ArrayUber · ONSITE INTERVIEWUber interview questions
- Find K Closest Elements in a Sorted ArrayBloomberg LP · ONSITE INTERVIEWBloomberg LP interview questions
- Find K Closest Elements in a Sorted ArrayNavi · PHONE SCREEN
- K Closest Elements in a Sorted ArrayAmazon · PHONE SCREEN
- Count Centaur Friend RequestsMeta · PHONE SCREENMeta interview questions
- Count the Number of Incremovable Subarrays IIThe D.E. Shaw Group · OAThe D.E. Shaw Group interview questions
- Count Triples That Can Form a TriangleAdobe · PHONE SCREENAdobe interview questions