Coding Interview: Find K Closest Elements

Introduction and solution on the Find K Closest Elements coding interview. Variations of this algorithm have been asked by a few big tech companies such as Google, Facebook, Microsoft, Netflix, Amazon, so it's important to know how to solve it efficiently.
Please support me through my Udemy courses:
Pass your coding interview in,
Java : www.udemy.com/course/beat-the...
Python: www.udemy.com/course/beat-the...
Ruby: www.udemy.com/course/beat-the...
JavaScript: www.udemy.com/course/beat-the...
Multithreading in,
Go Lang: www.udemy.com/course/multithr...
Python: www.udemy.com/course/parallel...
Java: www.udemy.com/course/master-p...
Learn Dynamic Programming in,
Java: www.udemy.com/course/dynamic-...
Python: www.udemy.com/course/dynamic-...
Ruby: www.udemy.com/course/dynamic-...

Пікірлер: 6

  • @empowercode
    @empowercode Жыл бұрын

    Hey James, great video! Particularly, I like how clear and detailed your explanations are as well as the depth of knowledge you have surrounding the general programming approach. Since I run a tech education channel as well, I love to see fellow Content Creators sharing, educating, and inspiring a large global audience. Keep up the great work!

  • @lvkaz
    @lvkaz Жыл бұрын

    This content is so underrated! Keep up the excellent work. I hope You will get a lot of recognition soon for such great explanations!

  • @vijayakumareyunni6010
    @vijayakumareyunni60107 ай бұрын

    Excellent explanation and solution

  • @Adaetro
    @Adaetro Жыл бұрын

    Since array is ordered what if you stop the cycle when current abs_sum is higher then previous abs_sum? In the first example since abs_sum of [8 , 9, 10] = 3 and previous abs_sum of [7, 8, 9] = 2 then there is no point in calculating [9, 10, 13] since abs_sum is only going to increase from now on?

  • @Adaetro

    @Adaetro

    Жыл бұрын

    def find_closest_elements(arr, k, x): abs_list = list(map(lambda n:abs(n-x), arr)) prev_abs_sum = abs_sum_min = abs_sum = sum(abs_list[0:k]) min_i = 0 for i in range(1, len(arr)-k+1): abs_sum = abs_list[i+k-1] + abs_sum - abs_list[i-1] if prev_abs_sum break if abs_sum abs_sum_min = abs_sum min_i = i prev_abs_sum = abs_sum return arr[min_i:min_i+k], i #print number of loops print(find_closest_elements([5, 7, 8, 9, 10, 13], k=3, x=8))

  • @yashchoube576
    @yashchoube576 Жыл бұрын

    Best