@@servantofthelord8147 dude , in the bible it says Jesus didn’t know hour . It means he is not G . It is a corrupt religion with a wrong belief système . Islam is the only correct religion that doesn’t have contradictions in it
@@diasutsman Contradiction #1: How did Judas Iscariot die? Matthew 27:5 Judas hung himself out of guilt. Acts 1:18 Judas fell and "his body burst open". Contradiction #2: Who was the father of Joseph, husband of Mary? Matthew 1:16 Joseph's father was Jacob. Luke 3:23 Joseph's father was Heli. Contradiction #3: Did Peter preach to Jews or Gentiles? Matthew 10:5-6 Peter (and all the disciples) were told to avoid Gentiles, and preach only to Jews. Acts 15:7 Peter was told "some time ago" that he should preach to Gentiles. Contradiction #4: Are we saved by faith or works? Matthew 7:21 Faith is not enough; obedience to the Father is also necessary to enter heaven. John 3:16 Anybody who believes in Christianity "shall not perish but have eternal life" Contradiction #5: Should good deeds be seen? Matthew 5:16 Good deeds should be seen. Matthew 6:1-4 We must not "practice our righteousness in front others". Contradiction #6: According to Paul, is the law necessary or not? Romans 3:31 The law is to be upheld. Romans 6:14 Christians are no longer under the law, but "under grace". Contradiction #7: How many believers were there at the time of the ascension? Acts 1:15 There were about 120 believers. 1 Corinthians 15:6 There were more than 500 believers. Contradiction #8: Who went to the tomb after the crucifixion? John 20:1 Only Mary Magdalene went to the tomb. Matthew 28:1 Mary Magdalene and "the other Mary" went to thetomb. Mark 16:1 The two Mary's and Salome went to the tomb. Luke 24:10 Mary Magdalene, Joanna, Mary, mother of James, and "others with them" told the disciples about the tomb. Contradiction #9: Is righteousness possible, and can it lead to salvation? Matthew 25:46 The righteous will have eternal life. Romans 3:10 There is "no one righteous, not even one" Contradiction #10: When did Jesus ascend? Luke 24:21 The third day after the crucifixion Acts 1:3 Jesus remained among the disciples for forty days.
At the beginning I was hesitant of watching this video because I'm not really proficient in Python, but the explanation of the problem was super clear and the code is so easy to understand. Good job!
So, one optimization I can think of is if the i value ever becomes positive then we can break out of the loop. Sino in the sorted list the if i is positive then adding the rest of the two value will always make the sum > 0. Of course this would only work when we are trying to find a, b and c such that a + b + c = 0.
Just wanted to drop an appreciation comment that your explanations and videos are better than services that charge hundreds of dollars. I used to not enjoy Leetcoding because I'd get frustrated when I try to read the solutions and don't understand them, but now I do thanks to Neetcode!
we can optimize the a loop by adding if a > 0: break #because as the leftmost pointer in a sorted array, if a > 0, that means we cant possibly adding left and right to 0
Tbh I think the jump towards immediately sorting the array is a bit unintuitive for beginners. Having watched the previous videos I would've started thinking "we can use hash sets" to check if for a,b,c we have already seen the number. And then the question would be how to improve runtime
I think the space complexity part is wrong there's no way it is O(1) because we still have the res list. Correct me if I am wrong but I would argue the space complexity is O(N) because we have the worst case where each element is unique and we'll len(res)==len(nums)
After watching many of your videos for many months, it's jarring to see a one-off where you're using white background. Nowadays so much prefer having a darker themed editor (after long time using light colors). Somehow I find it easier to read code on a dark background.
Even when I solved Two Sum and Two Sum II, I still couldn't figure out how to fix a value from the index and do the logic. Your explanationation is really helpful
Thanks for the solution! It really helped me to understand. I would also suggest to add the condition where the first name (a) is greater than zero. If it is, than just break the loop as there will be no solution afterwards.
you can also use a set instead of a list in order to prevent duplicates that appear from elements that have the same value and are one near the other.. but this is still executing more instructions..
Hey, man great explanation! I am just confused on one part: I believe there are quadratic distinct pairs that would equal the target sum. For instance: [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4], targetSum=0 The result array would be [[-5, -4, 4], [-5, -3, 3], [-5, -2, 2], [-5, -1, 1], [-4, -3, 3], [-4, -2, 2], [-4, -1, 1], [-3, -2, 2], [-3, -1, 1], [-2, -1, 1], [-1, 0, 1]] There would be n^2/2 combinations, so I believe the space complexity is O(n^2). Could you please clarify if this is correct?
Maybe a dumb question: would you mind explaining why we still need to update the "l" pointer after L18? L18 appends the combo of 3 numbers whose sum equals 0 to the result list, and so why do we need L19 to L21? Thanks.
if you have a case like: [-1, 0, 0, 1, 1] there is a solution at [-1, 0, 1] we now carry on in the while loop and increment the left and decrement the right. this will give us a duplicate solution of [-1, 0, 1] again. after finding a solution you have to keep moving the pointers until you get to the next non-duplicated number in the array
I mean I found a brute force algorithm that just checks if the current solution is a duplicate and doesnt add it if it is. But of course I get time limit exceeded because you always have to find the most efficient algorithm smfh.
came to say during 2022 i found a posted solution on LC using HashSet which helps with checking duplicate, that helps a ton without checking for duplication
U a God.. I agree the hardest part of incrementing that left pointer when your 3sum == 0. Else you'll run into an infinite loop or get multiple duplicate pairs.
ok, so I have tried the exact same code in leetcode and it is not going through. Any ideas? class Solution: def threeSum(self, nums: List[int]) -> List[List[int]]: l=len(nums) res=[] nums.sort() for i, a in enumerate(nums): if i>0 and a==nums[i-1]: continue l, r=i+1, l-1 while l0: r-=1 elif threeSum
Will this code work in an array that has the values [-2, -2,3,4] Since i = 0 which is -2, L = -2 and R = 4 which threesum = 0 but -2 is used twice? How is this solved?
I think here ruclips.net/video/jzZsG8n2R9A/видео.html explanation is a bit wrong since we still can add L=-3 because it is not considered as duplicate if [-3,-3,x]. All other staff is excellent. Thanks!
Can anyone please explain this to me, my doubt is if i miss to increment my start pointer after finding a triplet, the program gives memory limit exceed error. I don't get it why, it should not run in infinite loop as we are also checking start < end. This is the full code : vector threeSum(vector& nums) { sort(nums.begin(),nums.end()); vector ans; vector triplet(3); for(int i=0;i 0 && nums[i] == nums[i-1])continue; int start = i+1; int end = nums.size()-1; while(start < end) { int sum = nums[i] + nums[start] + nums[end]; if(sum > 0 ) { --end; } else if(sum < 0) { ++start; } else { triplet[0] = nums[i]; triplet[1] = nums[start]; triplet[2] = nums[end]; ans.push_back(triplet); ++start; while(nums[start] == nums[start-1] && start < end)++start; } } } return ans; }
Your last comment that it's a pretty hard problem and showing that you struggled was encouraging. I did both the Two Sum and Two Sum II problems but still was struggling in figuring out the solution. Thanks a lot for such a nice explanation and honest feedback! Appreciate it!
more than anything else i love how patient you are with us as the viewer, never skipping a step, sayng something is obvious, and offering encouragement by showing us all the times you screwed up too. it really helps. invaluable resource!!
Hi! Maybe I'm missing something, but what about the case where you have an array like [-3,-3,0,3,6]. In this case, both [-3,-3,6] and [-3,0,3] are valid. If you skip the second -3, you will miss out on [-3,0,3] as one of the triplets.
You bring up a good question that I spent some time thinking about. For the case you mentioned. [-3,-3,6] gets included when a is on the first -3, l is on second -3 and r is on 6. The l does not incremented before a solution is added because there are no checks to see if a and nums[l] are duplicates. The second -3 won't be skipped because when the sum of a + l + r is 0, the left pointer is incremented. So l comes to 0 while as 'a' stays on the first -3. Eventually r will end up on 3, and we will have [-3,0,3] as another solution. Hope it is useful to anyone who has the same doubt!
after sorting, you could check to see if the first element is greater than 0. if it is, then you can just return before looping. there's no possible triplet if the first number is greater than 0 (after sorting). if you want to add this optimization, you have to check to make sure it's not empty before trying to access first element
rather than just solving the question, you helped us understand the question and how to go about solving it, and THAT is what many channels lack! Thank you so much
The following code results in wrong aswer on leet code class Solution: def threeSum(self, nums: List[int]) -> List[List[int]]:
res = [] nums.sort() if len(nums) < 3: return []
for i in range(len(nums)): if i > 0 and nums[i-1] == nums[i]: continue
l = i r = len(nums)-1
while l < r: zero = nums[i] + nums[l] + nums[r] if zero > 0: r -= 1 elif zero < 0: l += 1 else: res.append([nums[i], nums[l], nums[r]]) l += 1 while nums[l] == nums[l-1] and l < r: l += 1
The whole software engineer hiring process is broken. These coding questions are just ridiculous, have nothing to do with your day to day job and don't give any clue about whether you are or you are not a capable and reliable programmer in a dev team.
Comment for the algo, but also just appreciate the encouragement. I feel like an idiot trying these problems, and I appreciate the reassurance that I'm probably not, it's just a hard problem to solve
Thanks bro, I was frustrated because I was not able to solve it, so I got high, and I was high and frustrated, but now with your video I understand the solution, so now I'm high and happy, thanks a lot :)
Java solution - public List threeSum(int[] nums) { Set result = new HashSet(); Arrays.sort(nums); // easier to ignore duplicates and deduce to two sum II problem for (int i = 0; i < nums.length - 1; i++) { // to handle duplicates if (i > 0 && nums[i] == nums[i - 1]) { continue; } // now 2 elements after ith index needs to be identified like two sum II problem int target = -nums[i]; List pairs = new ArrayList(); // two pointer approach for sorted array to find two sum int low = i + 1, high = nums.length - 1; while (low < high) { if (nums[low] + nums[high] == target) { pairs.add(nums[i]); pairs.add(nums[low]); pairs.add(nums[high]); low++; high--; result.add(new ArrayList(pairs)); pairs = new ArrayList(); } else if (nums[low] + nums[high] < target) low++; else if (nums[low] + nums[high] > target) high--; } } return new ArrayList(result); }
I have to say, there are few channels I will like + subscribe + hit notification bell, and you are one of them! Currently looking at practicing for interviews and this is incredibly helpful! Thank you for doing what you do!
I'm confused how the first conditional doesn't prevent something like [-7,-7,0,3,4,7] from passing where there are two solutions as shown: [[-7,0,7], [-7,3,4]]. Wouldn't sorting the input array cause the second -7 in the input Array to hit the first conditional, skipping the l/r pointer logic completely? Then the loop resumes on 0 and l takes the value of 3. And l can only increment, not decrement. Am I overlooking something obvious?
what if the list was -3 -3 1 1 2 2 3 4 and our a in a loop was at -3; wouldn't it make two combinations -3 1 2, and then again -3 1 2 because we're only checking for the repition of a?
Why is the first 'for loop' condition: if i > 0 and nums[i] == nums[i-1]: Instead of just: if nums[i] == nums[i-1]: ?? If the list is sorted, then nums[0] != nums[-1] anyway, so the condition feels redundant. Am I missing something? Thanks :)
As someone already said, Please dont stop. Keep up the good work. This is another gem of explanation and clean solution of yours. Hats off. Loved the way how you showed all your previous failed attempts.
The reason is that in JS the .sort() does not work as expected, try adding .sort((a, b) => a - b) and it should work. Explanation: Calling .sort() does the following [-1, -2, -3, 0, 1, 2, 3]. In order to have [-3, -2, -1, 0, 1, 2, 3] you need to pass a comparator function.
At minute 11:00 you are trying to explain why we only need to move the left pointer but your explanation is only valid for the current example array you are showing. What if there are more negative values in the list. Would have appreciated if you explained that for example [-2, -2, -1, 0, 0, 1, 1, 2, 2]
You recommended doing Two Sum II first before 3Sum but in neetcode blind75 there is no Two Sum II only in the 150. Was it just to make space for other problems? Assuming something had to get cut out
I guess the author is not fully right about the duplication concept. The idea is not having the same value on the same position: [-3, 3, 2, 1, 0]: There could be 2 options with the same -3 at index 0: [-3, 3, 0] & [-3, 2, 1]. Thus, problems in the tuples overall, like the entire tuple must be unique regardless of the position. Anyway, good examination.
Hello man, thanks a lot for sharing this high-quality explanation. One question on my mind if you don't mind me asking, how can I compute the space complexity of output `res`? Thanks again!
Imagine you're in an interview in 2000, and you don't know this technique exists. What are the odds you're going to come up with it on the spot? I think only a 0.0000001% genius would be able to.
I'm trying to understand in the else statement in the Github optimized solution after result.append, we increment the left pointer by 1 and decrement the right pointer by 1. In this video, he left out r -= 1 but added it to the optimized solution on github. I'm trying to understand why the solution is more optimized with this r -= 1?
I disagree with the -3 not allowed to be duplicated, it's clearly seen in the example that -1 is twice, and also what if you had a 6 somewhere there in your example and you needed -3 -3 + 6 = 0
Do I need to just keep on trying out problems until I can solve them by finding similar patterns? I can never come up with algorithm by myself, I always check out tutorials and it's frustrating af.
my only issue with this Video it I can only like it this Once.... Lol... More important than the solution was the evidence at the end showing all the work you put in for this. Pure HOPE dude. Thank you.
ruclips.net/video/jzZsG8n2R9A/видео.html This is the AHA! moment for me. You skip the adjacent duplicate element because in the previous loop you would have already tried finding a pair for it.
🚀 neetcode.io/ - I created a FREE site to make interview prep a lot easier, hope it helps! ❤
I really liked your explanation. It was very clear and clean. Keep it up and great work! :)
dude your doing so well. appreciate man. loved your explanation. hopeful for some constant tuts in the future
@NeetCode could you please add a video on Flattening of a LinkedList?
Please put explanation only if not the code of as many as you could. You are an absolute life saver.
These videos are amazing! Luckily I found this channel.
I will literally pay for leetcode premium if intuitive video explanations like these were supplied with it
Second that.
@@protyaybanerjee5051 Third that!
@@孙中胜 fourth that
'n'th that
(n+∞)th that
who taught neetcode how to leetcode if there was no neetcode back then 🤔
Who delivers mail to the mailman? Who coaches the coach? These questions also keep me up at night.
God
@@servantofthelord8147
dude , in the bible it says Jesus didn’t know hour .
It means he is not G .
It is a corrupt religion with a wrong belief système .
Islam is the only correct religion that doesn’t have contradictions in it
@@diasutsman
Contradiction #1: How did Judas Iscariot die?
Matthew 27:5
Judas hung himself out of guilt.
Acts 1:18
Judas fell and "his body burst open".
Contradiction #2: Who was the father of Joseph, husband of Mary?
Matthew 1:16
Joseph's father was Jacob.
Luke 3:23
Joseph's father was Heli.
Contradiction #3: Did Peter preach to Jews or
Gentiles?
Matthew 10:5-6
Peter (and all the disciples) were told to avoid
Gentiles, and preach only to Jews.
Acts 15:7
Peter was told "some time ago" that he should preach to Gentiles.
Contradiction #4: Are we saved by faith or works?
Matthew 7:21
Faith is not enough; obedience to the Father is also necessary to enter heaven.
John 3:16
Anybody who believes in Christianity "shall not perish but have eternal life"
Contradiction #5: Should good deeds be seen?
Matthew 5:16
Good deeds should be seen.
Matthew 6:1-4
We must not "practice our righteousness in front others".
Contradiction #6: According to Paul, is the law necessary or not?
Romans 3:31
The law is to be upheld.
Romans 6:14
Christians are no longer under the law, but "under grace".
Contradiction #7: How many believers were there at the time of the ascension?
Acts 1:15
There were about 120 believers.
1 Corinthians 15:6
There were more than 500 believers.
Contradiction #8: Who went to the tomb after the crucifixion?
John 20:1
Only Mary Magdalene went to the tomb.
Matthew 28:1
Mary Magdalene and "the other Mary" went to thetomb.
Mark 16:1
The two Mary's and Salome went to the tomb.
Luke 24:10
Mary Magdalene, Joanna, Mary, mother of James, and "others with them" told the disciples about the tomb.
Contradiction #9: Is righteousness possible, and can it lead to salvation?
Matthew 25:46
The righteous will have eternal life.
Romans 3:10
There is "no one righteous, not even one"
Contradiction #10: When did Jesus ascend?
Luke 24:21
The third day after the crucifixion
Acts 1:3
Jesus remained among the disciples for forty days.
Islam teaches earth is flat
At the beginning I was hesitant of watching this video because I'm not really proficient in Python, but the explanation of the problem was super clear and the code is so easy to understand. Good job!
So, one optimization I can think of is if the i value ever becomes positive then we can break out of the loop. Sino in the sorted list the if i is positive then adding the rest of the two value will always make the sum > 0. Of course this would only work when we are trying to find a, b and c such that a + b + c = 0.
b and c can be negative tho
@@Philgob No it can't since we are sorting the array before the loop
Just wanted to drop an appreciation comment that your explanations and videos are better than services that charge hundreds of dollars. I used to not enjoy Leetcoding because I'd get frustrated when I try to read the solutions and don't understand them, but now I do thanks to Neetcode!
we can optimize the a loop by adding if a > 0: break #because as the leftmost pointer in a sorted array, if a > 0, that means we cant possibly adding left and right to 0
Great explanation on how to avoid duplicate count for two sums!!
save the value in prev
Tbh I think the jump towards immediately sorting the array is a bit unintuitive for beginners. Having watched the previous videos I would've started thinking "we can use hash sets" to check if for a,b,c we have already seen the number. And then the question would be how to improve runtime
the way you explained three_sum is nothing but a number plus two_sum simplified it. you are super awesome!!
Thank you, 100% right about it being easier if doing Two Sum first
I didn't and what I created was...unique
the way you teach its so chill and calm feels like you are really understanding the question and also building our logic building thanks a lot
I think the space complexity part is wrong there's no way it is O(1) because we still have the res list. Correct me if I am wrong but I would argue the space complexity is O(N) because we have the worst case where each element is unique and we'll len(res)==len(nums)
Exactly what I was thinking, we always need extra space to store the answer
this exact code and I got Wrong Answer for [0,0,0,] input, and then TLE when I added a special case for it. Maybe they've added new test cases.
I've done like a million of stupid mistakes even after watching and understanding the video. It took me a day ahah now is engraved in my memory
I saw a couple videos of 3sum and couldn't get it until I saw your explanation. Now I'm subscribed :)
Glad it helped!
After watching many of your videos for many months, it's jarring to see a one-off where you're using white background.
Nowadays so much prefer having a darker themed editor (after long time using light colors).
Somehow I find it easier to read code on a dark background.
Even when I solved Two Sum and Two Sum II, I still couldn't figure out how to fix a value from the index and do the logic. Your explanationation is really helpful
Thanks for the solution! It really helped me to understand. I would also suggest to add the condition where the first name (a) is greater than zero. If it is, than just break the loop as there will be no solution afterwards.
Actually you do increment left and decrement right in the else statement. Just incrementing left works but doing both would find the solution faster
you can also use a set instead of a list in order to prevent duplicates that appear from elements that have the same value and are one near the other.. but this is still executing more instructions..
Hey, man great explanation! I am just confused on one part: I believe there are quadratic distinct pairs that would equal the target sum.
For instance: [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4], targetSum=0
The result array would be [[-5, -4, 4], [-5, -3, 3], [-5, -2, 2], [-5, -1, 1],
[-4, -3, 3], [-4, -2, 2], [-4, -1, 1],
[-3, -2, 2], [-3, -1, 1],
[-2, -1, 1],
[-1, 0, 1]]
There would be n^2/2 combinations, so I believe the space complexity is O(n^2).
Could you please clarify if this is correct?
There are n(n+1)/2 possible pairs. For each element in the array, you pick another pair to form a triplet so the limiting factor is O(n^3)
These are very helpful in my prep for my google loop! Thanks a lot.
did you get the job ?
Your explanations are what I strive towards! Keep up the good work man!
Crisp and intuitive explanation btw I was hoping for runtime error at the end.
your code looks very neat. Mine looks very messy. when you started doing problems were your code messy too? how did you get to keep it so simplicit
Maybe a dumb question: would you mind explaining why we still need to update the "l" pointer after L18? L18 appends the combo of 3 numbers whose sum equals 0 to the result list, and so why do we need L19 to L21? Thanks.
if you have a case like: [-1, 0, 0, 1, 1] there is a solution at [-1, 0, 1] we now carry on in the while loop and increment the left and decrement the right. this will give us a duplicate solution of [-1, 0, 1] again. after finding a solution you have to keep moving the pointers until you get to the next non-duplicated number in the array
Your tutorials help a lot.. Thankyou!!
Very comprehensive, thank you so much
why didnt u used set() to remove the duplicates? , directly removing the duplicayes in start will make the code easy and short
I am confused on the last 3 lines of code before the return statement. Why do we need to increment the left pointer by one?
3sum is my favorite sum
Keep up the good work love bro
I mean I found a brute force algorithm that just checks if the current solution is a duplicate and doesnt add it if it is. But of course I get time limit exceeded because you always have to find the most efficient algorithm smfh.
came to say during 2022 i found a posted solution on LC using HashSet which helps with checking duplicate, that helps a ton without checking for duplication
thank you!
U a God.. I agree the hardest part of incrementing that left pointer when your 3sum == 0. Else you'll run into an infinite loop or get multiple duplicate pairs.
Really good explanation
You do an awesome job!!!
ok, so I have tried the exact same code in leetcode and it is not going through. Any ideas?
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
l=len(nums)
res=[]
nums.sort()
for i, a in enumerate(nums):
if i>0 and a==nums[i-1]:
continue
l, r=i+1, l-1
while l0:
r-=1
elif threeSum
Output {-1,-1,2} same elements, you saying same element we skips
Ok so this is basically TwoSum II inside of TwoSum, right?
could we do this for optimization - if nums[i] > 0:
return result
Is using sort() right way to do a problem using pre defined library? , I'm new please don't mind if this is a dumb question.....
best explatation ever
You are amazing. 👍🏻
You'r Awesome
I feel hashmap would be a better solution
Why didn't we solve it like the 'longest palindrome substring' problem?
Will this code work in an array that has the values [-2, -2,3,4] Since i = 0 which is -2, L = -2 and R = 4 which threesum = 0 but -2 is used twice? How is this solved?
I think here ruclips.net/video/jzZsG8n2R9A/видео.html explanation is a bit wrong since we still can add L=-3 because it is not considered as duplicate if [-3,-3,x]. All other staff is excellent. Thanks!
Nice solution
Can anyone please explain this to me, my doubt is if i miss to increment my start pointer after finding a triplet, the program gives memory limit exceed error.
I don't get it why, it should not run in infinite loop as we are also checking start < end.
This is the full code :
vector threeSum(vector& nums) {
sort(nums.begin(),nums.end());
vector ans;
vector triplet(3);
for(int i=0;i 0 && nums[i] == nums[i-1])continue;
int start = i+1;
int end = nums.size()-1;
while(start < end)
{
int sum = nums[i] + nums[start] + nums[end];
if(sum > 0 )
{
--end;
}
else if(sum < 0)
{
++start;
}
else
{
triplet[0] = nums[i];
triplet[1] = nums[start];
triplet[2] = nums[end];
ans.push_back(triplet);
++start;
while(nums[start] == nums[start-1] && start < end)++start;
}
}
}
return ans;
}
Thanks man
Man, you do explanations exceptionally clean. Please don't stop.
Thanks, appreciate the kind words!
@@NeetCode Hey man you got any tips to learn leetcode faster?
Yeah man @NeetCode, got any tips to learn leetcode faster
While the problem name is 'threesome' and you're saying "don't stop". I can't resist a cracked laugh.
@@deepanshuchoudhary4598 hehe
Your last comment that it's a pretty hard problem and showing that you struggled was encouraging. I did both the Two Sum and Two Sum II problems but still was struggling in figuring out the solution. Thanks a lot for such a nice explanation and honest feedback! Appreciate it!
hahah, same)
I had done both 2 sums, but struggled on this problem. I feel that this should’ve been a leetcode 'hard' problem instead.
same!
same here bro haha
im ngl i didnt understand the question at all lmao
I can see this channel blowing up. just keep making vids man, these are great explanations! ty
more than anything else i love how patient you are with us as the viewer, never skipping a step, sayng something is obvious, and offering encouragement by showing us all the times you screwed up too. it really helps. invaluable resource!!
Hi! Maybe I'm missing something, but what about the case where you have an array like [-3,-3,0,3,6]. In this case, both [-3,-3,6] and [-3,0,3] are valid. If you skip the second -3, you will miss out on [-3,0,3] as one of the triplets.
No, it won't miss that pair. Notice the inner logic runs for every item of the list via outer for loop. I tested it and works as expected.
You bring up a good question that I spent some time thinking about. For the case you mentioned. [-3,-3,6] gets included when a is on the first -3, l is on second -3 and r is on 6. The l does not incremented before a solution is added because there are no checks to see if a and nums[l] are duplicates. The second -3 won't be skipped because when the sum of a + l + r is 0, the left pointer is incremented. So l comes to 0 while as 'a' stays on the first -3. Eventually r will end up on 3, and we will have [-3,0,3] as another solution. Hope it is useful to anyone who has the same doubt!
As a guy who is struggling with the easiest of LC questions, the final part of this video is really motivating.
after sorting, you could check to see if the first element is greater than 0. if it is, then you can just return before looping. there's no possible triplet if the first number is greater than 0 (after sorting). if you want to add this optimization, you have to check to make sure it's not empty before trying to access first element
rather than just solving the question, you helped us understand the question and how to go about solving it, and THAT is what many channels lack! Thank you so much
Why can't you use three pointers instead? Also why does this approach work for sums adding up to 0 but not for any other number?
How is this a medium? My brain hurts 😭🧠
The following code results in wrong aswer on leet code
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
res = []
nums.sort()
if len(nums) < 3:
return []
for i in range(len(nums)):
if i > 0 and nums[i-1] == nums[i]:
continue
l = i
r = len(nums)-1
while l < r:
zero = nums[i] + nums[l] + nums[r]
if zero > 0:
r -= 1
elif zero < 0:
l += 1
else:
res.append([nums[i], nums[l], nums[r]])
l += 1
while nums[l] == nums[l-1] and l < r:
l += 1
return res
can confirm
The whole software engineer hiring process is broken. These coding questions are just ridiculous, have nothing to do with your day to day job and don't give any clue about whether you are or you are not a capable and reliable programmer in a dev team.
Which keyboard you are using?
Comment for the algo, but also just appreciate the encouragement. I feel like an idiot trying these problems, and I appreciate the reassurance that I'm probably not, it's just a hard problem to solve
Thanks bro, I was frustrated because I was not able to solve it, so I got high, and I was high and frustrated, but now with your video I understand the solution, so now I'm high and happy, thanks a lot :)
Java solution -
public List threeSum(int[] nums) {
Set result = new HashSet();
Arrays.sort(nums); // easier to ignore duplicates and deduce to two sum II problem
for (int i = 0; i < nums.length - 1; i++) {
// to handle duplicates
if (i > 0 && nums[i] == nums[i - 1]) {
continue;
}
// now 2 elements after ith index needs to be identified like two sum II problem
int target = -nums[i];
List pairs = new ArrayList();
// two pointer approach for sorted array to find two sum
int low = i + 1, high = nums.length - 1;
while (low < high) {
if (nums[low] + nums[high] == target) {
pairs.add(nums[i]);
pairs.add(nums[low]);
pairs.add(nums[high]);
low++;
high--;
result.add(new ArrayList(pairs));
pairs = new ArrayList();
}
else if (nums[low] + nums[high] < target) low++;
else if (nums[low] + nums[high] > target) high--;
}
}
return new ArrayList(result);
}
thanks for directing me to 2sum part 2. I was indeed able to immediately solve 3sum after i solved that one with two converging pointers.
Thanks!
Thank you so much!
I have to say, there are few channels I will like + subscribe + hit notification bell, and you are one of them! Currently looking at practicing for interviews and this is incredibly helpful! Thank you for doing what you do!
This is the only 3some a programmer will ever get.
I'm confused how the first conditional doesn't prevent something like [-7,-7,0,3,4,7] from passing where there are two solutions as shown: [[-7,0,7], [-7,3,4]]. Wouldn't sorting the input array cause the second -7 in the input Array to hit the first conditional, skipping the l/r pointer logic completely? Then the loop resumes on 0 and l takes the value of 3. And l can only increment, not decrement. Am I overlooking something obvious?
The first loop would stop at -7, the left pointer would be pointing at 0.
what if the list was -3 -3 1 1 2 2 3 4 and our a in a loop was at -3; wouldn't it make two combinations -3 1 2, and then again -3 1 2 because we're only checking for the repition of a?
Why is the first 'for loop' condition:
if i > 0 and nums[i] == nums[i-1]:
Instead of just:
if nums[i] == nums[i-1]:
??
If the list is sorted, then nums[0] != nums[-1] anyway, so the condition feels redundant. Am I missing something?
Thanks :)
In many programming languages there is no negative indices so if I used nums[-1] it will give me an error
Why do you not need a while loop to move right pointer as long as your current right is equal to the last right pointer?
this is the question i got. Did you figure it out?
ok there is actually an explanation right in the video but i just didn't comprehend it at first, it starts at 10:00
[NeetCode] What if our left pointer was here: [points to -2 at index 0]
# [-2, -2, 0, 2, 2]
That can't happen. l's lowest value is i + 1.
exactly what i was wondering, that last bit about the left pointer isnt quite clear to me
why not use set instead of list. using set makes it easier
As someone already said, Please dont stop. Keep up the good work. This is another gem of explanation and clean solution of yours. Hats off. Loved the way how you showed all your previous failed attempts.
crazy how I have the exact same code line by line in JS and not passing all test cases
The reason is that in JS the .sort() does not work as expected, try adding .sort((a, b) => a - b) and it should work.
Explanation:
Calling .sort() does the following [-1, -2, -3, 0, 1, 2, 3].
In order to have [-3, -2, -1, 0, 1, 2, 3] you need to pass a comparator function.
At minute 11:00 you are trying to explain why we only need to move the left pointer but your explanation is only valid for the current example array you are showing. What if there are more negative values in the list. Would have appreciated if you explained that for example [-2, -2, -1, 0, 0, 1, 1, 2, 2]
3Sum.... Mmmmmm
Really interesting question
You recommended doing Two Sum II first before 3Sum but in neetcode blind75 there is no Two Sum II only in the 150. Was it just to make space for other problems? Assuming something had to get cut out
This line `if i > 0 and a == nums[i-1]: continue` gives huge optimization, it literally went from `beats 5%` to `beats 60%`
The explanation for the code solution was amazing!
excellent explanation, but the problem was hard i must say - at least for me!
I guess the author is not fully right about the duplication concept.
The idea is not having the same value on the same position: [-3, 3, 2, 1, 0]:
There could be 2 options with the same -3 at index 0:
[-3, 3, 0] & [-3, 2, 1].
Thus, problems in the tuples overall, like the entire tuple must be unique regardless of the position.
Anyway, good examination.
man i love you
Hello man, thanks a lot for sharing this high-quality explanation. One question on my mind if you don't mind me asking, how can I compute the space complexity of output `res`? Thanks again!
Imagine you're in an interview in 2000, and you don't know this technique exists. What are the odds you're going to come up with it on the spot? I think only a 0.0000001% genius would be able to.
back then interviews were way easier too, I bet. Many times pretty much if you have a decent CS degree, you are hired.
I'm trying to understand in the else statement in the Github optimized solution after result.append, we increment the left pointer by 1 and decrement the right pointer by 1.
In this video, he left out r -= 1 but added it to the optimized solution on github.
I'm trying to understand why the solution is more optimized with this r -= 1?
I was actually just looking for an adult video, but ended up landing a job at Google instead
I disagree with the -3 not allowed to be duplicated, it's clearly seen in the example that -1 is twice, and also what if you had a 6 somewhere there in your example and you needed -3 -3 + 6 = 0
Do I need to just keep on trying out problems until I can solve them by finding similar patterns? I can never come up with algorithm by myself, I always check out tutorials and it's frustrating af.
Not work with input like [-1,0,1,2,-1,-4,-2,-3,3,0,4]
It works.
Dude, you are just killing it, by the way, what is the blackboard you are using to illustrate the concept
Thanks, I appreciate it! I'm using Paint 3D, i think it's free for anyone with windows 10.
@@NeetCode Ok, thanks
my only issue with this Video it I can only like it this Once.... Lol...
More important than the solution was the evidence at the end showing all the work you put in for this. Pure HOPE dude.
Thank you.
Wow in 2024 there were 6k thump ups and 2024 we've jumped to 31k, just an oberservation
ruclips.net/video/jzZsG8n2R9A/видео.html
This is the AHA! moment for me. You skip the adjacent duplicate element because in the previous loop you would have already tried finding a pair for it.