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);
}
};
Difficulty
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
AI Disclaimer
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.
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.
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.
Code Quality
Complexity Analysis
Other Solutions
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++ |
Videos
Similar Problems
- problem 374: Guess Number Higher or Lower
- problem 375: Guess Number Higher or Lower II
- problem 719: Find K-th Smallest Pair Distance
- problem 2239: Find Closest Number to Zero
Solved On The Same Day
- problem 13: Roman to Integer
- problem 21: Merge Two Sorted Lists
- problem 28: Find the Index of the First Occurrence in a String
- problem 35: Search Insert Position
- problem 58: Length of Last Word
- problem 66: Plus One
- problem 67: Add Binary
- problem 69: Sqrt(x)
- problem 70: Climbing Stairs
- problem 206: Reverse Linked List
- problem 242: Valid Anagram
- problem 278: First Bad Version
- problem 283: Move Zeroes
- problem 367: Valid Perfect Square
- problem 374: Guess Number Higher or Lower
- problem 389: Find the Difference
- problem 441: Arranging Coins
- problem 459: Repeated Substring Pattern
- problem 509: Fibonacci Number
- problem 657: Robot Return to Origin
- problem 682: Baseball Game
- problem 704: Binary Search
- problem 709: To Lower Case
- problem 744: Find Smallest Letter Greater Than Target
- problem 746: Min Cost Climbing Stairs
- problem 860: Lemonade Change
- problem 896: Monotonic Array
- problem 976: Largest Perimeter Triangle
- problem 1137: N-th Tribonacci Number
- problem 1232: Check If It Is a Straight Line
- problem 1275: Find Winner on a Tic Tac Toe Game
- problem 1351: Count Negative Numbers in a Sorted Matrix
- problem 1491: Average Salary Excluding the Minimum and Maximum Salary
- problem 1502: Can Make Arithmetic Progression From Sequence
- problem 1523: Count Odd Numbers in an Interval Range
- problem 1539: Kth Missing Positive Number
- problem 1572: Matrix Diagonal Sum
- problem 1672: Richest Customer Wealth
- problem 1768: Merge Strings Alternately
- problem 1822: Sign of the Product of an Array
- problem 2: Add Two Numbers
- problem 5: Longest Palindromic Substring
- problem 33: Search in Rotated Sorted Array
- problem 34: Find First and Last Position of Element in Sorted Array
- problem 43: Multiply Strings
- problem 50: Pow(x, n)
- problem 54: Spiral Matrix
- problem 62: Unique Paths
- problem 63: Unique Paths II
- problem 64: Minimum Path Sum
- problem 73: Set Matrix Zeroes
- problem 74: Search a 2D Matrix
- problem 120: Triangle
- problem 139: Word Break
- problem 153: Find Minimum in Rotated Sorted Array
- problem 198: House Robber
- problem 221: Maximal Square
- problem 275: H-Index II
- problem 279: Perfect Squares
- problem 300: Longest Increasing Subsequence
- problem 436: Find Right Interval
- problem 445: Add Two Numbers II
- problem 528: Random Pick with Weight
- problem 540: Single Element in a Sorted Array
- problem 611: Valid Triangle Number
- problem 852: Peak Index in a Mountain Array
- problem 981: Time Based Key-Value Store
- problem 1041: Robot Bounded In Circle
- problem 1146: Snapshot Array
- problem 2300: Successful Pairs of Spells and Potions
- problem 154: Find Minimum in Rotated Sorted Array II
Extra
- 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