TWO SUM II - Amazon Coding Interview Question - Leetcode 167 - Python

SdĂ­let
VloĆŸit
  • čas pƙidĂĄn 26. 07. 2024
  • 🚀 neetcode.io/ - A better way to prepare for Coding Interviews
    đŸ„· Discord: / discord
    🐩 Twitter: / neetcode1
    🐼 Support the channel: / neetcode
    💡 CODING SOLUTIONS: ‱ Coding Interview Solut...
    💡 DYNAMIC PROGRAMMING PLAYLIST: ‱ House Robber - Leetco...
    đŸŒČ TREE PLAYLIST: ‱ Invert Binary Tree - D...
    💡 GRAPH PLAYLIST: ‱ Course Schedule - Grap...
    💡 BACKTRACKING PLAYLIST: ‱ Word Search - Backtrac...
    💡 LINKED LIST PLAYLIST: ‱ Reverse Linked List - ...
    Solve it yourself: neetcode.io/problems/two-inte...
    0:00 - Intuition / Brute force
    3:55 - Two pointer / optimal
    6:39 - Coding two pointer
    #Coding #Programming #CodingInterview
    Disclosure: Some of the links above may be affiliate links, from which I may earn a small commission.
  • Věda a technologie

Komentáƙe • 294

  • @NeetCode
    @NeetCode  Pƙed 4 lety +40

    🚀 neetcode.io/ - I created a FREE site to make interview prep a lot easier, hope it helps! ❀

    • @liairi6834
      @liairi6834 Pƙed 2 lety +1

      the video's title should be 167 instead of 157đŸ€Ł

    • @NeetCode
      @NeetCode  Pƙed 2 lety +2

      @@liairi6834 Just fixed, surprised no one noticed until now lol

    • @boluaygepong5920
      @boluaygepong5920 Pƙed 2 lety +3

      Do you use blue switches???

    • @PavelPalancica
      @PavelPalancica Pƙed 3 měsĂ­ci

      Thanks for the video. I would add a if sum == target break as first condition in the while loop. Technically, the return [] should never be executed, and we should avoid such code (generally speaking, if the code is there - it must be executed in some edge cases, and I prefer to not have incorrect code, even if it will never be reached).

  • @illuminado538
    @illuminado538 Pƙed 3 lety +204

    high quality explanations, honestly way better than most channels on this site. great work

    • @CostaKazistov
      @CostaKazistov Pƙed 3 lety +8

      ...and on top of that - high quality microphone setup

  • @vetoramireziii6218
    @vetoramireziii6218 Pƙed 2 lety +112

    I like how you also included the brute force solution. Thanks a lot!

  • @Gabriel-cd5jx
    @Gabriel-cd5jx Pƙed 2 lety +24

    The beauty about these challenges is that the code is simple but the logic to get to an optimal solution is quite complex.

  • @canete_code
    @canete_code Pƙed 5 měsĂ­ci +3

    One of the few leetcode mediums I've been able to solve alone, just by watching your videos with similar problems. Really appreciate the help

  • @MegaWinner16
    @MegaWinner16 Pƙed 2 lety +15

    The solution itself is quite intuitive, the nontrivial part of this question is explaining why it always works (which I'm pretty sure the interviewer will ask).
    More specifically, at each step we only consider moving the lower pointer up or the upper pointer down (in order to increase or decrease the sum resp), why do we not need to consider moving both pointers up or down at the same time (which might change the sum)?
    Proof: Suppose exists a sorted array of n such that exists 2 indexes a,b that give the required sum, WLOG a

  • @DanielSmith-uj7rr
    @DanielSmith-uj7rr Pƙed 2 lety +3

    Hey There! I always look for your solutions in the CZcams first and then I move it to someone if I couldn't find your solution available to understand the leet code challenges. Thank you for all your efforts to demonstrate the leet code solutions. It really help us. Thank you! Please post as many solutions you can from leet code.

  • @FluidEnjoyer
    @FluidEnjoyer Pƙed 2 lety +6

    Really clear explanation with no useless information and a smart solution on top of that.👍

  • @mkSkeptics
    @mkSkeptics Pƙed 2 lety +2

    You got a new subscriber in your first couple of minutes! I would love to see & hear more from you, great!

  • @srinadhp
    @srinadhp Pƙed 2 lety +3

    That is very sweet solution! Loved it while you explain and arrive at the solution. Keep up the great work!

  • @MinhNguyen-lz1pg
    @MinhNguyen-lz1pg Pƙed rokem +4

    Brilliant mate, consistent quality explanation from the start!

  • @burakb8708
    @burakb8708 Pƙed 2 lety

    That was a great video. I'll be sharing this with some friends for sure.

  • @SiddhantParkar
    @SiddhantParkar Pƙed 2 lety

    Amazing solution. Will keep that in mind about using sorted array to our advantage!

  • @hsoley
    @hsoley Pƙed 2 lety

    Love your videos, they are amazing!

  • @smitshah9085
    @smitshah9085 Pƙed 4 lety +3

    Thank you, this was very helpful.

  • @meghanapg7194
    @meghanapg7194 Pƙed rokem

    Your solutions are the best. Thanks!

  • @gadgetguy6651
    @gadgetguy6651 Pƙed 2 lety +2

    Amazing explanation !

  • @TheZayzoo
    @TheZayzoo Pƙed 2 lety +117

    No way amazon asked this simple question 😂, I took 2 coding interviews with amazon and its always matrices or something difficult.

    • @robr4501
      @robr4501 Pƙed 2 lety

      what was the question?

    • @begenchorazgeldiyev5298
      @begenchorazgeldiyev5298 Pƙed 2 lety +12

      @@robr4501 we cannot share but mine were def on leetcode. Just different wording

    • @nero9985
      @nero9985 Pƙed 2 lety +1

      I got house robber on one of my FAANG interviews

    • @PippyPappyPatterson
      @PippyPappyPatterson Pƙed 2 lety +3

      @@nero9985 which FAANG? Curious who's still asking DP

    • @AyushSachan2211
      @AyushSachan2211 Pƙed rokem +2

      ​@@PippyPappyPattersoneveryone is asking dp

  • @kamaboko1
    @kamaboko1 Pƙed 3 lety +3

    Great explanation!

  • @adveshdarvekar7733
    @adveshdarvekar7733 Pƙed měsĂ­cem

    It feels so good when you solve using the exact method I was thinking about!

  • @SosetaFurioasaJr
    @SosetaFurioasaJr Pƙed 2 lety

    Thanks for the explanation!

  • @denisebishi5212
    @denisebishi5212 Pƙed 2 lety +3

    You’re literally saving my life rnđŸ™đŸŸthank you for these videos

    • @NeetCode
      @NeetCode  Pƙed 2 lety +3

      Happy to help!

    • @DrewLevitt
      @DrewLevitt Pƙed 2 lety +5

      Figuratively! Unless your life literally depends on clever pointer manipulation...

    • @denisebishi5212
      @denisebishi5212 Pƙed 2 lety

      @@DrewLevitt lol! figuratively of course

  • @CriCKiD3
    @CriCKiD3 Pƙed 2 lety

    Great solution, good job ✅

  • @gorsama-2190
    @gorsama-2190 Pƙed 2 lety +8

    The two pointers solution was actually pretty neat 👌

  • @giritejareddy8195
    @giritejareddy8195 Pƙed 3 lety +1

    Please continue to upload videos like this

  • @infinitefretboard
    @infinitefretboard Pƙed 6 měsĂ­ci

    That's a lot easier than I thought it'd be! They mark it as medium, but it's almost like doing a binary search.

  • @amogchandrashekar8159
    @amogchandrashekar8159 Pƙed 4 lety +1

    Great! as always!

  • @joshuao4928
    @joshuao4928 Pƙed 2 lety +61

    Not sure if someone else mentioned this, but it seems to me that you could have also excluded 10 in the first round and 7 in the second round. If the array is sorted and 1 + 10 is greater than the target, then nothing after 1 can be added to 10 either. Same for 7 summed with anything after 3.

    • @jimmy090
      @jimmy090 Pƙed 2 lety +5

      This still results in O(n^2), right?

    • @discomoses360
      @discomoses360 Pƙed 2 lety +3

      @@jimmy090 Yup

    • @TheNuub63
      @TheNuub63 Pƙed 2 lety +2

      I mean yeah, but why waste time with that? It's now like they are thousands of extra iterations. Although I agree with the simple exclusion of >target (9).

    • @daimeunpraytor7984
      @daimeunpraytor7984 Pƙed 2 lety +2

      @@TheNuub63 That works for this case but not for cases with negatives on the left side unless I am misunderstanding your implications.

    • @TheNuub63
      @TheNuub63 Pƙed 2 lety +1

      @@daimeunpraytor7984 if there are negative numbers you are correct! We would have to check everything basically!

  • @mr.goldenball333
    @mr.goldenball333 Pƙed 2 lety

    Amazing solution, thank you sir.

  • @AdityaSharma-wg4rj
    @AdityaSharma-wg4rj Pƙed rokem +1

    best LC python solutions. I recommend this to everyone!

  • @ahmedaj2000
    @ahmedaj2000 Pƙed 2 lety

    clear explanation, thanks!

  • @somefreshbread
    @somefreshbread Pƙed 2 lety +2

    Key thing I think you missed deleting array items is that you could have deleted, for example, the 10 in the first one, because if 1+10 > 9, then clearly n+1+10 is going to be correct.

  • @bhaskyOld
    @bhaskyOld Pƙed 2 lety

    Thank you NeetCode

  • @danielzuzevich4161
    @danielzuzevich4161 Pƙed 3 lety +2

    heroic explanation

  • @floydian25
    @floydian25 Pƙed rokem

    such an underrated channel

  • @mr.fusion9872
    @mr.fusion9872 Pƙed 2 lety +3

    love your channel. really well done videos. hoping to get FANG now :)

  • @Louis-qy8uh
    @Louis-qy8uh Pƙed rokem

    nice explanation, thanks!

  • @rajarajan1338
    @rajarajan1338 Pƙed 6 měsĂ­ci +1

    We can use hash mapping to...
    _hash = {}
    for index, i in enumerate(numbers):
    complement = target - i
    if complement in _hash:
    return [_hash[complement] + 1, index+1]
    _hash[i] = index
    i = 2, complement = 9-2 => complement = 7. It will check key 7 is in the hash, if not it will add key 2 in hash
    i = 7, complement = 9-7 => complement = 2. Key 2 is present in hash, so it returns index of key 2 and i (add 1 at return because index is starting from 1)

    • @Ab7636_6
      @Ab7636_6 Pƙed 3 měsĂ­ci +2

      It uses extra space ...
      //O(log n) best solution 🎉
      if (numbers.size() target)
      r = mid - 1;
      else
      r--;
      }
      }
      return {-1, -1};

  • @prabinlamsal5125
    @prabinlamsal5125 Pƙed rokem +1

    So, in 2sum 2 as compared to 2sum, we use the fact that the array is sorted to take the best-case space complexity from O(n) to O(1).

  • @shivarammuthukumaraswamy7164

    Thank you so much

  • @regnam503
    @regnam503 Pƙed 7 měsĂ­ci +1

    I considered two pointers at first but for some reason decided that it wouldn't work. I went with finding the complement by binary search which was kind of an overkill but gave me an obviously suboptimal O(n*logn). Still, better than brute force.

  • @mohamednkadi7729
    @mohamednkadi7729 Pƙed rokem

    We can stop at 10 from the first iteration since 1+ 10 is 11. No need to continue to 11 as you mentioned and also not to consider 10. So the second iteration array is 3457

  • @denzildk
    @denzildk Pƙed 2 lety +1

    This looks good for small arrays, but my guess at a solution for a bigger array would be to use a log search for the number closest to half of the target, eliminating any Halves of the given array who's numbers were above the target, and then use the same method you did to find the pair, except go outward from the middle, where the numbers closest to half of the target are, instead of going inward from the ends.
    In good cases that would reduce the amount of searches you would need, although it would give an upper bounds of a n log n runtime if none of the elements were higher than the target.

    • @mhtwedt
      @mhtwedt Pƙed 2 lety +1

      Hey, thats a good thought! but that wouldn't work if say, all the numbers in the middle 50% are even, and all the numbers in each outer quartile were odd.

  • @tejaswihegde9384
    @tejaswihegde9384 Pƙed rokem

    beautifully explained

  • @ardemus
    @ardemus Pƙed 2 lety +1

    This is satisfyingly efficient. Note that you can initialize r to the smaller the length of the array or the target number. The smallest possible values in numbers[0] and numbers[x] are 1 and x-1, thus the smallest sum is x, and r will always be

    • @nikhil_a01
      @nikhil_a01 Pƙed rokem +2

      This doesn't work if the array can contain negative numbers. LeetCode's constraints say that -1000

    • @romanpisani8157
      @romanpisani8157 Pƙed měsĂ­cem

      non decreasing does not mean the same thing as increasing. It could be the same number many times

    • @ardemus
      @ardemus Pƙed měsĂ­cem

      ​@@romanpisani8157 It is correct, a non-descending array of integers can include duplicate values. However, note that you're responding to an old comment and there is a lot of evidence that the problem details have changed more than once over the years. I may well have made a mistake back then, but we can't really know without the context I was in at the time.

  • @theornament
    @theornament Pƙed 5 měsĂ­ci

    I managed to do this very elegantly without looking at any help. I'm proud of myself, a week ago I was very bad at this.
    Here's my solution:
    def twoSum(self, numbers: List[int], target: int) -> List[int]:
    i = 0
    j = len(numbers) - 1
    while numbers[i] + numbers[j] != target:
    if numbers[i] + numbers[j] < target:
    i += 1
    else:
    j -= 1
    return [i + 1, j + 1]
    It's a little bit more elegant as we don't compare the index numbers but the values of the array in those indexes. That's the condition of our while loop. I find it more readable this way.
    Either way, great explanation as always.

    • @brhnkh
      @brhnkh Pƙed 2 měsĂ­ci

      nums =[3], target =6 fails this

  • @dancingdragon1143
    @dancingdragon1143 Pƙed rokem +5

    Quick note, this technique only works assuming the list is sorted. So in an interview you have to ask if the indices of the original list being returned is one of the constraints. Given that when you sort the original list the indices of what add up to the target will change.

  • @debashishmahato4591
    @debashishmahato4591 Pƙed 5 měsĂ­ci

    added this program to my list

  • @saimmehmood6936
    @saimmehmood6936 Pƙed 3 lety

    this is beautiful!

  • @kayodeogunrinde7380
    @kayodeogunrinde7380 Pƙed rokem

    Bro you're a genius.

  • @EranM
    @EranM Pƙed 3 měsĂ­ci

    This guy talking and typing.. TOP ASMR CHANNEL!!!

  • @asagiai4965
    @asagiai4965 Pƙed 2 lety

    I think the first part of the solution is finding r

  • @sharuksk5801
    @sharuksk5801 Pƙed rokem

    Thank you man!!.

  • @iworeushankaonce
    @iworeushankaonce Pƙed 2 lety +1

    target = 9
    lst = [1,4,5,7,10,11]
    for i, el in enumerate(lst):
    if (target-el) in lst:
    val1 = i
    val2 = lst.index(target-el)
    break
    print(val1+1,val2+1)

    • @Harish_Prince_
      @Harish_Prince_ Pƙed rokem +1

      Great answer. But time complexity is O(nÂČ). Since the index() takes O(n) time complexity ✹

  • @mnchester
    @mnchester Pƙed 2 lety +1

    This question is now a Medium! Lol, LeetCode should make it possible for users (at least paid ones) to have an input on the difficulty of problems.

  • @SajedulKarim_mesuk
    @SajedulKarim_mesuk Pƙed 2 lety

    nice explanation

  • @JulianoNaves
    @JulianoNaves Pƙed 2 lety

    Awesome. Thanks.

  • @jst8922
    @jst8922 Pƙed 6 měsĂ­ci

    When you have sorted array, and target= 9, you can throw away all elements from array at the beginning (before running algorithm code), which are greater than target (15 for this example), because we are doing Two Sum (addition with two numbers)

  • @expansivegymnast1020
    @expansivegymnast1020 Pƙed rokem

    NeetCode for president.

  • @TarunKumar-ff8lj
    @TarunKumar-ff8lj Pƙed 2 lety

    This can be solved using binary search as well

  • @johnvonhorn2942
    @johnvonhorn2942 Pƙed 2 lety +1

    Had I done this I would have coded option #1 and felt good about myself. Clearly I'm a beta programmer and not a chad coder.

  • @moade5700
    @moade5700 Pƙed rokem +1

    Why not use binary search on the items after the current ?

  • @mjprescotti
    @mjprescotti Pƙed rokem

    This video was amazing! Thank you, thank you & thank you! (or thank you * 3 :))

  • @chiragrajpurohit6998
    @chiragrajpurohit6998 Pƙed rokem

    i used the same two sum solution and added +1 returning index. works smoothly

    • @MohamedMosatafa
      @MohamedMosatafa Pƙed rokem

      Yes, I wonder why we can't use the same approach here since it's still O(n) complexity.

    • @caca738
      @caca738 Pƙed 10 měsĂ­ci

      @@MohamedMosatafaUsing 2 pointers has space of O(1), don’t know if it is stated anywhere that it has to be that though but this is the most optimal.

  • @PippyPappyPatterson
    @PippyPappyPatterson Pƙed 2 lety +1

    One of the most impressive parts of your leetcode skillz is the ability to draw everything cleanly using a mouse lol

  • @muhammadal-khwarizmi6933
    @muhammadal-khwarizmi6933 Pƙed 3 lety +2

    Great video. I used it for Ruby and am in the 95th percentile for speed.

  • @DavidDLee
    @DavidDLee Pƙed 2 lety +6

    Looks like sub-linear is possible, instead of moving the pointers to the next position, do a binary search for the number you need or the one right after it.

    • @zwanchis
      @zwanchis Pƙed 2 lety

      Binary search is possible, you can even invert the list to improve performance

    • @spencer3
      @spencer3 Pƙed 2 lety

      @@zwanchis how does that improve performance? I could possibly see readability, but isn't it just the mirror of the given array? That would mean you just swap certain operations, right?

    • @aminafounoun
      @aminafounoun Pƙed 2 lety

      What about time complexity? Are you going to apply binary search for each element?

    • @DavidDLee
      @DavidDLee Pƙed 2 lety

      @@aminafounoun Time complexity could be sub-linear by changing the proposed algorithm, of complexity O(N), to instead of moving the right or left pointers just by one, doing a binary search for the value that will be needed. Using the above example, left pointer -> 1, right pointer could be found by looking for 8 (= 9 - 1) using a binary search. The result of the search will yield 7, the entry available in the next position. Then, search for 2 (= 9 - 7), etc. The boundaries of the search narrowing each time. With the resulting complexity O(LogN), because we did not need to examine every position and taking advantage of the sorted order of entries.

    • @nikhil_a01
      @nikhil_a01 Pƙed rokem

      @@DavidDLee This does multiple binary searches though, so it will only be O(log N) if the number of binary searches is constant, i.e. the number of searches doesn't increase as N increases.
      I don't know if that's true for the average case, but you can find a worst- case example that is O(N log N).
      When nums = [1,3,5,6,7,9,11] and target = 13, the left and right pointers alternate between which one has to move. It ends up doing approximately N binary searches.
      Even though the array to search decreases by 1 each time, summing up log N + log (N-1) + ... + 2 + 1 is still O(N log N).

  • @macdjord
    @macdjord Pƙed 2 lety +5

    One improvement I'd suggest: Lets say your array in all the numbers 1 through 1 million, and you target is 10. You'd waste a lot of time decrementing the right pointer one step at a time. Alternately, if your target is 1.9 million, you waste time slowly incrementing the left pointer. It would be more efficient to use a gallop search to find the next element to stop at each time.

    • @MoogieSRO
      @MoogieSRO Pƙed 2 lety +2

      What's a gallop search?

    • @macdjord
      @macdjord Pƙed 2 lety +1

      @@MoogieSRO It's where you jump 1 item, then 2, then 4, then 8, etc..
      Basically, you know what a binary search is? Where you know that x is too low and y is too high, so you check halfway between them? And if the middle point is too low, it becomes your new x, and if its too high, it becomes your new y? Well, gallop search is what you use when you have an x which is too low, but don't know where the y which is too high starts.

    • @MoogieSRO
      @MoogieSRO Pƙed 2 lety +2

      @@macdjord Ahh I see. Thanks for the explanation!

  • @saminchowdhury7995
    @saminchowdhury7995 Pƙed rokem

    Why why why didn't I figure that out. Thank you master

  • @5vart5ol
    @5vart5ol Pƙed 2 lety

    Does it point out that it has to be positive numbers in the array?

  • @thelonearchitect
    @thelonearchitect Pƙed rokem

    Somehow this has grown into a Medium problem in LC. You might want to move it to another playlist.

  • @pinakadhara7650
    @pinakadhara7650 Pƙed rokem

    This was genius.

  • @user-uj3ew6fm8r
    @user-uj3ew6fm8r Pƙed 4 lety +6

    u an actual NEET? i am rn but only b/c i chose a shitty major
    i'm trying to get into CS industry after this by doing more leetcode and self-teaching algos
    do u have a discord?

    • @user-uj3ew6fm8r
      @user-uj3ew6fm8r Pƙed 4 lety

      my discord is hydro#3651

    • @NeetCode
      @NeetCode  Pƙed 4 lety +3

      Haha, technically I am a NEET right now, but maybe not in its true meaning. Good luck with self-teaching, it's definitely possible because many people have been successful doing that.

  • @Zinxiee
    @Zinxiee Pƙed 3 dny

    @NeetCode Can I ask if it would be acceptable to use the same theory behind the first Two Sum question (Leetcode 1) in this problem? Logging the difference between the target and the current number in a hashmap would also work no?

  • @champion5946
    @champion5946 Pƙed 2 lety

    thanks

  • @naimeimran3247
    @naimeimran3247 Pƙed 2 lety

    Thanks

  • @s.a.somersault3973
    @s.a.somersault3973 Pƙed 2 lety +2

    1:49 be careful. The statement says integers, so there could be negative numbers and hence there could perfectly be a combination (l,r) with r>T>=0>l (where l is the first element of the solution tuple and r the second, and T is our target value) such as (l+r)==T.
    Great video!!!!!! 😃😃💯
    Edit: I had misunderstood the brute force strategy. I guess it can also work for negative numbers, too.

    • @witchedwiz
      @witchedwiz Pƙed 2 lety

      Technically a valid point, but if we assume the array sorted, the approach works nonetheless ;)

  • @lch99310
    @lch99310 Pƙed 2 lety

    What if there is duplicate numbers in the array? should we add one more condition to deal with that?

  • @yuurishibuya4797
    @yuurishibuya4797 Pƙed rokem

    What about a binary search for the complement? Where complement = target - first.
    Starting from first, search for the complement, if not available, move on to the next value.
    This o(n) as well.

    • @heyyayesh
      @heyyayesh Pƙed rokem

      That will be O(n.log n) as binary search is O(log n) itself and you might have to search n-1 times in the worst case.

  • @sapnavats9105
    @sapnavats9105 Pƙed 3 lety +5

    How did you think of using two pointers? I used binary search and wrote a really ugly code

    • @dylanmartin998
      @dylanmartin998 Pƙed 2 lety

      generally speaking you can use two pointer solutions for any of the various Two Sum style problems

  • @Kitsune_Dev
    @Kitsune_Dev Pƙed 3 měsĂ­ci

    wouldn’t it be faster if we cut out the numbers that are greater or more than target as well?

  • @TimHoefer
    @TimHoefer Pƙed 2 lety

    Wouldn't this be similar but slightly more efficient? (assumes 1-based array indexes)
    n=# array elements
    for x from 1 to n-1
    for y from x+1 to n
    if value[y]>=9-value[x] break
    is value[y]=9-value[x] DONE - FOUND IT!

    • @Insideoutcest
      @Insideoutcest Pƙed 2 lety

      not more efficient or even viable. consider negative numbers.

  • @Kokurorokuko
    @Kokurorokuko Pƙed 2 lety +4

    This was surprisingly easy. I doubt it's a real interview question.

    • @deckardbarnes6715
      @deckardbarnes6715 Pƙed 2 lety

      Maybe for interns or new grads

    • @eile4219
      @eile4219 Pƙed rokem

      for phone screen interviews and this is not the final solution. They are actually looking for binary search with two points.

  • @nero9985
    @nero9985 Pƙed 2 lety

    If I got asked this question on an interview, I'd do a backflip

  • @sanooosai
    @sanooosai Pƙed 6 měsĂ­ci

    great thank you

  • @comarnicolodi
    @comarnicolodi Pƙed 2 lety

    Very cool

  • @thiagot7706
    @thiagot7706 Pƙed 2 lety

    This challenge is actually medium level now (on leetcode)

  • @shadyapp7416
    @shadyapp7416 Pƙed 10 měsĂ­ci

    Which one js better the hashing way or this one?

  • @guynameddan427
    @guynameddan427 Pƙed 2 lety +2

    Great video. Thanks! I have a dumb question. Why couldn't I use the same method from the first version of two sum to solve this?...

    • @jphill3426
      @jphill3426 Pƙed 2 lety

      I used the method from the first version and added +1 to returns and it worked fine

    • @enfieldli9296
      @enfieldli9296 Pƙed 2 lety

      This one is sorted, so the first one using this solution will miss the mark

    • @heatchecknyc2142
      @heatchecknyc2142 Pƙed rokem +1

      This problem says you must use O(1) space while the Traditional 2sum uses a hashmap

  • @zaqxswcdevfr40
    @zaqxswcdevfr40 Pƙed 2 lety

    Thanks!

  • @BrknSoul
    @BrknSoul Pƙed 2 lety

    Couldn't you add a check "if r > target r-=1" (if right pointer greater than target number, decrement right pointer)?

    • @Kokurorokuko
      @Kokurorokuko Pƙed 2 lety

      why would you compare an index with a desired sum?

    • @BrknSoul
      @BrknSoul Pƙed 2 lety

      @@Kokurorokuko I meant the number at index r, rather than index r itself.

  • @jiquandeng7110
    @jiquandeng7110 Pƙed rokem

    class Solution:
    def twoSum(self, numbers: List[int], target: int) -> List[int]:
    i = 0
    j = len(numbers)-1
    while numbers[i] + numbers[j] != target:
    if numbers[i] +numbers[j] > target:
    j -= 1
    elif numbers[i] +numbers[j] < target:
    i += 1
    return [i+1,j+1]

  • @ranjithragul
    @ranjithragul Pƙed rokem

    difficult level changed from (Easy to Medium)

  • @sraxler
    @sraxler Pƙed 9 měsĂ­ci

    I get that we can use this solution, but why don’t we use the Hashmap one pass solution? Is it because we occupy O(n) space and that isn’t optimal?

  • @qwrt9626
    @qwrt9626 Pƙed rokem +2

    A quick performance increase for edge cases:
    Add a conditional that checks for length 2. Given we know that there has to exist a valid solution in each test set (as per instructions), a length of two means you can return those values without setting up the pointers. Also, modifying the original array values to instead be 1 and 2 and returning it will also lower space usage (but keep in mind this is not best practice).
    For Java I got a 99.2% runtime and 74% memory using these tricks. And I've found atleast in the case of leetcode that a lot of the easy/med problems can be slightly optimized when the solution is guaranteed to exist by doing this setup.

    • @Mo-cn9kd
      @Mo-cn9kd Pƙed rokem

      how would u do either of those? not sure if its just me but I don't understand your explanations >.

  • @akagamishanks7991
    @akagamishanks7991 Pƙed 10 měsĂ­ci

    @neetcode if happen to read this! THANK YOU FAM!

  • @-_______________________.___

    So are we supposed to come up with these solutions ourselves or are we supposed to just do a bunch of questions and memorize these solutions and use them on similar questions that come up with different wording??

  • @mohamedmagdy4522
    @mohamedmagdy4522 Pƙed rokem

    amaaaaazing

  • @MrMidjji
    @MrMidjji Pƙed 2 lety +2

    If you use binary search to find the starting point for pointer two you get a significant perf boost. Further, the statement you may assume that each input has exactly one solution means that the elements of the solution are unique, which means you dont increment the pointer by 1, you find the next unique value by binary search. Meaning the solution is log(n).

    • @nikhil_a01
      @nikhil_a01 Pƙed rokem +1

      This does multiple binary searches though, so it will only be O(log N) if the number of binary searches is constant, i.e. the number of searches doesn't increase as N increases.
      I don't know if that's true for the average case, but you can find a worst- case example that is O(N log N).
      When nums = [1,3,5,6,7,9,11] and target = 13, the left and right pointers alternate between which one has to move. It ends up doing N binary searches.
      Even though the array to search decreases by 1 each time, summing up log N + log (N-1) + ... + 2 + 1 is still O(N log N).

  •  Pƙed 2 lety

    Why don't you remove 10 in the first iteration and 7 in the second one?