Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Find k closest elements in a sorted array

Given a sorted array, return the k elements closest to a target x in ascending order. Use two pointers for an optimal linear solution.

Python practice24 minTwo Pointers & Sliding WindowAdvancedLast updated March 26, 2026

Problem statement

You are given a sorted list of integers arr, an integer k, and a target value x. Return a list of the k integers in arr that are closest to x. The returned list must be sorted in ascending order. If there is a tie (two numbers are equally close), prefer the smaller number (the one with the lower value). Aim for O(k + log n) time by locating the insertion position and expanding two pointers outward.

Task

Implement a function that finds the k closest elements to x in a sorted list using two-pointer expansion from the insertion point.

Examples

Basic example

Input

arr = [1, 2, 3, 4, 5], k = 4, x = 3

Output

[1, 2, 3, 4]

The four numbers closest to 3 are 1,2,3,4. They are returned in ascending order.

Input format

A sorted list of integers arr, an integer k (1 <= k <= len(arr)), and an integer x.

Output format

A list of k integers from arr, sorted in ascending order, representing the k closest elements to x.

Constraints

arr is sorted in non-decreasing order. 1 <= k <= len(arr). Time complexity target: O(k + log n). No external libraries required.

Samples

Sample 1

Input

arr = [1, 2, 3, 4, 5], k = 4, x = -1

Output

[1, 2, 3, 4]

x is less than all elements, so return the first k elements.