Learn
Practice
Interview
Resources
Newsletter
F
Toggle theme
0
F
0
Toggle menu
Animations
← Back to All Animations
Find K Closest Elements
Bookmark
Sort by Distance
Two Pointers
Binary Search
Input
Standard
Left edge
Right edge
Larger array
Custom
arr
=
[1, 2, 3, 4, 5]
,
k
=
4
,
x
=
3
x = 3
0
1
1
2
2
3
3
4
4
5
x = 3
0
1
1
2
2
3
3
4
4
5
x = 3
|arr[0] - x| = |1 - 3| = 2
0
1
1
2
2
3
3
4
4
5
x = 3
|arr[1] - x| = |2 - 3| = 1
0
1
1
2
2
3
3
4
4
5
x = 3
|arr[2] - x| = |3 - 3| = 0
0
1
1
2
2
3
3
4
4
5
x = 3
|arr[3] - x| = |4 - 3| = 1
0
1
1
2
2
3
3
4
4
5
x = 3
|arr[4] - x| = |5 - 3| = 2
0
1
1
2
2
3
3
4
4
5
x = 3
0
1
1
2
2
3
3
4
4
5
x = 3
0
1
1
2
2
3
3
4
4
5
algo
master
.
io
Step:
Start: sort the 5 elements by distance to x = 3, keep the 4 closest
0 / 7
Input
Standard
Left edge
Right edge
Larger array
Custom
arr
=
[1, 2, 3, 4, 5]
,
k
=
4
,
x
=
3
0 / 7
algo
master
.
io
Step:
Start: sort the 5 elements by distance to x = 3, keep the 4 closest