Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using array strategy.
Given a sorted integer array arr, two integers k and x, return the k closest integers to x in the array. The result should also be sorted in ascending order.
An integer a is closer to x than an integer b if:
|a - x| < |b - x|, or|a - x| == |b - x| and a < bExample 1:
Input: arr = [1,2,3,4,5], k = 4, x = 3
Output: [1,2,3,4]
Example 2:
Input: arr = [1,1,2,3,4,5], k = 4, x = -1
Output: [1,1,2,3]
Constraints:
1 <= k <= arr.length1 <= arr.length <= 104arr is sorted in ascending order.-104 <= arr[i], x <= 104Problem summary: Given a sorted integer array arr, two integers k and x, return the k closest integers to x in the array. The result should also be sorted in ascending order. An integer a is closer to x than an integer b if: |a - x| < |b - x|, or |a - x| == |b - x| and a < b
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Two Pointers · Binary Search · Sliding Window
[1,2,3,4,5] 4 3
[1,1,2,3,4,5] 4 -1
guess-number-higher-or-lower)guess-number-higher-or-lower-ii)find-k-th-smallest-pair-distance)find-closest-number-to-zero)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #658: Find K Closest Elements
class Solution {
public List<Integer> findClosestElements(int[] arr, int k, int x) {
List<Integer> ans = Arrays.stream(arr)
.boxed()
.sorted((a, b) -> {
int v = Math.abs(a - x) - Math.abs(b - x);
return v == 0 ? a - b : v;
})
.collect(Collectors.toList());
ans = ans.subList(0, k);
Collections.sort(ans);
return ans;
}
}
// Accepted solution for LeetCode #658: Find K Closest Elements
func findClosestElements(arr []int, k int, x int) []int {
sort.Slice(arr, func(i, j int) bool {
v := abs(arr[i]-x) - abs(arr[j]-x)
if v == 0 {
return arr[i] < arr[j]
}
return v < 0
})
ans := arr[:k]
sort.Ints(ans)
return ans
}
func abs(x int) int {
if x >= 0 {
return x
}
return -x
}
# Accepted solution for LeetCode #658: Find K Closest Elements
class Solution:
def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
arr.sort(key=lambda v: abs(v - x))
return sorted(arr[:k])
// Accepted solution for LeetCode #658: Find K Closest Elements
impl Solution {
pub fn find_closest_elements(arr: Vec<i32>, k: i32, x: i32) -> Vec<i32> {
let n = arr.len();
let mut l = 0;
let mut r = n;
while r - l != (k as usize) {
if x - arr[l] <= arr[r - 1] - x {
r -= 1;
} else {
l += 1;
}
}
arr[l..r].to_vec()
}
}
// Accepted solution for LeetCode #658: Find K Closest Elements
function findClosestElements(arr: number[], k: number, x: number): number[] {
let l = 0;
let r = arr.length;
while (r - l > k) {
if (x - arr[l] <= arr[r - 1] - x) {
--r;
} else {
++l;
}
}
return arr.slice(l, r);
}
Use this to step through a reusable interview workflow for this problem.
Two nested loops check every pair of elements. The outer loop picks one element, the inner loop scans the rest. For n elements that is n × (n−1)/2 comparisons = O(n²). No extra memory — just two loop variables.
Each pointer traverses the array at most once. With two pointers moving inward (or both moving right), the total number of steps is bounded by n. Each comparison is O(1), giving O(n) overall. No auxiliary data structures are needed — just two index variables.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Advancing both pointers shrinks the search space too aggressively and skips candidates.
Usually fails on: A valid pair can be skipped when only one side should move.
Fix: Move exactly one pointer per decision branch based on invariant.
Wrong move: Setting `lo = mid` or `hi = mid` can stall and create an infinite loop.
Usually fails on: Two-element ranges never converge.
Fix: Use `lo = mid + 1` or `hi = mid - 1` where appropriate.
Wrong move: Using `if` instead of `while` leaves the window invalid for multiple iterations.
Usually fails on: Over-limit windows stay invalid and produce wrong lengths/counts.
Fix: Shrink in a `while` loop until the invariant is valid again.