Find K-th Smallest Pair Distance - Leetcode 719 - Python

Поділитися
Вставка
  • Опубліковано 16 гру 2024

КОМЕНТАРІ • 123

  • @NeetCodeIO
    @NeetCodeIO  4 місяці тому +96

    why are the problems so hard lately, we're not even halfway through the month...

    • @tjsm4455
      @tjsm4455 4 місяці тому +8

      Did you solved this one on ur first try or looked up to the hints?
      For me BS wasn't intuitive at all.

    • @tanzimchowdhury320
      @tanzimchowdhury320 4 місяці тому +1

      better for your business lol

    • @ashaynaik7540
      @ashaynaik7540 4 місяці тому +3

      this exact question was asked in interview for entry level job 😢

    • @hardiksrivastava9174
      @hardiksrivastava9174 4 місяці тому

      @@ashaynaik7540 which company ?

    • @hasferrr
      @hasferrr 4 місяці тому

      ​@@ashaynaik7540 really? what company?

  • @gmh14
    @gmh14 4 місяці тому +44

    halfway through the video i forgot what the question was

  • @tuandino6990
    @tuandino6990 4 місяці тому +54

    Yeap, my 45 days streak ends here

    • @RajdeepJadeja
      @RajdeepJadeja 4 місяці тому +1

      use a ticket buddy

    • @sagayaraj6298
      @sagayaraj6298 3 місяці тому

      What is mean by ticket and how it will help us. Can anyone explain

    • @pavankalyan-lv8pf
      @pavankalyan-lv8pf 3 місяці тому

      @@sagayaraj6298 you can regain your streak by spending 70 points

  • @pk2468-z2w
    @pk2468-z2w 4 місяці тому +8

    The question states that we want pairs nums[i] and nums[j] where 0

    • @AnilKumar-d6y1l
      @AnilKumar-d6y1l 4 місяці тому +1

      us bro us

    • @pk2468-z2w
      @pk2468-z2w 4 місяці тому

      It seems Leetcode also forgot about the condition. Neetcode's solution passed all test cases.

    • @pk2468-z2w
      @pk2468-z2w 4 місяці тому

      @NeetCodeIO Can you explain what's going on here? There is clearly something that I'm missing.

    • @NeetCodeIO
      @NeetCodeIO  4 місяці тому +21

      The only reason they mention that constraint is because they don't want you to count a single pair twice.
      Notice that we calculate the absolute difference of the pairs. Thus, the ordering is irrelevant.

    • @pk2468-z2w
      @pk2468-z2w 4 місяці тому +1

      @@NeetCodeIO Gotcha, didn't realize that part. Irrespective of the ordering, a pair will be counted if the absolute difference matches the condition. Thanks!

  • @hardiksrivastava9174
    @hardiksrivastava9174 4 місяці тому +28

    Don't worry the problem isn't even that hard.
    The problem :

  • @iams04
    @iams04 4 місяці тому +16

    I thought you won't drop the video, thank you Neetcode

  • @ankitadey9040
    @ankitadey9040 4 місяці тому +3

    At first, I carefully watched your intuition explanation, had to replay few parts at times to understand properly, then when I understood what approach you talked about, I tried to code it myself. I did it. But the complexity looked pretty bad, still I was happy I did it. And then I watched you writing the code and saw that in the helper function, I wrote a longer while() loop than you because I used while() for the whole window movement instead of just l, so when i changed that part in my code, the complexity got so much better. Anyway, my point is.. THANK YOU SO MUCH FOR ALWAYS GUIDING ME! I don't watch the code right away unless it's about graph or trees because I am weak at those but you always help with the intuition part if I had been stuck for quite some time. Thanks a lot.

  • @Sid37612
    @Sid37612 4 місяці тому +3

    This problem was really difficult for me lmao. It took 2-3 replays just to visualize what's going on. Thanks for the explanation!

  • @Генри-ю5б
    @Генри-ю5б 4 місяці тому +9

    At first time tried to implement myself. Make combinations of pairs and their differences put in an array. 17 / 19 passed

    • @saranshtyagi1214
      @saranshtyagi1214 4 місяці тому +2

      us bro, brute force did really passed 17 testcases and then boom :(

    • @user-tt3lb1yy6i
      @user-tt3lb1yy6i 4 місяці тому +1

      If you really wanted it, then you wouldve done
      If num == (testcase): return (testcase answer)

  • @lavanya_m01
    @lavanya_m01 4 місяці тому +5

    At 20:09 there are 10 pairs with difference

  • @MehmetDemir-xi3yy
    @MehmetDemir-xi3yy 4 місяці тому +10

    Actually brute force T.C is n^2logn since there are n * (n-1) /2 pairs

    • @greatfate
      @greatfate 4 місяці тому +1

      yup yup, it's O(n^2 * log(n^2)) = O(n ^ 2 * (2 * log(n))) = O(n^2 logn)

    • @sarmohanty
      @sarmohanty 4 місяці тому +2

      no, you guys are wrong. Assuming you store all the differences between all the pairs (O(n^2) space compexity), you can run QuickSelect in linear time to get the Brute Force T.C to n^2

    • @greatfate
      @greatfate 4 місяці тому

      @@sarmohanty fair enough, didn't think that deep coz brute force was instantly out of the question

  • @MehmetDemir-xi3yy
    @MehmetDemir-xi3yy 4 місяці тому +2

    Btw could you please explain, how to know if the value of mid in the binary search, actually exists as a difference of 2 elements in the array? We just assume there are set of differences from 0 to max but we may not have these?

  • @siddharth-gandhi
    @siddharth-gandhi 4 місяці тому +6

    The only thing I'm confused about is what is the guarantee that m will be in the differences array. Not necessary that all values in [0, max] will be a possible difference of any pair. Eg. [1,1,6] has [0,6] possible difference values but only 0 & 5 actually exist.

    • @NeetCodeIO
      @NeetCodeIO  4 місяці тому +2

      M doesn't have to be in the differences array, we can still count differences that are less than or equal to m. Eventually our m will be a valid difference.

    • @siddharth-gandhi
      @siddharth-gandhi 4 місяці тому +1

      @@NeetCodeIO How do we prove that m will be eventually valid? The thing I was doing wrong was that in the while loop when pairs == k, i was returning m and I'm not able to quite understand how not exiting early prevents this.

    • @siddharth-gandhi
      @siddharth-gandhi 4 місяці тому +1

      @@NeetCodeIO So like in [1,1,6], with k = 1 differences are [0,5,5] and l,r = 0,6. First m is 3 and thus pairs = 1 (since only 0 is

    • @gavinebenezer1670
      @gavinebenezer1670 4 місяці тому

      ⁠@@siddharth-gandhi idk if this makes sense but if we have 3 as a valid solution for the example, we will end up reducing the search space, then when we do binary search we will find any values smaller than 3 that also satisfy having greater than or equal to k num of pairs that are less than it, as we keep reducing the search space we’ll get to a point where we get an invalid value we’re searching on, it’s kind of difficult to see in ur example but if we have [1,2,6] as the arr and [1,4,5] as the pair dists, we can set our search space as [0, max - min] -> [0, 5] and k = 1, then our first mid value we search is 5 - 0 // 2 = 2 and we see that there is >= 1 pair of at least dist 2, so now high = 2, low remains 0, and mid = 2 // 2 = 1, now when we count pairs on 1 (which is in the array) it will give us the same result as the higher value from before, so we can be sure the dist is in the array because we r looking for the smallest value for mid that satisfies k

    • @MarkGuy-i4e
      @MarkGuy-i4e 4 місяці тому

      @@siddharth-gandhi I had the same question. It turns out that if you have an array such as [1,1,2,2,3] with k=4, and you started the binary search with the range [0,6] since 6 is the max element, the differences array would be [0,1,1,2,1,1,2,0,1,1] which sorts to [0,0,1,1,1,1,1,1,2,2]. Then we can clearly see the kth smallest sum is 1 at index 3 of the differences array (0-indexed). Now using the algorithm, we would start with r = 6 and l = 0 and get m = 3 with pairs = 10. We would then get r = 3 and l = 0 which would give us a new m = 1 for which pairs = 8. We would then get r = 1 and l = 0 which would give us a new m = 0 for which pairs = 2, leaving us with a final l = r = 1. In the above approach, m eventually becomes valid because the binary search keeps choosing the smallest valid number such that helper(m) is at least equal to k. In the example, the smallest m that achieves this is m = 1 where we have pairs = 8 because if we go to m = 0 we have pairs = 2 which is less than k. This suggests that since m = 0 only had 2 pairs, there must be 6 differences that are equal to 1 in the original array, therefore making m = 1 have pairs = 8. There is no other integer between m = 0 and m = 1 that would cause the pairs to go from 2 to 8, so it is as if incrementing the potential sum (which is m) by 1 adds 6 pairs. Therefore m = 1 regardless of the situation must correspond to some valid difference in the original array because of the jump in 6 pairs. The binary search always find the smallest m such that it is on this cusp.

  • @vietnguyenquoc4948
    @vietnguyenquoc4948 4 місяці тому

    TYSM, I struggled with understanding the binary search approach and 16:22 is literally an "Aha" moment.
    After that it still took sometimes for me to come up with how to count the pairs but it still much better than twiddling my thumbs trying to understand the editorial of leetcode

  • @yuhangzhao3303
    @yuhangzhao3303 4 місяці тому

    I kinda like this question because it just combines multiple basics to solve it, not like some others solved with a crazy complicated specific algorithm.

  • @bhumikagupta1978
    @bhumikagupta1978 4 місяці тому

    The brute force time complexity will be of order O(n^2 . logn) since there will be n * (n -1) / 2 distance pairs, and sorting them would have time complexity O(m . logm) where m = n * (n -1) / 2, which make it O(n^2 . logn).

  • @jamestwosheep
    @jamestwosheep 4 місяці тому

    Thank you very much for that explanation, I was really struggling with figuring out how to get around the O(n^2) problem with the pairs.

  • @guyguysir3216
    @guyguysir3216 4 місяці тому +6

    I am able to implement once understanding the method. But how on earth do I come up with this solution...

    • @michaelroditis1952
      @michaelroditis1952 4 місяці тому +3

      If you can implement it you are on really good road. There was a leetcode daily challenge that had similar solution and I didn't think of the solution, I felt like I couldn't figure it out myself, but I remembered the previous problem so I was able to solve this

  • @v3updates649
    @v3updates649 4 місяці тому

    Had to watch twice to finally get it. Thanks for making these videos🙂

  • @chukkalasaiganadev79
    @chukkalasaiganadev79 4 місяці тому

    Great explanation . ❤
    I tried brute force first but failed as 17/19 test cases passed. Again i optimised the space to O(max) then the code got submitted but still the time and space complexity is huge. Tried and tried... but i wasn't able to optimise. I thought of taking hints from this solution.
    First hint: Binary Search.... No idea to move further .
    Second hint: Finding the no. of pairs which are less than X in O(n) average time complexity. Still confused.
    Third Hint : Applying two pointers to count.
    After third hint i got the solution and understood the solution.

  • @KoiDB
    @KoiDB 4 місяці тому

    Do you have to continue counting the number of pairs with differences

  • @PhanNghia177
    @PhanNghia177 4 місяці тому

    This one is remind me of problem 4. Median of 2 sorted array
    I think this is almost impossible to solve it in the first time unless u have a really good base in mathematic :D

  • @zweitekonto9654
    @zweitekonto9654 4 місяці тому

    This becomes more interesting if we need to find the kth distinct smallest diff

  • @sankhadip_roy
    @sankhadip_roy 4 місяці тому

    can do r=nums[-1] as it is already sorted , improves runtime

  • @spacebreak8032
    @spacebreak8032 4 місяці тому +1

    The Code :
    The Intuition and thought process:💀

  • @FizzaAhmad-up8ns
    @FizzaAhmad-up8ns 4 місяці тому +1

    Thank you so much Sir..!

  • @AbdulWahab-jl4un
    @AbdulWahab-jl4un 4 місяці тому +1

    Biro ur a godammm genius !!!!!!!!!!!!!

  • @anandsrikumar007
    @anandsrikumar007 4 місяці тому +1

    I did an easy brute force and it passes 18/19 cases

  • @santiagoramirez851
    @santiagoramirez851 4 місяці тому

    Neetcode = The G.O.A.T

  • @akialter
    @akialter 4 місяці тому

    Got asked this problem while applying as a server for a restaurant

  • @putnam120
    @putnam120 4 місяці тому

    Where does it state that the numbers are positive? I didn't see it in the problem statement you showed. Same for the limits on num[i].

  • @MP-ny3ep
    @MP-ny3ep 4 місяці тому

    Well explained. Thank you !

  • @homyakMilashka
    @homyakMilashka 4 місяці тому

    Great explanation, thank you

  • @randsam6629
    @randsam6629 4 місяці тому +2

    this is too hard yaar,not able to understand even with your explaination

  • @kamranriyaz6717
    @kamranriyaz6717 4 місяці тому

    i was thinking instead of using sliding window on every binary search, why dont we use dynamic programming and store the number of pairs with 0 difference, 1 diff , 2 diff etc. .... that way we dont have to use 2 pointer every time .

  • @siddharthsinghverma1062
    @siddharthsinghverma1062 4 місяці тому

    I got the intuition and coded it myself using c++ . Well my question is how am I supposed to come to this approach myself?

  • @OwenWu-f9t
    @OwenWu-f9t 2 місяці тому

    why are we setting r to m instead of m - 1? why don't we just do the while l

  • @SourceCode-q8h
    @SourceCode-q8h 4 місяці тому

    wont the search space be 0 to nums[n-1]-nums[0] when nums is sorted?

  • @pastori2672
    @pastori2672 4 місяці тому

    this one is a career crusher

  • @flavorfabs
    @flavorfabs 4 місяці тому

    I guess I might've missed it, but how do we know that the solution will be between 0 and the max element in the array?
    I'm not understanding the max element portion.

    • @NeetCodeIO
      @NeetCodeIO  4 місяці тому

      Since we calculator absolute values, none of the pair differences can be outside that range

    • @flavorfabs
      @flavorfabs 4 місяці тому

      @@NeetCodeIO Ahh. Okay that makes sense!

  • @pianokage
    @pianokage 4 місяці тому +2

    Gyatt, awesome explanation for such a tricky problem

  • @hemantparmar4604
    @hemantparmar4604 4 місяці тому

    Can anyone explain how the sliding window is O(n). Because the inner while loop also get executed a lot ... is it not significant..?

  • @nptel1punith929
    @nptel1punith929 4 місяці тому

    Looks more like magic to me😆😆

  • @heybeachMIN
    @heybeachMIN 3 місяці тому

    why we take max(nums) except len(nums) - 1? Sry for mb silly quiestion, but i can't understand : (
    And one more, if we take max(nums) we can get Error index out of range, coz max num can be like 10^6 and max length of massive can be 10^5 for example, am I wrong??
    Pls help me to understand!

  • @speedblash
    @speedblash 4 місяці тому +1

    tried heap solution but still got a TLE 18/19

  • @thndesmondsaid
    @thndesmondsaid 4 місяці тому

    why is m considered a potential difference? Don't differences rely on the values themselves, not index values?

    • @thndesmondsaid
      @thndesmondsaid 4 місяці тому

      like if input array was [0,100,200] I get that the max possible diff is 200. However how does m relate to that.
      oh I see! I think the `diff` value we are comparing the two pointer diffs to is nums[m], not the index value itself.
      So in the first round here, m=1, nums[m] = 100. So we do the two pointer approach to get all diffs

    • @thndesmondsaid
      @thndesmondsaid 4 місяці тому

      oh finally! For anyone else confused about this, l and r are NOT index values. They are values in the range 0 -> max(nums). Therefore, in my example above, the first value of `m` would be 100, NOT 1 (if it were a index based binary search).

  • @mugdhadas7413
    @mugdhadas7413 4 місяці тому

    How the hell i will came up with this idea with that much efficiency within 20 minute timespan

  • @kapilkhandelwal48
    @kapilkhandelwal48 4 місяці тому

    counting sort worked for cpp

  • @soumyajitchatterjee5822
    @soumyajitchatterjee5822 4 місяці тому +1

    Damn thats crazy

  • @krupakarreddy1758
    @krupakarreddy1758 3 місяці тому

    Me at the start : ooh! This looks simple, why is it in hard level
    Me at the end of video : I need to have RTX 4090 to process this information 😢

  • @myfavouritecolorisgreen
    @myfavouritecolorisgreen 4 місяці тому

    thanks a lot :')

  • @ajitpalsingh606
    @ajitpalsingh606 4 місяці тому +1

    almost coded my self

    • @zweitekonto9654
      @zweitekonto9654 4 місяці тому

      Damn you must be very simple if you were able to code yourself.

    • @ajitpalsingh606
      @ajitpalsingh606 4 місяці тому

      @@zweitekonto9654 means?

  • @tuanhungphamcong1340
    @tuanhungphamcong1340 4 місяці тому

    mind bending

  • @6leok155
    @6leok155 3 місяці тому

    question: how do you get your search range if you don’t get all pairs 😢

  • @edanurisk3410
    @edanurisk3410 4 місяці тому

    my brain gived error but thank you so much for solution

  • @hwang1607
    @hwang1607 4 місяці тому

    i thought it would let me get away with a brute force heap

  • @hwang1607
    @hwang1607 4 місяці тому

    this is a pretty hard question

  • @sundew_ii
    @sundew_ii 4 місяці тому

    17/19 brute force gang

  • @juanmacias5922
    @juanmacias5922 4 місяці тому

    Another EGO CRUSHER! xD

  • @deepakjain4481
    @deepakjain4481 4 місяці тому

    its scary difficult

  • @Ryan-hk5yb
    @Ryan-hk5yb 4 місяці тому

    25 mins, im cooked

  • @chinmoydebnath353
    @chinmoydebnath353 4 місяці тому

    It feels like we are coding for some low memory 80s device where every space counts. Its 2024 memory is cheap, why do we even care about space complexity.

    • @emenikeanigbogu9368
      @emenikeanigbogu9368 4 місяці тому

      it's supposed to test how well you can actually think. Leetcode isn't supposed to be practical it's supposed to test how good of a problem solver you are.

  • @il5083
    @il5083 4 місяці тому +1

    I thought my heap solution is good enough with the time complexity of O(k·log(n)), sadly still TLE.

  • @6leok155
    @6leok155 3 місяці тому

    the first time neetcode won’t work for me

  • @GliderOne-uo2jy
    @GliderOne-uo2jy 4 місяці тому

    Let's go sleep ma broder

  • @jonsmith8579
    @jonsmith8579 4 місяці тому

    NeetCode

  • @nanicreations7729
    @nanicreations7729 4 місяці тому

    :(((

  • @aashishbathe
    @aashishbathe 4 місяці тому +2

    BRO I came in 40 seconds, 0 views.

  • @pragyanvarshney17
    @pragyanvarshney17 4 місяці тому

    Your while loop won't even execute.