Leetcode Solution - 1.0 Two Sum | Javascript

  Рет қаралды 86,147

ThinkFWD

ThinkFWD

Күн бұрын

Пікірлер: 114
@shrfu31
@shrfu31 4 жыл бұрын
This is super helpful as a bootcamp student. I also appreciate seeing the errors happen.
@ThinkFWD
@ThinkFWD 4 жыл бұрын
Thank you ! Hope this helps you out. As i was in the same shoes as you a few years ago ! keep it up
@humancyyborg
@humancyyborg 4 жыл бұрын
you are amazing, the best leetcode walkthrough so far... so natural, not just pounding straight into problems
@ThinkFWD
@ThinkFWD 4 жыл бұрын
Thank you so much ! I will continue to make more. I was away and taking a break . but now i'm back :)
@sreekumarmenon
@sreekumarmenon 4 жыл бұрын
if the array is sorted, we can use 2 pointers approach as well - function twoSum(nums, target){ let left =0; let right = nums.length-1; while(left < right){ const sum = nums[left] + nums[right]; if(sum == target){ return [left, right]; } else if(sum > target){ right--; } else { left++; } } return [-1,-1]; }
@Onomandah
@Onomandah 4 жыл бұрын
Another solution, perhaps a much easier one, would be to have 2 pointers on either end of the array. But this solution was new for me. Thank you.
@daveisdead
@daveisdead 3 жыл бұрын
Wouldn’t that be assuming the array is sorted?
@sreerags5818
@sreerags5818 Жыл бұрын
Only work for sorted array
@altayezekariyas9243
@altayezekariyas9243 2 жыл бұрын
const twoSum = (nums, target) => { for(i of nums ){ a = target - i if (a in nums){ return [nums.indexOf(i), nums.indexOf(a)] } } };
@captainalpha4853
@captainalpha4853 Жыл бұрын
I think the complexity of this algorithm is O(n^2). Since "in" operator has a loop implementation internally
@Amar11115
@Amar11115 2 жыл бұрын
Thanks for the video! I am a beginner, Learned a lot for you.
@narayanareddy15
@narayanareddy15 2 жыл бұрын
Thanks for the detailed explanation. Please continue this series 🔥
@SuperKojota
@SuperKojota 4 жыл бұрын
Hi.Why you dont use classic if-else in this challenge? I am used to work with if(statement ) then { return something} then else{ return something}.
@hongkaihuang1503
@hongkaihuang1503 Жыл бұрын
best explanation... You are a monster.
@pratiik37
@pratiik37 4 жыл бұрын
You're doing a great job🔥🤗
@Simple_Otaku
@Simple_Otaku 3 ай бұрын
설명이 깔끔합니다. 감사합니다😊
@islamibrahim8121
@islamibrahim8121 2 жыл бұрын
This was really helpful. (My attempt at interpreting the solution provided) Halfway through your introduction of the solution I thought you were going to do a first loop where each difference is stored in the map and then a second one where we check each element against the map. This is an interesting optimisation of this that uses the property that if two numbers add to a third, then removing one number will yield the other (which, based on the question, should be in the list. And no repetition so just one pass was sufficient). Good stuff!
@ДениИмагожев11
@ДениИмагожев11 3 жыл бұрын
That's perfect, very detailed and helpful👍🏻👍🏻👍🏻 thanks
@TheSaltyCook
@TheSaltyCook 2 жыл бұрын
this was really great. thank you for walking through each step of the logic.
@javascript_developer
@javascript_developer 2 жыл бұрын
I find this same approach on other videos too. but thanks your explaination did helped me understand.
@PavanKumar-mr9td
@PavanKumar-mr9td 3 жыл бұрын
Wonderful explanation i loved it. KEEP DOING..
@beluga8230
@beluga8230 Жыл бұрын
another way if you dont want like this method :- const nums = [1,2,3,4,5,6,7,8,9]; let target = 5; var countElements = function(nums ,target) { for(let i=0;i
@gabrieltavares8214
@gabrieltavares8214 2 ай бұрын
That’s the “brute force” he said would not be the ideal solution
@DA_Karas
@DA_Karas 4 жыл бұрын
I love your videos, thank you!
@TheILOVEYOUXD
@TheILOVEYOUXD 2 жыл бұрын
Thank you for content and understanding;)
@nehaprakash3073
@nehaprakash3073 3 жыл бұрын
This is Great!! Subscribed.. Thanks to you for this!
@keerthiseelan5457
@keerthiseelan5457 4 жыл бұрын
Keep on going
@Canaano_0
@Canaano_0 11 ай бұрын
Nice video!!!
@tevinthuku
@tevinthuku 5 жыл бұрын
This was neatly done
@ThinkFWD
@ThinkFWD 5 жыл бұрын
Tevin Thuku thanks!
@minhan2198
@minhan2198 4 жыл бұрын
Hey ThinkFWD, which do you think is a better programming language is better for Algo: Java or Javascript?
@ThinkFWD
@ThinkFWD 4 жыл бұрын
Min Han whatever language your most comfortable with is the primary choice, but if you want less amount of code I would go python. But JavaScript works for me.
@jessesavoey1349
@jessesavoey1349 Жыл бұрын
For the ES6 syntax of the for of Loop where is the .entries coming from? Is this a new method from ES6?
@geek_24
@geek_24 Жыл бұрын
Hi if anyone having the same doubt the .entries is basically creating a new Array Iterator object that contains the key/value pairs for each index and its corresponding value in the array, because for of loops iterates over iterable objects, such as arrays, strings, or collections. Now nums is already an array right? so why do we need to explicitly write .entries()? So the answer is When using destructuring in the loop declaration, you need to enclose nums in the entries() method to iterate over the index-value pairs correctly. I hope it will help someone
@PeterPengUW
@PeterPengUW 5 жыл бұрын
Thx for the easy follow Along!
@ThinkFWD
@ThinkFWD 5 жыл бұрын
thank !
@jamesmeegan2066
@jamesmeegan2066 2 жыл бұрын
Learned a lot, thanks.
@Ozoocats
@Ozoocats Жыл бұрын
I can't thank you enough
@JustThink2000
@JustThink2000 3 жыл бұрын
Definitely not the most efficient solution but this was nice to see as an addnl way to solve it.
@kiadyravel975
@kiadyravel975 3 жыл бұрын
Can you tel me your solution plz, i'm very curious, because i can't find another one
@whizzkee
@whizzkee 2 жыл бұрын
I wish this made sense
@gearsighted
@gearsighted 3 жыл бұрын
Great stuff, I'm still a little confused but significantly less so! Subscribed! :D
@ThinkFWD
@ThinkFWD 3 жыл бұрын
Awesome, check out my more recent vids, those should be slightly better :)
@MrWardo2009
@MrWardo2009 2 жыл бұрын
Thank you for doing this!
@dylandupasquier
@dylandupasquier 2 жыл бұрын
huh, I've never seen .entries() used on an array. Is that the only way to enable the use of 2 declared indexes in the for loop?
@villacarlos
@villacarlos 4 жыл бұрын
Good stuff!
@pinkhairblackman8141
@pinkhairblackman8141 3 жыл бұрын
const twoSum=(nums, target) => { let storage = {}; for (let i = 0; i < nums.length; i++) { let num= nums[i]; if(storage[num] !== undefined) return([storage[num],i]) ; storage[target-nums[i]]=i; }
@justadev____7232
@justadev____7232 4 жыл бұрын
What does the time complexity equal on this one?
@ThinkFWD
@ThinkFWD 4 жыл бұрын
O(N) time with space of O(N) where N is the size of the input array.
@yashu6404
@yashu6404 2 жыл бұрын
thank you so much sir
@angeloliwanag2619
@angeloliwanag2619 4 жыл бұрын
This video is GOATED
@anastasiyat9116
@anastasiyat9116 Жыл бұрын
thank you!!❤
@edetmmekut809
@edetmmekut809 3 жыл бұрын
men u are the bomb
@simamorpho2641
@simamorpho2641 2 жыл бұрын
Simpler to understand working answer: nums = [9, 0, 7, 2]; target = 9; function twoSum(array, target) { answer = []; for (let i = 0; i < array.length; i++) { for (let j = i + 1; j < array.length; j++) { let sum = array[i] + array[j]; if (sum === target) { if (array[i] === array[j]) continue; else { answer.push(i); answer.push(j); return answer; } } } } } console.log(twoSum(nums, target));
@rizwanshaik2116
@rizwanshaik2116 2 жыл бұрын
It is a brute force approach ..to save time and space complexity maintain key, value pairs as mentioned in video
@simamorpho2641
@simamorpho2641 2 жыл бұрын
@@rizwanshaik2116 Hi! What do you mean by "brute force" in this context?
@lamnguyenduc6216
@lamnguyenduc6216 2 жыл бұрын
@@simamorpho2641 running time is O(n2)
@ogbillity
@ogbillity 11 ай бұрын
Using a nested loop is not an efficient solution.
@okonkwo.ify18
@okonkwo.ify18 2 жыл бұрын
Try to use if num in storage. It’s better
@rawstrife9762
@rawstrife9762 3 жыл бұрын
Hi great video! I have a quick question, your object has the number as a string but you are checking object[7] instead of object["7"]. Do they just parse the same way? What about object.7?
@virajjoshi7569
@virajjoshi7569 3 жыл бұрын
In example he has used single quotes for object key but it will store in number data type.
@azikkii
@azikkii Жыл бұрын
You can’t do dot notation on variables or numbers. When you put 7 in the bracket notation using the variable it still looks for the key 7. In his example I don’t think JS would have automatically put quotes around the key like that. It would have just been the number 7 as a key. I’d have to check though.
@davidc3268
@davidc3268 4 жыл бұрын
is there a benefit of adding the result of the current number - target as the object key, and the index of the current number as the value as opposed to adding the current number as the key and its index as the value? seems confusing this way.
@haripriyaramanathan3817
@haripriyaramanathan3817 4 жыл бұрын
Nice video!! Thank you!! Do you have any recommendations on what resources to use to learn JS in terms of interview prep? I learned JS from W3Schools.
@Ali-mc4le
@Ali-mc4le 4 жыл бұрын
learn Algorithms and Data Structures: www.udemy.com/course/coding-interview-crash-course-for-web-developer-2020/?couponCode=ADA6B72288D49A1CAE25
@Ali_Egamberdiyev
@Ali_Egamberdiyev 2 жыл бұрын
Thank You Bro 😇
@okidokiyowyow356
@okidokiyowyow356 2 жыл бұрын
freaking awesome
@mohitsaud2071
@mohitsaud2071 3 жыл бұрын
Nice explanation and as a result, Subscribed to the channel.
@akarshs9552
@akarshs9552 4 жыл бұрын
Hey, are these algorithms enough to crack the technical interview?
@ThinkFWD
@ThinkFWD 4 жыл бұрын
Akarsh did you watch my ace the interview vid? These questions will help with major faang and other tech companies. However some may smaller companies may ask subject specific or system design type questions. But these algo will give you some foundation
@akarshs9552
@akarshs9552 4 жыл бұрын
@@ThinkFWD No I haven't watched I will watch now actually my problem is I am building mobile apps in React Native since a year but week at Data structure and algorithms. so is it really important to learn data structure for good development?
@ThinkFWD
@ThinkFWD 4 жыл бұрын
Akarsh s when you start building things that rely less on libraries and require more foundational ways to solve things, I would say yes. Especially if your apps deal with managing large sets of data efficiently. It is probably used more in the back end micro services as well. If you want to get into most tech companies in the valley or nyc, knowing you data structures and algo is super important. When scaling an app is part of your critical path. Anyone can manually sort a deck a cards, but what if you had to sort 1M deck of cards... that same process applied to 1 won’t fly. :) hope it helps!
@akarshs9552
@akarshs9552 4 жыл бұрын
@@ThinkFWD Thanks, I am good at basics but I find difficult to crack complicated problems
@medalikhaled
@medalikhaled 3 жыл бұрын
thank you
@atoztravelgyan7247
@atoztravelgyan7247 Жыл бұрын
It says “EASY” on the top and you made it look like an enterprise project😂🤣
@ismaelfernandez6359
@ismaelfernandez6359 5 жыл бұрын
how can I change the language to Javascript on leetcode?
@ThinkFWD
@ThinkFWD 5 жыл бұрын
Emoneyonthebeat top left corner of where you can start to code, there is a drop down where you can select you me desired language
@cvxcfv
@cvxcfv 3 жыл бұрын
could be explained better but as you said this is a raw footage
@ThinkFWD
@ThinkFWD 3 жыл бұрын
I do have a more refined one as I’m kicking off a new series called 75 questions, I believe everyone should do
@elvispastiche
@elvispastiche 2 ай бұрын
you are my OPRAH
@jadedvi1044
@jadedvi1044 3 жыл бұрын
Hello guys, I can not get the systax that he uses since part If(storage[num] ...... ). Can someone suggest me where to study this new JS version ?
@wolfdaddy085
@wolfdaddy085 3 жыл бұрын
what is required to know for solving this?? I can't solve it by myself
@haoz7529
@haoz7529 2 жыл бұрын
I got "nums.entries is not a function. (In 'nums.entries()', 'nums.entries' is undefined)
@HawkingMerchant
@HawkingMerchant 3 жыл бұрын
I though by the name that I had to sum two numbers but problem is totally different
@emilyreese9551
@emilyreese9551 2 жыл бұрын
What kind of for loop is this?
@geek_24
@geek_24 Жыл бұрын
if anyone having the same doubt this is called for of loop in javascript for of loops iterates over iterable objects, such as arrays, strings, or collections. Here is the simplest example of this loop -> const arr = ['apple', 'banana', 'cherry']; for (const fruit of arr) { console.log(fruit); } Now if I want to print the index numbers too of the associated entries like apple - 0, banana -1 etc the code will be like this -> const arr = ['apple', 'banana', 'cherry']; for (const [index, fruit] of arr.entries()) { console.log(`Index: ${index}, Fruit: ${fruit}`); } we are destructuring index and entries of array and while destructuring we have to use the .entries() to get the proper array iterable that holds the key and value. Hope that helps!
@mrSargi7
@mrSargi7 2 жыл бұрын
I would've definetly used two loops here. That was a clever solution, shows why knowing algorithms is so important
@imyounick
@imyounick 2 жыл бұрын
twoSumd([3, 3, 4, 2], 6 ) - Fails in this case
@billybrains
@billybrains 3 жыл бұрын
Is it bad that i couldnt even do this question on my own…
@ThinkFWD
@ThinkFWD 3 жыл бұрын
No way! Just keep it up and built up the experience :) stay positive
@billybrains
@billybrains 3 жыл бұрын
@@ThinkFWD thanks bro! I just finished a bootcamp. Was an underwater welder for 12 years, COVID made me rethink everything. 33 years old changing careers appreciate the vids, subscribed!
@opdelta4854
@opdelta4854 2 жыл бұрын
@@billybrains if you don’t mind me asking which bootcamp did you go to? Was it worth it? Also, have you landed a job yet? I am currently deciding to attend a bootcamp or not.
@ishumishra8104
@ishumishra8104 4 жыл бұрын
hey i have used you code but it doesn't got executed,showing output Undefined !! /** * @param {number[]} nums * @param {number} target * @return {number[]} */ const twoSum=(nums,target)=>{ let storage={}; for(const [num,index] of nums.entries()){ if(storage[num]!==undefined) return [storage[num],index]; storage[target-num]=index; } };
@ThinkFWD
@ThinkFWD 4 жыл бұрын
You have the Num and index in reverse order. const [index, num] !== const [num, index].
@ishumishra8104
@ishumishra8104 4 жыл бұрын
@@ThinkFWD copied from. Your code only, so code was wrong?
@ThinkFWD
@ThinkFWD 4 жыл бұрын
@@ishumishra8104 the code in the video is not wrong. Look at my video @13:12 ... look at line 9 and you will see what you pasted is incorrect.
@ishumishra8104
@ishumishra8104 4 жыл бұрын
@@ThinkFWD I was saying my code was wrong not yours 😒
@JazzFanss
@JazzFanss 3 жыл бұрын
@@ishumishra8104 er.. maybe you should come up with your own solution like using a different type of loop instead of ( i assume) copy paste
@moosegoose1282
@moosegoose1282 3 жыл бұрын
:/ did u already did the problem
@ThinkFWD
@ThinkFWD 3 жыл бұрын
I did recently, but that is more part of a 75 question series I recommend people do.
@moosegoose1282
@moosegoose1282 3 жыл бұрын
@@ThinkFWD :( I prefer a fresh take so I can see thinking process
@ThinkFWD
@ThinkFWD 3 жыл бұрын
@@moosegoose1282 I redid it on the new vid :), but new questions are coming this week :). I’m doing 1 vid a week so stay tuned
@infyro
@infyro 2 жыл бұрын
Amazing explanation, I really appreciated this! I just have one question though that i'd like some clarification on. I'm not entirely clear how the algorithm knows to return the index once it finds the storage[num]. Any further explanation would be greatly appreciated thanks!
@dylandupasquier
@dylandupasquier 2 жыл бұрын
I'm also curious about that. I've never seen this syntax of using an array within your for loop. Super cool.
@stukagamerxtreme
@stukagamerxtreme 3 жыл бұрын
@etymology_
@etymology_ 4 жыл бұрын
Hi Everyone, here is an actual good answer, although leet code wants the indexes, this returns the actual values/the better way of doing it: const twoSum = (array, target) => { const numbers = {}; for(num of array){ const potentialMatch = target - num; if(potentialMatch in numbers){ return [potentialMatch, num] }else{ numbers[num] = true; } } return []; };
@vivarantx
@vivarantx 2 жыл бұрын
it's the same he did but you are actually making it less efficient by using that in
@christinele5832
@christinele5832 3 жыл бұрын
are you Vietnamese ?
@abhishekpatnaik144
@abhishekpatnaik144 9 күн бұрын
// arrayinput [2,7,11,15,3] target 18 function getIndicesToAchieveTarget(inputarray,target){ var finalarray=[]; for(let i=0;i
@uzairrajpoot5219
@uzairrajpoot5219 2 жыл бұрын
//Two number of sum let twoSum = (num1, num2) => { return num1 + num2; } twoSum(5, 5);
@juliusoh
@juliusoh 4 жыл бұрын
your solution is very confusing to me..
LeetCode Solution - 2.0 Add Two Numbers | Google Interview
14:27
Чистка воды совком от денег
00:32
FD Vasya
Рет қаралды 2,7 МЛН
Two Sum | LeetCode 1 | JavaScript | Easy
13:20
Gordon Zhu
Рет қаралды 11 М.
C Programming Tutorial for Beginners
3:46:13
freeCodeCamp.org
Рет қаралды 14 МЛН
Leetcode Two Sum Solution |  Coding Interview Question
13:03
techsith
Рет қаралды 32 М.
Two Sum - Leetcode 1 - HashMap - Python
8:26
NeetCode
Рет қаралды 1,4 МЛН
My Brain after 569 Leetcode Problems
7:50
NeetCode
Рет қаралды 2,7 МЛН
Leetcode Solution - 7.0 Reverse Integer | Javascript
10:18
ThinkFWD
Рет қаралды 14 М.
LEETCODE 200 (JAVASCRIPT) | NUMBER OF ISLANDS
17:54
Andy Gala
Рет қаралды 71 М.