Тёмный

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

NeetCode
Подписаться 815 тыс.
Просмотров 405 тыс.
50% 1

Опубликовано:

 

16 сен 2024

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 297   
@NeetCode
@NeetCode 4 года назад
🚀 neetcode.io/ - I created a FREE site to make interview prep a lot easier, hope it helps! ❤
@liairi6834
@liairi6834 3 года назад
the video's title should be 167 instead of 157🤣
@NeetCode
@NeetCode 3 года назад
@@liairi6834 Just fixed, surprised no one noticed until now lol
@boluaygepong5920
@boluaygepong5920 2 года назад
Do you use blue switches???
@PavelPalancica
@PavelPalancica 5 месяцев назад
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 4 года назад
high quality explanations, honestly way better than most channels on this site. great work
@CostaKazistov
@CostaKazistov 3 года назад
...and on top of that - high quality microphone setup
@vetoramireziii6218
@vetoramireziii6218 2 года назад
I like how you also included the brute force solution. Thanks a lot!
@Gabriel-cd5jx
@Gabriel-cd5jx 2 года назад
The beauty about these challenges is that the code is simple but the logic to get to an optimal solution is quite complex.
@MegaWinner16
@MegaWinner16 2 года назад
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
@aradfir3441
@aradfir3441 20 дней назад
I was wondering this exact same question! Thank you so much!
@canete_code
@canete_code 6 месяцев назад
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
@TheZayzoo
@TheZayzoo 2 года назад
No way amazon asked this simple question 😂, I took 2 coding interviews with amazon and its always matrices or something difficult.
@robr4501
@robr4501 2 года назад
what was the question?
@begenchorazgeldiyev5298
@begenchorazgeldiyev5298 2 года назад
@@robr4501 we cannot share but mine were def on leetcode. Just different wording
@nero9985
@nero9985 2 года назад
I got house robber on one of my FAANG interviews
@PippyPappyPatterson
@PippyPappyPatterson 2 года назад
@@nero9985 which FAANG? Curious who's still asking DP
@AyushSachan2211
@AyushSachan2211 Год назад
​@@PippyPappyPattersoneveryone is asking dp
@prabinlamsal5125
@prabinlamsal5125 Год назад
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).
@joshuao4928
@joshuao4928 2 года назад
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 2 года назад
This still results in O(n^2), right?
@discomoses360
@discomoses360 2 года назад
@@jimmy090 Yup
@TheNuub63
@TheNuub63 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 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 2 года назад
@@daimeunpraytor7984 if there are negative numbers you are correct! We would have to check everything basically!
@FluidEnjoyer
@FluidEnjoyer 2 года назад
Really clear explanation with no useless information and a smart solution on top of that.👍
@theornament
@theornament 7 месяцев назад
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 3 месяца назад
nums =[3], target =6 fails this
@messagegc
@messagegc Месяц назад
​@@brhnkh: If I got the question right, the input is expected to contain numbers that will always add up to target. With that assumption, there cannot be a single number as input. So nums = [3, 3], target = 6 can be a valid example I think.
@brhnkh
@brhnkh 23 дня назад
@@messagegc you're right! the problem actually states len.nums >=2
@iworeushankaonce
@iworeushankaonce 2 года назад
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_ Год назад
Great answer. But time complexity is O(n²). Since the index() takes O(n) time complexity ✨
@dancingdragon1143
@dancingdragon1143 Год назад
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.
@regnam503
@regnam503 9 месяцев назад
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.
@DavidDLee
@DavidDLee 2 года назад
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 2 года назад
Binary search is possible, you can even invert the list to improve performance
@spencer3
@spencer3 2 года назад
@@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 2 года назад
What about time complexity? Are you going to apply binary search for each element?
@DavidDLee
@DavidDLee 2 года назад
@@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 Год назад
@@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).
@ardemus
@ardemus 2 года назад
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 Год назад
This doesn't work if the array can contain negative numbers. LeetCode's constraints say that -1000
@romanpisani8157
@romanpisani8157 3 месяца назад
non decreasing does not mean the same thing as increasing. It could be the same number many times
@ardemus
@ardemus 3 месяца назад
​@@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.
@MinhNguyen-lz1pg
@MinhNguyen-lz1pg 2 года назад
Brilliant mate, consistent quality explanation from the start!
@DanielSmith-uj7rr
@DanielSmith-uj7rr 2 года назад
Hey There! I always look for your solutions in the RU-vid 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.
@gorsama-2190
@gorsama-2190 2 года назад
The two pointers solution was actually pretty neat 👌
@leeroymlg4692
@leeroymlg4692 9 месяцев назад
*neet
@jst8922
@jst8922 8 месяцев назад
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)
@mapledanish3662
@mapledanish3662 7 месяцев назад
Negative integers tho…
@AdityaSharma-wg4rj
@AdityaSharma-wg4rj Год назад
best LC python solutions. I recommend this to everyone!
@rajarajan1338
@rajarajan1338 7 месяцев назад
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 5 месяцев назад
It uses extra space ... //O(log n) best solution 🎉 if (numbers.size() target) r = mid - 1; else r--; } } return {-1, -1};
@denzildk
@denzildk 2 года назад
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 2 года назад
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.
@mohamednkadi7729
@mohamednkadi7729 Год назад
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
@macdjord
@macdjord 2 года назад
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 2 года назад
What's a gallop search?
@macdjord
@macdjord 2 года назад
@@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 2 года назад
@@macdjord Ahh I see. Thanks for the explanation!
@somefreshbread
@somefreshbread 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.
@infinitefretboard
@infinitefretboard 8 месяцев назад
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.
@MrMidjji
@MrMidjji 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 Год назад
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).
@sapnavats9105
@sapnavats9105 3 года назад
How did you think of using two pointers? I used binary search and wrote a really ugly code
@dylanmartin998
@dylanmartin998 2 года назад
generally speaking you can use two pointer solutions for any of the various Two Sum style problems
@yuurishibuya4797
@yuurishibuya4797 Год назад
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 Год назад
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.
@mkSkeptics
@mkSkeptics 2 года назад
You got a new subscriber in your first couple of minutes! I would love to see & hear more from you, great!
@s.a.somersault3973
@s.a.somersault3973 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 2 года назад
Technically a valid point, but if we assume the array sorted, the approach works nonetheless ;)
@srinadhp
@srinadhp 3 года назад
That is very sweet solution! Loved it while you explain and arrive at the solution. Keep up the great work!
@adveshdarvekar7733
@adveshdarvekar7733 3 месяца назад
It feels so good when you solve using the exact method I was thinking about!
@mnchester
@mnchester 2 года назад
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.
@denisebishi5212
@denisebishi5212 2 года назад
You’re literally saving my life rn🙏🏾thank you for these videos
@NeetCode
@NeetCode 2 года назад
Happy to help!
@DrewLevitt
@DrewLevitt 2 года назад
Figuratively! Unless your life literally depends on clever pointer manipulation...
@denisebishi5212
@denisebishi5212 2 года назад
@@DrewLevitt lol! figuratively of course
@EranM
@EranM 5 месяцев назад
This guy talking and typing.. TOP ASMR CHANNEL!!!
@asagiai4965
@asagiai4965 2 года назад
I think the first part of the solution is finding r
@Nicinic1312
@Nicinic1312 2 года назад
Wouldn't it also be possible to solve this using a tree to store numbers that we want to find ? We start with the first number, and store its "opposite" (in this example, as we see 1, we store 8 inside the tree), and we iterate until we reach a number which is in the tree. Here, it would be : - Add 8 to the tree - Add 6 to the tree - Add 5 to the tree - We inspect 5, and see that's it's already in the tree. Thus, we know that 9-5 = 4 was already in the array, thus we have our pair (4,5). Since we need the index of both, we can either use a label in the tree, a tuple, or just use a HashMap to store numbers that we want to hit as keys (and indexes as values).
@MiloDC
@MiloDC 2 года назад
That takes extra memory. Solution in video avoids excess memory consumption.
@Nicinic1312
@Nicinic1312 2 года назад
@@MiloDC True. If memory consumption is considered, this solution is less efficient, even if the memory cost of a HashMap shouldn't be too high in the end
@user-uj3ew6fm8r
@user-uj3ew6fm8r 4 года назад
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 4 года назад
my discord is hydro#3651
@NeetCode
@NeetCode 4 года назад
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.
@jiquandeng7110
@jiquandeng7110 Год назад
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]
@devduttabiswas2204
@devduttabiswas2204 4 дня назад
My first medium difficulty question that i solved intuituvely
@mr.fusion9872
@mr.fusion9872 2 года назад
love your channel. really well done videos. hoping to get FANG now :)
@nero9985
@nero9985 2 года назад
How's it going?
@CuriousAnonDev
@CuriousAnonDev 2 года назад
Yo???? Where are you, made it?
@moade5700
@moade5700 Год назад
Why not use binary search on the items after the current ?
@danielzuzevich4161
@danielzuzevich4161 3 года назад
heroic explanation
@smitshah9085
@smitshah9085 4 года назад
Thank you, this was very helpful.
@johnvonhorn2942
@johnvonhorn2942 2 года назад
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.
@Qwickset
@Qwickset 2 года назад
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 2 года назад
not more efficient or even viable. consider negative numbers.
@giritejareddy8195
@giritejareddy8195 4 года назад
Please continue to upload videos like this
@SiddhantParkar
@SiddhantParkar 3 года назад
Amazing solution. Will keep that in mind about using sorted array to our advantage!
@chiragrajpurohit6998
@chiragrajpurohit6998 2 года назад
i used the same two sum solution and added +1 returning index. works smoothly
@MohamedMosatafa
@MohamedMosatafa Год назад
Yes, I wonder why we can't use the same approach here since it's still O(n) complexity.
@caca738
@caca738 Год назад
@@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.
@BelisariusAlKhwarizmi
@BelisariusAlKhwarizmi 4 года назад
Great video. I used it for Ruby and am in the 95th percentile for speed.
@kamaboko1
@kamaboko1 3 года назад
Great explanation!
@amitsharmagkp
@amitsharmagkp 2 года назад
This can be further improve. Let say Input = [1, 4 ,6,7,9,10,13,16,17,20] Target = 10 Then we don't need to take last index of input array since 1010 and then follow with logic explained. This will give better performance if make this correct high index finding by using search like jump search since input is already sorted.
@Insideoutcest
@Insideoutcest 2 года назад
would fail if negative numbers were included. problem description: -1000
@burakb8708
@burakb8708 2 года назад
That was a great video. I'll be sharing this with some friends for sure.
@qwrt9626
@qwrt9626 Год назад
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 Год назад
how would u do either of those? not sure if its just me but I don't understand your explanations >.
@PippyPappyPatterson
@PippyPappyPatterson 2 года назад
One of the most impressive parts of your leetcode skillz is the ability to draw everything cleanly using a mouse lol
@MohamedMosatafa
@MohamedMosatafa Год назад
He's probably using a tablet with a stylus.
@Kokurorokuko
@Kokurorokuko 2 года назад
This was surprisingly easy. I doubt it's a real interview question.
@deckardbarnes6715
@deckardbarnes6715 2 года назад
Maybe for interns or new grads
@eile4219
@eile4219 2 года назад
for phone screen interviews and this is not the final solution. They are actually looking for binary search with two points.
@Kitsune_Dev
@Kitsune_Dev 5 месяцев назад
wouldn’t it be faster if we cut out the numbers that are greater or more than target as well?
@guynameddan427
@guynameddan427 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 2 года назад
I used the method from the first version and added +1 to returns and it worked fine
@enfieldli9296
@enfieldli9296 2 года назад
This one is sorted, so the first one using this solution will miss the mark
@heatchecknyc2142
@heatchecknyc2142 Год назад
This problem says you must use O(1) space while the Traditional 2sum uses a hashmap
@BrknSoul
@BrknSoul 2 года назад
Couldn't you add a check "if r > target r-=1" (if right pointer greater than target number, decrement right pointer)?
@Kokurorokuko
@Kokurorokuko 2 года назад
why would you compare an index with a desired sum?
@BrknSoul
@BrknSoul 2 года назад
@@Kokurorokuko I meant the number at index r, rather than index r itself.
@meghanapg7194
@meghanapg7194 2 года назад
Your solutions are the best. Thanks!
@Zinxiee
@Zinxiee Месяц назад
@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?
@akagamishanks7991
@akagamishanks7991 11 месяцев назад
@neetcode if happen to read this! THANK YOU FAM!
@sraxler
@sraxler 11 месяцев назад
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?
@bigzigtv706
@bigzigtv706 2 года назад
I think the best way to do this is to binary search for the index of the first number greater than the target. (Ignore this step if the target is greater than the largest element) then do the double pointer method from there.
@reidyoung298
@reidyoung298 2 года назад
Wouldn't that be O(nlogn) complexity, though?
@omarhosny6947
@omarhosny6947 2 года назад
@@reidyoung298 yes, it runs in O(n * log(n)).
@bigzigtv706
@bigzigtv706 2 года назад
Wouldnt it cut the n time in half on average and convert that first half to log n?
@bigzigtv706
@bigzigtv706 2 года назад
I bet this can be done with two binary search pointers, ill think abt it and get back to you
@thelonearchitect
@thelonearchitect Год назад
Somehow this has grown into a Medium problem in LC. You might want to move it to another playlist.
@floydian25
@floydian25 Год назад
such an underrated channel
@debashishmahato4591
@debashishmahato4591 6 месяцев назад
added this program to my list
@TarunKumar-ff8lj
@TarunKumar-ff8lj 2 года назад
This can be solved using binary search as well
@mr.goldenball333
@mr.goldenball333 2 года назад
Amazing solution, thank you sir.
@behradx
@behradx 10 месяцев назад
Why didn't we eliminate numbers that are larger than target? Aren't all numbers positive?
@shivarammuthukumaraswamy7164
@shivarammuthukumaraswamy7164 4 года назад
Thank you so much
@CriCKiD3
@CriCKiD3 2 года назад
Great solution, good job ✅
@ahmedaj2000
@ahmedaj2000 2 года назад
clear explanation, thanks!
@utkarshkumar7336
@utkarshkumar7336 Год назад
my code TLE'd in c++ class Solution { public: vector twoSum(vector& numbers, int target) { vector ans; int i=0; int j=numbers.size()-1; int sum=0; while(itarget){ j--; } else if(sum
@utkarshkumar7336
@utkarshkumar7336 Год назад
if(sum==target){ ans.push_back(i+1); ans.push_back(j+1); break; } fixed it :)
@-_______________________.___
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??
@tejaswihegde9384
@tejaswihegde9384 2 года назад
beautifully explained
@tonyiommisg
@tonyiommisg 9 месяцев назад
The wording of the problem on leetcode is extremely confusing for such a simple problem and overcomplicated with making the array 1-indexed without it meaningfully changing the problem.
@hsoley
@hsoley 2 года назад
Love your videos, they are amazing!
@amogchandrashekar8159
@amogchandrashekar8159 4 года назад
Great! as always!
@TheJanstyler
@TheJanstyler Год назад
I'm shit at programming, so I'd love to hear from someone if the solution I came up with actually works (memory wise its less efficient then the solution here guaranteed) My solution is basically this: Subtract each number in the array from the target and save the result (probably in a hashmap with the key being the index) and if, at any point, the next number is equal to ine if the reaults, those are the correct numbers. So basically "Target - num[n] = result[n]", result get saved, and if num[n+i] = result[n] thats the solution. Logically it makes sense, I have no idea if there is a proper (and efficient) way to code this though. Could someone tell me if that works?
@ranjithragul
@ranjithragul Год назад
difficult level changed from (Easy to Medium)
@dARKf3n1Xx
@dARKf3n1Xx 2 года назад
since it's sorted, why don't try binary search?
@nikhil_a01
@nikhil_a01 Год назад
Binary search is a good option to consider when you see a sorted array. But what exactly are you planning to search for? You need to find two values that sum up to the target.
@Louis-qy8uh
@Louis-qy8uh Год назад
nice explanation, thanks!
@akashghanate1878
@akashghanate1878 2 года назад
Could have used binary search that would decrease TC from O(n) to O(logn)
@joshgreenwood9390
@joshgreenwood9390 2 года назад
Would be O(nlogn) I believe as you would perform binary search for the second number n times
@defilerzerg9152
@defilerzerg9152 2 года назад
You can use binary search to find an upper bound and exclude all numbers higher than the target at the start. The rest will still be O(n), with better average performance overall (constant factors are ignored by O-notation).
@isaactang9599
@isaactang9599 2 года назад
great solution ! ! I modified it by adding while numbers[r] == numbers[r + 1]: r -= 1 while numbers[l] == numbers[l - 1]: l += 1 when changing l and r this will avoid the checking for identical left or right values my time performance changed from 30% to 90%
@kayodeogunrinde7380
@kayodeogunrinde7380 Год назад
Bro you're a genius.
@saminchowdhury7995
@saminchowdhury7995 Год назад
Why why why didn't I figure that out. Thank you master
@shadyapp7416
@shadyapp7416 11 месяцев назад
Which one js better the hashing way or this one?
@DFPercush
@DFPercush 2 года назад
Hmm, I'll take a crack at it before watching the rest. if (size < 2) throw error("invalid input"); int iLow = size / 2; int iHigh = iLow + 1; while (true) { int sum = data[iLow] + data[iHigh]; if (sum == target) return {iLow, iHigh}; if (sum < target) iHigh++; else if (sum > target) iLow--; if (iLow < 0 || iHigh >= size) throw error("no solution"); }
@DFPercush
@DFPercush 2 года назад
oh and insert one more bounds check if size == 2
@bhaskyOld
@bhaskyOld 2 года назад
Thank you NeetCode
@flingmonkey5494
@flingmonkey5494 2 года назад
Funny thing: I have been forced to hunt for a job recently, and I have taken coding tests as part of the interview process. I always do poorly at these coding interviews, I *NEVER* do well. I am a non-degreed test engineer specializing in test automation. I have been doing it for 36 years. I have created both production tests and product verification tests, written in C, all these years. My verification tests tend to find the issues that no one else can isolate but that are still impacting the customer. My production tests work very reliably, allowing remote diagnostics, and no false-failures. I have saved companies I have worked for from gaining a reputation for shoddy product using my test systems. I have been accused of doing the impossible, but I was actually doing what I said I was doing and proved it. I am senior level, I am a mentor to other engineers, but I always fail these coding tests. I recently took a new job as a test engineer. After less than a month working my boss came to me and asked if I knew any other test engineers that work the way I do. Unfortunately, no, I do not. It's not just about being able to code, it's about attitude.
@lch99310
@lch99310 2 года назад
What if there is duplicate numbers in the array? should we add one more condition to deal with that?
@sharuksk5801
@sharuksk5801 2 года назад
Thank you man!!.
@angelofdeath095
@angelofdeath095 5 месяцев назад
wait does this also work on unsorted arrays? or just only on sorted arrays? i don't think [3,2,4] would work... if the target is 6...
@serpent2776
@serpent2776 4 месяца назад
Only sorted
@Tony-yn5rr
@Tony-yn5rr 2 года назад
Why not use a dictionary with the .get() method so that you can get the numbers you need in the dictionary by storing the different as a key and value as the index so that way you can just .get() on the dictionary as you go through the list in O(n) time. The dictionary .get() should be 0(1) in python since the solution this way worked and was same speed as the video solution.
@Insideoutcest
@Insideoutcest 2 года назад
problem description states O(1) space complexity
@5vart5ol
@5vart5ol 2 года назад
Does it point out that it has to be positive numbers in the array?
@expansivegymnast1020
@expansivegymnast1020 2 года назад
NeetCode for president.
@docx9877
@docx9877 2 года назад
why didnt we use binary search here ??