Тёмный

2 Sum Problem | 2 types of the same problem for Interviews | Brute-Better-Optimal 

take U forward
Подписаться 680 тыс.
Просмотров 394 тыс.
50% 1

Notes/C++/Java/Python codes: takeuforward.o...
Problem links.
2 Sum: bit.ly/3Iu7zMu
We have solved the problem, and we have gone from brute force and ended with the most optimal solution.
Full Course: bit.ly/tufA2ZYt
You can follow me across social media, all my handles are below:
Linkedin/Instagram/Telegram: linktr.ee/take...
0:00 Introduction of course

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

 

27 сен 2024

Поделиться:

Ссылка:

Скачать:

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

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 450   
@takeUforward
@takeUforward Год назад
Let's march ahead, and create an unmatchable DSA course! ❤ Timestamps pleaseeee Use the problem links in the description.
@prithammahato1915
@prithammahato1915 Год назад
0.45 - BRUTE SOL 5.13 - BETTER APPROACH (USING HASHING) 11.55 - OPTIMAL APPROACH (USING 2 POINTER)
@prithammahato1915
@prithammahato1915 Год назад
0.45 BRUTE 5.13 BETTER 11.55 OPTIMAL
@amitranjan6998
@amitranjan6998 Год назад
@take U forward : Hi Striver Bhaiya , I love your video , I am learning alot from you , just want to highlight in SDE sheet for this problem it's redirecting to some other question (i.e Find all pairs with a given sum) ,but it's similiar to 2sum approach only :)
@RamanKumar-er8ie
@RamanKumar-er8ie Год назад
it does not work on tc=-3,-2,2,3,3 any please help me out in this
@abhinavennala9613
@abhinavennala9613 Год назад
@@RamanKumar-er8ie what is the target?
@TheITEngineer
@TheITEngineer 19 дней назад
Striver, I cracked my coding interview by providing your optimal solution. Can’t thank you enough. You have changed lives of many. Keep doing great work ❤
@Pai5566la
@Pai5566la 14 дней назад
Bro, can you say about your complete interview experience
@pragmaticcoder6910
@pragmaticcoder6910 10 месяцев назад
I can’t thank enough because you teach so well about the concepts of DSA compared to others. None of the paid resources out there have good content. All I can say is May God bless you with long life and happiness. You are making all of us to land in our dream job.
@many987
@many987 Год назад
bhaiya you're so much doing for us, even you live alone in Poland, you sacrifice your time for you and I understand every thing you teach as you are so good in explaining and making people understand. once again thanks a lot for this
@suravighosal9934
@suravighosal9934 Год назад
We need more problem solving videos. Explanation is super. I have gone through a few channels but this is the best! Thank you so much.❤️
@habeeblaimusa4466
@habeeblaimusa4466 Год назад
Bro, I am a guy from Africa you are the first person in this tech community that inspires me that I can do it.. Hats off for you bro 🔥🔥🔥
@kushalchakraborty6970
@kushalchakraborty6970 Год назад
Bro ,I need some tips to increase my 🍆?
@kulkarnisoham
@kulkarnisoham Год назад
That's a complement to whole country..!!
@Fe-ironman
@Fe-ironman 8 месяцев назад
no@@kulkarnisoham
@barnam_das
@barnam_das 7 месяцев назад
yes my boy, you can do it lets gooooo !!!!
@ArvindSingh-wj7vy
@ArvindSingh-wj7vy 5 месяцев назад
Thank you from India on behalf of Striver 😂
@09ankurjaiswal85
@09ankurjaiswal85 11 месяцев назад
00:06 The video covers the 'two sum problem' and its two varieties. 02:04 Two sum problem can be solved using brute force method 04:05 Optimizing 2 Sum problem using a better solution 06:08 Using hashing to easily retrieve elements from a data structure. 08:13 Find the indexes of two elements in an array 10:30 Two pointer approach is a slightly better solution to solve the problem without using a map data structure. 12:38 Using the two-sum problem to find pairs that add up to a given target 14:51 The time complexity of the algorithm is O(n) 16:49 Space complexity and array manipulation explanation
@KP-we9ce
@KP-we9ce 8 месяцев назад
@takeUforward
@manideep7148
@manideep7148 2 месяца назад
​ @takeUforward
@aryansinha1818
@aryansinha1818 Год назад
Man you have changed a lot, this new version feels like a super saiyan mode.
@takeUforward
@takeUforward Год назад
Haha, experience :)
@itzmartin20
@itzmartin20 Год назад
Understood! Thanks a billion for your top-notch explaination brother!
@Josuke217
@Josuke217 2 месяца назад
Man after watching the first 5 videos and solving the problems on my own , I was also able to solve almost all medium and some hard problems. Watching these videos really built my logic , these lectures are a gold mine.
@Josuke217
@Josuke217 2 месяца назад
I didn't think about hashing but you mentioned it, I quickly coded it and got the answer. Now I just have to think of these approaches quickly
@Squirt_Turtle
@Squirt_Turtle 2 месяца назад
Yes even i can solve any problem using brute force approach for better & optimal i have to think....i m sure till the course end i will able to improve my solving skills..i belive ❤
@KrishnaKumar-b4m9p
@KrishnaKumar-b4m9p 14 дней назад
@@Josuke217 same
@secretcoder7
@secretcoder7 Год назад
GREAT BHAIYA I buy multiple dsa courses but i only understand with ur lectures 🤗🤗
@PrithaMajumder
@PrithaMajumder 4 месяца назад
Raj, Thanks a lot for This Amazing Video about C++ Arrays Video - 5 Completed ✅
@AbjSir
@AbjSir 11 месяцев назад
2 pointer approach was very beautiful
@anamikarawat3698
@anamikarawat3698 Год назад
Thankss bhaiya for this consistency ❤️🙌 My placement is coming soon I'm in 6th semester!!🙂
@legendrose6828
@legendrose6828 Год назад
me too, can we connect on linkedin?
@jayrathod7957
@jayrathod7957 10 месяцев назад
Hello bhaiya how was it? I'm here at 3rd sem 🤔
@chiragdusad2015
@chiragdusad2015 6 месяцев назад
Hey! Do you get the placements or how was your experience?
@KomalSingh-qr4mu
@KomalSingh-qr4mu Месяц назад
Understood ! This is the first ques of my challenge 😃
@yashwanthostwal6947
@yashwanthostwal6947 Год назад
int main() {int n=3; int array[3]={3,2,4}; int target=6; for(int i=0; i
@movocode
@movocode 2 месяца назад
10:36 mpp.insert({nums[i], i}); is more optimised than mpp[num] = i; (used in video)
@harshitrautela6585
@harshitrautela6585 8 месяцев назад
🎯 Key Takeaways for quick navigation: 00:45 📚 *The video is part of the Striver's A to Z DSA course, covering comprehensive content with a guarantee of deep understanding in DS algo for interviews worldwide.* 01:12 🎯 *The Two Sum problem has two varieties: one asks for a yes or no if a pair with the given sum exists, and the other requires returning the indices of the pair.* 02:50 🧠 *The initial Brute Force solution involves nested loops to check every pair's sum.* 05:24 ⏩ *The improved solution uses hashing, mapping array elements to their indices, reducing time complexity to O(n).* 09:17 🚀 *The optimal approach, sorting the array and using two pointers, achieves O(n log n) time complexity without extra space.* 15:16 🔄 *The space complexity for the two-pointer approach is O(1), considering no additional space is used.* 17:50 📂 *Code for all three approaches (Brute Force, Hashing, Two-Pointer) is available in C++, Java, and Python in the video description.* Made with HARPA AI
@hareshnayak7302
@hareshnayak7302 6 месяцев назад
Understood, Thank you strivers for this amazing video.
@sagestudy
@sagestudy Год назад
You are Great Sir! I love your explanation !!
@shafiulhaque6583
@shafiulhaque6583 Год назад
Thanks to you for the video Sir . Had a query : In Type 2 of the problem , why do we need the extra Data structure for the indices ? Because I think "left" and "right" these should be giving us the indices of the 2 numbers whose sum equals to the target .
@aashishomre1624
@aashishomre1624 Год назад
Aftet sorting indices are changed
@himanshukaushik9223
@himanshukaushik9223 Год назад
​@@aashishomre1624 bhai return hum curly braces ma kyu nahi kar sakta hai
@aashishomre1624
@aashishomre1624 Год назад
Bcoz return type function ka vector hai {-1,-1} indicating no pair found
@aashishomre1624
@aashishomre1624 Год назад
vector vect{ 10, 20, 30 }; this syntax is used
@sunilkamat8199
@sunilkamat8199 Год назад
Brute -> Better > Optimal = BEST👌
@JatinderDhiman-e4c
@JatinderDhiman-e4c 7 месяцев назад
The question is to find the indices of the elements which on adding give us the target value. In the last part of video, where we need to find the solution in O(1) space, we sort the array and hence lose the indices of input array. So how can we return the indices of elements then ?
@harshukey6072
@harshukey6072 Год назад
Understood 🎉 40 lakh
@kapilraivines8486
@kapilraivines8486 5 месяцев назад
Hey Striver I am from Jupiter... I love your DSA playlist
@samlinus836
@samlinus836 Год назад
As usual you rock as you explain 🔥 Hey Raj, what if the array has duplicate elements for example, arr = [2,3,5,1,2] and target = 4 Will hashing work for this case too?.................Because hashmap has unique keys
@ayushmittal9666
@ayushmittal9666 Год назад
Yes it will work beacuse we will check if the target - curr is present in the hashmap before putting the curr in map , So if the curr elem is duplicate of some element that is previiously present, we wont have to worry coz we are checking before inserting .
@samlinus836
@samlinus836 Год назад
@@ayushmittal9666 Understood thanks
@cinime
@cinime Год назад
Understood! Super awesome explanation as always, thank you very very much for your effort!!
@Manipinnaka
@Manipinnaka Месяц назад
i got an small logic striver not so optimal for(int i = 0; i < nums.length; i++) { for(int j = i + 1; j < nums.length; j++) { if(target-(nums[i]+nums[j])==0){ return new int[]{i,j}; array:[8,4,6,12[ } ex: target =14 14-(8+4)=!0x 14-(8+6)=0 true so we wil return the indexes
@m_fi8926
@m_fi8926 Месяц назад
in the brute force approach you should have initialized j=i+1;
@bhavyasharma3500
@bhavyasharma3500 Год назад
Hats off to you striver bro
@rhapsody4025
@rhapsody4025 Год назад
12:36 sorting the array itself will take O(n*n) then another O(n) for the 2 pointer traverssal whick adds up to O(n*n) ruining the whole point of optimisation !
@venkatesh_kens
@venkatesh_kens Год назад
No bro when we sort using bubble sort or selection sort or insertion sort we will get O(n*2) but if we use MERGE SORT or QUICK SORT we will end up with O(N*log(N)) that’s what he is saying to do
@venkatesh_kens
@venkatesh_kens Год назад
But in this question we need to use only QUICK SORT but not MERGE SORT becoz MERGE SORT space complexity is O(N) but for Quick Sort it is O(1)
@venkatesh_kens
@venkatesh_kens Год назад
And you can see him saying it at 16:51
@balajik7376
@balajik7376 6 месяцев назад
Got the same doubt
@balajik7376
@balajik7376 6 месяцев назад
​@@venkatesh_kensyou cleared it thanks❤
@zameeralucknowi872
@zameeralucknowi872 Год назад
Thank u soo much Dada, u r the real inspiration. Respect++;
@charuwaka1
@charuwaka1 7 месяцев назад
3:33 here you can keep j=i+1 instead of 0 so you don' need to write i==j
@Nishantkumar-oh9th
@Nishantkumar-oh9th Год назад
HE just killed it as it says🤗
@nagame859
@nagame859 Год назад
Top notch 🤩. Understood
@soumyadeepchatterjee2189
@soumyadeepchatterjee2189 4 месяца назад
For the 2 pointer approach, if we are sorting the array it is changing the original indexex. So, it is giving a error in LeetCode.
@arshpuri3079
@arshpuri3079 22 дня назад
i am having trouble in understanding that when we declare a map how can we immediately start finding elements in it without filling in the values
@reshmah1497
@reshmah1497 15 дней назад
Only after filling the map as we iterate on the array, we can find elements.
@arunimachakraborty1175
@arunimachakraborty1175 10 месяцев назад
Awesome explanation, thanks a lot
@chidambarjoshi3470
@chidambarjoshi3470 Год назад
I did not understand why you did mpp[a]=i at the last in the type-1 problem
@girdhar3224
@girdhar3224 Месяц назад
can we do binary search and improve on approach
@SigmaEditsbr
@SigmaEditsbr 6 месяцев назад
Thanks sir for provide us this type of content ❤❤❤
@lifehustlers164
@lifehustlers164 Год назад
Completed 5/28!!!
@poojadasari8140
@poojadasari8140 Год назад
Understood. Very clear explanation
@jay8118
@jay8118 Год назад
Job ke saath saath Padhana koi inse sikhe..🙌🙌
@karamveeryadav8824
@karamveeryadav8824 4 месяца назад
00:06 The video covers the 'two sum problem' and its two varieties. 02:04 Two sum problem can be solved using brute force method 04:05 Optimizing 2 Sum problem using a better solution 06:08 Using hashing to easily retrieve elements from a data structure. 08:13 Find the indexes of two elements in an array 10:30 Two pointer approach is a slightly better solution to solve the problem without using a map data structure. 12:38 Using the two-sum problem to find pairs that add up to a given target 14:51 The time complexity of the algorithm is O(n) 16:49 Space complexity and array manipulation explanation Crafted by Merlin AI.
@ronakparjapati2264
@ronakparjapati2264 4 месяца назад
bhaiya Third approach will not be apply if we return index of both element because if we do sort the element then automatically element indexes will be changed...
@shubhamlipane8634
@shubhamlipane8634 Год назад
Understood Thank You :-)
@banothutharun2743
@banothutharun2743 7 месяцев назад
understood sir
@yashicagarg6365
@yashicagarg6365 Год назад
Can we do this using recursion like picking up the index and not picking....please share the code for it.
@27-Joshna
@27-Joshna 9 месяцев назад
even im looking for that solution
@priyankagorkhe2870
@priyankagorkhe2870 Год назад
Your way of teaching is amazing but I struggle sometimes to convert your code into Python only then when I m facing complexities otherwise its manageable. I would request if you can add Python code of the solutions as well. Thank you !
@himanshukumar7034
@himanshukumar7034 Год назад
Refer to his sheet in given description , you can easily find python code as well
@ExpoDev_Dash
@ExpoDev_Dash 10 месяцев назад
for optimal solution why cant we return the pointer values as indexs ?? for variety 2
@saumitrapandey3070
@saumitrapandey3070 10 месяцев назад
because after sorting the array indexes are changed
@saibunny1253
@saibunny1253 2 месяца назад
thank you anna
@ybs383
@ybs383 10 месяцев назад
The Last Optimal Solution of Sorting an array and using two pointer technique will be difficult to use if Array is not Sorted and I have been told to return index of the pairs.
@RajNamdev_19
@RajNamdev_19 3 месяца назад
Understood;
@thesalahrand
@thesalahrand 11 месяцев назад
Understood
@haramritsingh6521
@haramritsingh6521 Год назад
Understood !
@mohithvaishnav4317
@mohithvaishnav4317 Год назад
you jus make things easier..
@devil_m_0069
@devil_m_0069 3 месяца назад
while (left
@AhanaVats-m7h
@AhanaVats-m7h 5 месяцев назад
understood brother💞
@DK-ox7ze
@DK-ox7ze Год назад
Average and worst csse TC of unordered Hashmap is O(1) and O(N), so total TC can be O(N) or O(N^2). So how did you arrive at total TC of O(NlogN) for the better approach?
@lakshitamanie85
@lakshitamanie85 Год назад
Sir has suggested to take ordered_map which has TC = O(logN) for search and insertion instead of unordered_map in case we are given with critical inputs or when problem might end up to worst case.
@shlokpatel3105
@shlokpatel3105 4 месяца назад
Where can I find the python code for the same? In the notes its C++ and Java
@samuelfrank1369
@samuelfrank1369 11 месяцев назад
Understood. Thanks a lot. Make More videos please......
@m.nirupreddy8001
@m.nirupreddy8001 Год назад
Understood! great explanation
@RamanKumar-er8ie
@RamanKumar-er8ie Год назад
it does not work on tc=-3,-2,2,3,3 any please help me out in this
@kingbadshah452
@kingbadshah452 8 месяцев назад
understood everything .... thanks striver
@vinayakd4444
@vinayakd4444 5 месяцев назад
What to do if for the optimal solution there are duplicate elements? The next occurrence of the element overwrite the previous index and it leads to wrong answers if we were to return all the solutions. However the current code works if there are no duplicate elements and if only one unique solutions exists. Can someone tell me if they found a good approach to deal with duplicate elements (when we have to return index)
@GhostVaibhav
@GhostVaibhav Год назад
Understood 🔥
@Palak-qy7jo
@Palak-qy7jo 8 дней назад
in the optimal approach why cannot we return left and right pointer for indexes
@Himanshuhhk
@Himanshuhhk 5 дней назад
because the array is sorted now and the original indexes will be not available .
@RahulUnscripted_
@RahulUnscripted_ 3 месяца назад
Can anyone pls explain why it is checked whether remaining is not equal to mp.end() 👀👀
@SAGARSINGH-ej4rj
@SAGARSINGH-ej4rj Год назад
def two(): nums = [3, 3] target = 6 dic = {} for i, v in enumerate(nums): dic[v] = i nums.sort() left = 0 right = len(nums) - 1 iteration = len(nums) - 1 for _ in range(iteration): if nums[left] + nums[right] == target: if dic[nums[left]] == dic[nums[right]]: a = dic[nums[left]] dic.pop(nums[left]) b = dic[nums[right]] return a, b else: return left, right elif nums[left] + nums[right] > target: right -= 1 elif nums[left] + nums[right] < target: left += 1 print(two()) Hello! Bro I am getting problem in line 22 while popping the key[3] with value (0, 1), Because its a test case of num = [3, 3] and target = 6. So, while in a dictionary when we remove a key it removes all the matching keys. Try to give us the solution with this test case --> nums = [3, 3] and Target = 6 👈🏻👈🏻 👆🏻👆🏻👆🏻👆🏻 This is my only request, Don't get frustate with my code just plz resolve this test case with your Opinion and Logic.🙏🏻🙏🏻 Please..
@sainallajarla7022
@sainallajarla7022 21 день назад
Understood !!
@2Roshan9
@2Roshan9 9 месяцев назад
I am starting leetcode from 1st January 2024 1st problem two sums
@ShravanKumar-wg9pv
@ShravanKumar-wg9pv 2 месяца назад
I have a doubt at 10:12 at line number 10. Why that mpp[a] = i is used there.... If any one knows please explain
@shreyamittal9152
@shreyamittal9152 2 месяца назад
same doubt
@mannusharma3228
@mannusharma3228 18 дней назад
To store that key value in map...
@udaytewary3809
@udaytewary3809 Год назад
Understood bhaiya 🙏 ❤️
@Mani_0962
@Mani_0962 6 месяцев назад
1.Understood
@Radhika-0110
@Radhika-0110 2 месяца назад
Understood💌
@rupalikumari8829
@rupalikumari8829 3 месяца назад
Understood : )
@madhu_mohanreddy
@madhu_mohanreddy 3 месяца назад
lets go!!
@NeelakshiSachdeva
@NeelakshiSachdeva 3 месяца назад
Which year are u guys in?
@anshulrai6058
@anshulrai6058 12 дней назад
understood 👍
@TrinmoyDutta
@TrinmoyDutta 10 месяцев назад
how the time complexity is O(n), sorting also has a time complexity, please explain
@ameyshinde4297
@ameyshinde4297 Год назад
// Two Sum in Java using HashMap TC --> O(N) import java.util.*; class HelloWorld { static int[] twoSum(int arr[] , int target) { HashMap map = new HashMap(); for(int i=0;i
@abhijeetmishra3804
@abhijeetmishra3804 Год назад
understood bhaiya. u r best
@CodeWithAnishDubey
@CodeWithAnishDubey 4 месяца назад
Understand…….👍🏻
@himanshukaushik9223
@himanshukaushik9223 Год назад
Koi muja batayega hum return parenthesis ma kyu kar rahe ha curly braces ma kyu nahi ??
@konankikeerthi
@konankikeerthi 4 месяца назад
Understood bro.. thank you
@faizanahmed9304
@faizanahmed9304 Год назад
striver bhaiya, thank you so much!!
@gautamsaxena4647
@gautamsaxena4647 17 дней назад
understood bhaiya
@oyeesharme
@oyeesharme 21 день назад
thank you bhaiya
@zororonoroa2194
@zororonoroa2194 Месяц назад
mpp.find(more) != mpp.end() can anyone explain why its like that why comparing with end?
@ekta9145
@ekta9145 22 дня назад
Understood
@utsavseth6573
@utsavseth6573 Год назад
As usual lovely.
@kamsaial
@kamsaial 2 месяца назад
Can anyone help me When solving with 2 pointer approach Raj is mentioning greedy What does he mean Greedy here
@torishi82
@torishi82 2 месяца назад
Samaj aa gaya!!
@AtulPal
@AtulPal 7 месяцев назад
I am still looking for hash function, which can work for similar values. example : input array contains : [ 1 1 1 1 1 1 4 1 1 1 1 1 7 1 1 1 1 ] where some constant number of value are other integers and mostly all values are same. in other ways: BigOh (n - c) values are similar and number of different values are "c" constant # of values as we can see above input array as example. If anyone have understood the problem, please share your thought, I will highly appreciated. I know the problem with Hashing is collisions, and find will take BigOh(n) for above example. Can anyone help me to find the solution??
@PIYUSHRAJ-t5v
@PIYUSHRAJ-t5v 7 месяцев назад
What if duplicate elements exist ?In that case two pointer approach will fail …!!
@rohansachdeva627
@rohansachdeva627 9 месяцев назад
I feel confident till step 3.1, shall i jump to next topic (like linkedlist, trees) or continue the medium and hard sections? Please someone reply.
@shrad6611
@shrad6611 5 месяцев назад
how to handle duplicates here brother ?
@heyOrca2711
@heyOrca2711 6 месяцев назад
Understood! Sir
@gersonlopes1471
@gersonlopes1471 Год назад
Great job. Thanks.
@AshishSahu-ef9rl
@AshishSahu-ef9rl Месяц назад
Thanks
@KR_Technical-hj3bf
@KR_Technical-hj3bf 3 месяца назад
I have to do clap for your optimal solution
Далее
Barno
00:22
Просмотров 538 тыс.
titan tvman's plan (skibidi toilet 77)
01:00
Просмотров 4,4 млн
Меня Забанили в Steam CS2 / PUBG
19:19
Просмотров 157 тыс.
Coding Interviews Be Like
5:31
Просмотров 6 млн
LeetCode was HARD until I Learned these 15 Patterns
13:00
3 Sum | Brute -  Better - Optimal with Codes
38:25
Просмотров 317 тыс.
BS-27. Median in a Row Wise Sorted Matrix
23:13
Просмотров 94 тыс.
How to Solve ANY LeetCode Problem (Step-by-Step)
12:37
Просмотров 231 тыс.
Barno
00:22
Просмотров 538 тыс.