Problem 658

Abstract / Summary

Given a sorted array and a value x, find k elements closest to x in the array.

Note

The full problem description, including helpful examples, can be found on LeetCode.

C++ 0658.cpp

class Solution {
public:
    vector<int> findClosestElements(vector<int>& arr, int k, int x) {
        auto left = lower_bound(arr.begin(), arr.end(), x);

        if (left == arr.end())
            left--;

        if (*left != x && left != arr.begin())
        {
            auto prev = left - 1;
            if (x - *prev <= *left - x)
                left = prev;
        }

        auto right = left;

        for (auto need = k - 1; need > 0; need--)
        {
            auto diffLeft  = 9999999;
            auto diffRight = 9999999;

            if (left != arr.begin())
                diffLeft  = x - *(left - 1);
            if (right + 1 != arr.end())
                diffRight = *(right + 1) - x;

            if (diffLeft <= diffRight)
                left--;
            else
                right++;
        }

        return vector<int>(left, right + 1);
    }
};
36 lines | 919 bytes | submitted August 7, 2023 | GitHub   tab size 4

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 50% (1+ million submissions).

Typical patterns to solve this problem:
  • Array
  • Binary Search
  • Heap (Priority Queue)
  • Sliding Window
  • Sorting
  • Two Pointers
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The implementation provides a method to return the k elements of a sorted integer array that are closest to a target value x. It leverages the standard library’s binary search to locate the region around x, then expands outward from that region until the required number of elements is gathered. The final result is produced by constructing a vector from the identified range.

Key Steps

Locate the insertion point for x

The algorithm begins by finding the first element that is not less than x using lower_bound. This gives a pointer (left) to the position where x would be inserted while preserving order.

auto left = lower_bound(arr.begin(), arr.end(), x);

If the target exceeds the largest element, lower_bound returns arr.end(). The code corrects this by moving the pointer one step back, ensuring left always references a valid element.

if (left == arr.end())
    left--;

Adjust when x is not present

When the element at left is not exactly x and left is not at the beginning, the algorithm compares the distance to the previous element. If the previous element is nearer (or equally near) to x, left is shifted leftward to that element.

if (*left != x && left != arr.begin())
{
    auto prev = left - 1;
    if (x - *prev <= *left - x)
        left = prev;
}

Initialize the right boundary

The right boundary (right) is initially set to the same position as left. At this point the range [left, right] contains a single candidate element that is closest to x.

auto right = left;

Expand the window to include k elements

A loop runs k-1 times, each iteration deciding whether to extend the window to the left or to the right. The distances from x to the next potential left and right elements are computed, defaulting to a large sentinel value when the respective side is out of bounds.

for (auto need = k - 1; need > 0; need--)
{
    auto diffLeft  = 9999999;
    auto diffRight = 9999999;

    if (left != arr.begin())
        diffLeft  = x - *(left - 1);
    if (right + 1 != arr.end())
        diffRight = *(right + 1) - x;

    if (diffLeft <= diffRight)
        left--;
    else
        right++;
}

The comparison diffLeft <= diffRight ensures that when distances are equal the element on the left side is chosen, preserving the required ordering rule that prefers smaller values in ties.

Produce the result

After the window has been expanded to contain exactly k elements, a new vector is constructed directly from the iterator range [left, right + 1). This yields a contiguous block of the original array without additional copying of individual elements.

return vector<int>(left, right + 1);

Edge Cases Handled

When x lies beyond the maximum element, the initial correction of left guarantees that the algorithm starts from the last element, and the expansion loop will only move the right boundary forward if possible, otherwise it will keep extending leftward until k elements are collected.

If x is smaller than the minimum element, lower_bound points to the first element. The subsequent adjustment does not move left leftward because left is already at arr.begin(). The expansion loop then proceeds by moving the right boundary rightward as needed.

When x exactly matches an element, the early adjustment step is bypassed because *left == x. The window then expands symmetrically around that exact match, again respecting the tie-breaking rule that prefers the left side when distances are equal.

If the array contains duplicate values equal to x, lower_bound returns the first occurrence. The algorithm’s distance comparison treats the preceding element (if any) as a candidate, ensuring that the window can include earlier duplicates when they are equally close.

When k equals the size of the array, the loop will eventually expand the window to cover the entire range. The sentinel values for out-of-bounds checks prevent attempts to read beyond the container’s limits.

Performance Optimizations

The use of lower_bound provides a logarithmic search to locate the vicinity of x, avoiding a linear scan of the entire array. Subsequent expansion operates in a tight loop that only examines the immediate neighbors of the current window, resulting in constant-time work per iteration.

By storing the distances in local variables (diffLeft, diffRight) and reusing them for the comparison, the code minimizes repeated arithmetic and dereferencing. The sentinel value 9999999 acts as a simple guard that eliminates the need for additional conditional branches when one side of the window has reached the array boundary.

Constructing the result vector directly from iterator bounds (left to right + 1) leverages the range constructor of std::vector, which copies the required segment in a single operation. This avoids the overhead of pushing elements individually or performing multiple reallocations.

Overall, the algorithm balances a fast initial positioning step with a minimal-overhead expansion phase, delivering an efficient solution for the “closest elements” problem.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a long row of numbered toy blocks lined up from smallest to largest on the floor. You are holding a special target card with a number written on it, and you want to pick out a specific group of blocks that are the closest to your target number.

First, the code goes on a little scavenger hunt to find where your target number would fit in the line. It looks around to see if your target is already there or which block is the closest neighbor to it. Once it finds that starting spot, it marks it as a place to begin gathering your collection.

Since you need to pick a certain amount of blocks, the code acts like a helper who reaches out to the left and to the right of the starting spot. It checks its map to see which neighbor is closer to your target number. If the block to the left is closer, it adds that one to your group. If the block to the right is closer, it picks that one instead.

It keeps repeating this process over and over, carefully looking at both sides to find the best neighbors until the right amount of blocks has been gathered into your pile. Once the pile is the correct size, it gives you back your new group of blocks.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 7 | μ = 6.69 | σ = 1.03

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java Rust Go TS
LeetcodeHelp C++ Python Java
MemoryLimitExceeded C++ Python
Progiez C++ Python Java
github black-shadows C++
chandansgowda Python
charles-wangkai Java
everthis JS
fengvyi C++
fsq C++
halfrost Go
JoshCrozier JS
keineahnung2345 C++
Krazune C++
lkwq007 Python
MacJim C++
ruoru Rust
sonugiri1043 C++
suxrobGM C#
trung-hn Python
varunu28 Java
vthwang Java
wisdompeak C++
YuriSpiridonov Python
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
black-shadows C++, C++
chandansgowda Python
charles-wangkai Java
everthis JavaScript
fengvyi C++
fsq C++
halfrost Go
JoshCrozier JavaScript
keineahnung2345 C++
Krazune C++
lkwq007 Python
MacJim C++
ruoru Rust
sonugiri1043 C++
suxrobGM C#
trung-hn Python
varunu28 Java
vthwang Java
wisdompeak C++
YuriSpiridonov Python
zfang399 C++
42 links | 27 authors | 8 languages

Videos

7 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

4 similar problems

Solved On The Same Day

40 easy 30 medium 1 hard
72 solutions   August 7, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality