Python Programming Practice: LeetCode #1 -- Two Sum

แชร์
ฝัง
  • เผยแพร่เมื่อ 25 พ.ย. 2019
  • In this episode of Python Programming Practice, we tackle LeetCode #1 -- Two Sum.
    Link to the problem here:
    leetcode.com/problems/two-sum/
    If you don't know Python, you can learn the basics of Python for data analysis using this guide I created on Kaggle (DataDaft video series forthcoming): www.kaggle.com/hamelg/python-...
    Python Programming Practice is a series focused on teaching practical coding skills by solving exercises on popular coding websites. Note that the solutions seen here may not be the most efficient possible.
    I am not going to provide the full code in the video description for this series, since copy and pasting solutions is not in the spirit of doing coding exercises. It is intended that the video will help you think about problems, approaches and how to structure solutions so that you are able to code up a working solution yourself.
    ⭐ Kite is a free AI-powered coding assistant that integrates with popular editors and IDEs to give you smart code completions and docs while you’re typing. It is a cool application of machine learning that can also help you code faster! Check it out here: www.kite.com/get-kite/?...
  • ภาพยนตร์และแอนิเมชัน

ความคิดเห็น • 98

  • @GamingNoodle
    @GamingNoodle 3 ปีที่แล้ว +138

    I've seen 100 vids on this two-sum problem and it just never clicked with me. I just dont think people could teach it in a way that I would understand. This short video of yours very clearly explained it and I finally understand now. This was a big brick wall for me so it feels amazing to finally get through it.

    • @UnknownSend3r
      @UnknownSend3r 3 ปีที่แล้ว +2

      Have you started on medium problems yet. And how are the easy problems to now, 4 months later.

    • @lonestarstatechris
      @lonestarstatechris 2 ปีที่แล้ว +2

      I know that feeling

    • @jitendrarajde430
      @jitendrarajde430 11 หลายเดือนก่อน +1

      literally same feeling brother

  • @maxgriffiths6968
    @maxgriffiths6968 4 ปีที่แล้ว +34

    This is great content. Your explanations are clear and logical. Thanks

  • @marcofer1996
    @marcofer1996 ปีที่แล้ว +6

    Great video with clear explanation on every concept. Amazing!

  • @yowanehakuuu
    @yowanehakuuu 9 หลายเดือนก่อน

    Amazing explanation, I understood for the first time after watching many videos

  • @TheMouseJerry-du1md
    @TheMouseJerry-du1md 23 วันที่ผ่านมา

    Thank you for sharing the videos. keep going and I'm purely subscribing to your channel just for leet code problems in python.

  • @9362boy
    @9362boy 3 ปีที่แล้ว +6

    This is an awesome walkthrough of coding !! Just a quick question.. Do we need the elif in 2nd solution ? Can't it be within for .

  • @bvlmari6989
    @bvlmari6989 3 หลายเดือนก่อน

    Great explanation, i needed it thank you!

  • @xkoredeveloper8422
    @xkoredeveloper8422 4 ปีที่แล้ว +2

    This is great!

  • @matattz
    @matattz ปีที่แล้ว

    This is fantastic content thank you!

  • @IDK-kv8ob
    @IDK-kv8ob 3 ปีที่แล้ว

    This is amazing. You are awesome

  • @priyavardhanpatel6155
    @priyavardhanpatel6155 3 ปีที่แล้ว +3

    thank you for such a nice way of doing and explaining the problem.

    • @DataDaft
      @DataDaft  3 ปีที่แล้ว +3

      Glad you liked it! I'm planning to do more videos like this in 2021!

    • @priyavardhanpatel6155
      @priyavardhanpatel6155 3 ปีที่แล้ว

      @@DataDaft waiting 😊

    • @sumantwankhede
      @sumantwankhede 2 ปีที่แล้ว

      sorry but i didn't understand the code/problem statement.

  • @jesusaves709
    @jesusaves709 9 หลายเดือนก่อน

    The second solution was highly efficient

  • @Moody0101
    @Moody0101 3 ปีที่แล้ว

    Thanks you, I understood :3

  • @NOBOBI1306
    @NOBOBI1306 3 หลายเดือนก่อน

    def twoSum(self, nums: List[int], target: int) -> List[int]:
    numToIndex = {}
    for i in range(len(nums)):
    if target - nums[i] in numToIndex:
    return [numToIndex[target - nums[i]], i]
    numToIndex[nums[i]] = i
    return []

  • @user-nv2uq5yq3t
    @user-nv2uq5yq3t 4 หลายเดือนก่อน +1

    def twoSum(array, target):
    for x in array:
    if target - x in array and target - x != x: return [array.index(x), array.index(target - x)]
    easy 3 liner

    • @dapianna23
      @dapianna23 3 หลายเดือนก่อน +3

      That works for distinct numbers but not if the numbers that add up to the target are the same. If the array is [2,2] and target = 4, it should return [0,1] but your function returns [] instead.

    • @user-nv2uq5yq3t
      @user-nv2uq5yq3t 2 หลายเดือนก่อน +1

      you're right. it should be index(target-x) != index(x). my bad

  • @jimmymesa
    @jimmymesa 4 ปีที่แล้ว +17

    In the 2nd solution, how does Python find out whether the value is or is not in the dictionary without looping through the dictionary somehow?

    • @DataDaft
      @DataDaft  4 ปีที่แล้ว +38

      Good question Jimmy.
      Dictionaries in Python are implemented as hash tables under the hood, which allow you to look up whether an item exists in the table directly in constant run time instead of having to go through every element one at a time to check membership like you would with a normal list or array. Basically, the keys or index values for a dictionary are passed through a complicated "hash function" which assigns them to unique buckets in memory. A given input value for the key or index will always access the same bucket when passed through the hash function, so instead of having to check every value to determine membership, you only have to pass the index through the hash function and then check if anything exists at the bucket associated with it. The drawback of dictionaries is that they are not ordered and require more memory than lists.

  • @liatris69
    @liatris69 2 ปีที่แล้ว +10

    What about traversing the list, subtracting the number at the current index from 9 and then searching the list for the complement?

    • @nourdouffir
      @nourdouffir ปีที่แล้ว +5

      Each search of the list takes O(n) time, and u have to do this for every number in the list. This works, but isn’t the most efficient solution.

  • @joshikaran-zm2ju
    @joshikaran-zm2ju 10 หลายเดือนก่อน

    other videos in yt looks like they memorizing the code and faking like the they thinking and coding , but this one looks legit

  • @sangpark7656
    @sangpark7656 11 หลายเดือนก่อน

    hey, but seen = {} is an empty string at first. how can it be assumed to contain?

  • @user-qs6gz4gt3r
    @user-qs6gz4gt3r 8 หลายเดือนก่อน

    Thank you sir ❤

  • @newyabba5756
    @newyabba5756 2 ปีที่แล้ว

    Aren’t numbers from 2nd loop being used more than once?

  • @kosmonautofficial296
    @kosmonautofficial296 ปีที่แล้ว

    Great video thank you. I paused and thought about this for a while and didn't come up with the dictionary lookup.

    • @greyshopleskin2315
      @greyshopleskin2315 ปีที่แล้ว

      Hashmaps (dictionaries) are very useful for algorithm. They're used a lot.
      Whenever you're stuck just think: would a hashmaps help me?
      Also, keep in mind whenever input is sorted or not, if binary search can be useful, trees or graphs. Also recursion and memorization

  • @Elunicozorro
    @Elunicozorro 4 หลายเดือนก่อน

    Should we just assume that for the first solution that the two values that sum to target will be consecutive?

  • @kvelez
    @kvelez 8 หลายเดือนก่อน

    def sum_index(arr, i):
    if i >= len(arr) - 1:
    return 0
    now = arr[i]
    next = arr[i+1]
    sum = now+next
    print(f"Sum {i+1}: {sum}")
    return sum + sum_index(arr, i+1)
    print(sum_index([2,7,11,18], 0))

  • @Draco-pu4ro
    @Draco-pu4ro 3 ปีที่แล้ว +8

    Your explanations are so precise and easy to understand. Is it possible to make three sum explanation video?

    • @DataDaft
      @DataDaft  3 ปีที่แล้ว +1

      Thanks for the kind words. I will consider making some more python programming practice videos after I finish the last 3 lessons of the Python for Data Analysis series I'm working on.

    • @Draco-pu4ro
      @Draco-pu4ro 3 ปีที่แล้ว

      @@DataDaft Thanks :). can you share me the links for Data Analysis series?

    • @DataDaft
      @DataDaft  3 ปีที่แล้ว +2

      @@Draco-pu4ro th-cam.com/play/PLiC1doDIe9rCYWmH9wIEYEXXaJ4KAi3jc.html

    • @Draco-pu4ro
      @Draco-pu4ro 3 ปีที่แล้ว

      @@DataDaft Thanks for your support

  • @jaishreeram4177
    @jaishreeram4177 6 หลายเดือนก่อน

    Using recursion:
    def twoSum(j=0,i=1):
    if (nums[j]+nums[i])==target:
    return [j,i]
    else:
    return twoSum(j+1,i+1)

    print(twoSum())

  • @ajm0o
    @ajm0o 3 ปีที่แล้ว

    def check_result(myList , target):
    if len(myList) target \
    or target != myList[i] + myList[i+1] :
    continue
    list_indx.extend([i , i+1])
    return list_indx
    myList = [1 , 2 , 3 , 4 , 5 , 6]
    target = 7
    print(check_result(myList ,target ))

  • @beb57swatimohapatra21
    @beb57swatimohapatra21 3 ปีที่แล้ว

    can we do it using list? plz someone send me the code, cz m getting wrong answer using list

  • @simparinkasamuel7810
    @simparinkasamuel7810 4 ปีที่แล้ว +2

    superb!.

  • @wesleyurena2217
    @wesleyurena2217 ปีที่แล้ว

    How would I wun this code in VScode?

  • @ShubhamKumar-iv7qh
    @ShubhamKumar-iv7qh 3 ปีที่แล้ว

    Why showing Syntex error

  • @Bingbong420style
    @Bingbong420style ปีที่แล้ว +2

    One question regarding the seen dictionary. We create an empty dictionary called seen, however we are then checking the dictionary to see if it contains the (target-current) number. I am confused on how it went from being empty, to potentially storing numbers?

    • @iroveth6690
      @iroveth6690 11 หลายเดือนก่อน +1

      elif

    • @DetectiveConan990v3
      @DetectiveConan990v3 2 หลายเดือนก่อน

      because we add numbers to it eventually. line 10 is where we add to it. the reason we can't make it originally contain the first number for example is because lets say the target is 4 and the first number is 2, then we see that 4-2 is already in the dictionary but that is an error since we need two values, not one. So it's just something done at initialization which helps with that first issue.

  • @michasekua4642
    @michasekua4642 2 ปีที่แล้ว +3

    I added this code into my Pycharm.
    nums = [2,4,6,8,10,12,14,16,18,20,100]
    target = 18
    class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
    seen = {}
    for i, num in enumerate(nums):
    if target - num in seen:
    return([seen[target - num], i])
    elif num not in seen:
    seen[num] = i
    print(twoSum())
    and I got error:
    NameError: name 'List' is not defined

    • @FsimulatorX
      @FsimulatorX 2 ปีที่แล้ว

      either remove 'List', or replace it with 'list'

    • @Miggy97
      @Miggy97 ปีที่แล้ว

      Might be an error with pycharm as 'List' should be 'list' on there.

  • @DeshBhakt588
    @DeshBhakt588 หลายเดือนก่อน

    def getindex(n,lis):
    for i in lis:
    If n - i in lis:
    return[lis.index(i),lis.index(n-i)]
    Just reduced number of line

  • @Kerogas_
    @Kerogas_ 6 หลายเดือนก่อน

    I don't understand the 2nd solution.
    At first we have an empty dict.
    On a first iteration we added "2: 0" to it.
    On a second iteration we subtracted 7 from 9 (target - num) and got 2, that we already have in "seen" as key.
    But what is going on in the line 8???
    As I can see it is [2, 1] because 9-7 = 2 and i on 2nd iteration is 1.
    But how are we getting [0, 1]?

    • @HarshvardhanKanthode
      @HarshvardhanKanthode 5 หลายเดือนก่อน

      Line number 8 is just returning the Index of the previous number and the index of the current matching number.
      The first iteration stores {'2' : 0 } in Seen.
      The 2nd iteration will search for a Key = 9-7 = 2, this key exists in the Dictionary.
      So it will input '2' in the dictionary, and get back "i" which is the index that we stored the key with. Since we stored 2 in the first iteration itself, the "value" of the "key" is 0.
      So it will output [0,1]

  • @phoebeiz
    @phoebeiz 10 หลายเดือนก่อน

    Can anyone explain me why bulid a new dictionary?

  • @davidebizzarri9460
    @davidebizzarri9460 4 หลายเดือนก่อน

    Isn't doing
    "if target - num in seen:" in the second solution the same as looping over all the elements of seen? If this is the case, why is the second solution faster than the first one?

    • @user-dq4fc2zs3p
      @user-dq4fc2zs3p 3 หลายเดือนก่อน

      Python interpreter probably uses C when you use built-in things like 'in", so it will be faster than making Python itself to loop over the array

    • @DetectiveConan990v3
      @DetectiveConan990v3 2 หลายเดือนก่อน

      its a dictionary which has faster access time than a list

  • @bubbatheg
    @bubbatheg 11 หลายเดือนก่อน

    Another solution could be: looping through all the numbers

    • @pharaoh9483
      @pharaoh9483 10 หลายเดือนก่อน

      if you use the loops you would have to do a double for loop and that would be O(n)^2 which is slower than the O(n) which he showed

  • @taenight2359
    @taenight2359 ปีที่แล้ว

    why did we exclude the last number in 1st loop using -1??

    • @joaquing3263
      @joaquing3263 ปีที่แล้ว +1

      It’s not excluding the last number. Think of it this way.
      Here are the numbers being checked:
      1 2 3 4 5
      The total numbers. Length of list. I.e Len(num) is equal to a list of 5 numbers.
      If we are checking the first number against the rest, then that means that we are checking:
      1 against 2,3,4,5
      In other words. We are checking 1 against the other numbers by looping 4 times. Since 2,3,4,5 are the total of 4 numbers. Another way to represent this is length of the list, which is 5 minus one which is 4. I.e. len(list)-1

    • @mryup6100
      @mryup6100 8 หลายเดือนก่อน

      The number is only excluded in the outer loop, but it's ok because it's included in the inner loops. Writing it this way (along with the i+1 in the inner loops) is more efficient since you avoid adding the same numbers (not allowed) or numbers you already added. All this without any conditional checks.
      If a list has a length of 5, then it has the indices 0,1,2,3, and 4. Using the 1st solution in the video, looping through the example list above would look like the following. With the number on the left being the index in the outer loop, and the numbers on the right of the arrow being the indices in the inner loop.
      Outer Loop 1: 0 -> 1 2 3 4
      Outer Loop 2: 1 -> 2 3 4
      Outer Loop 3: 2 -> 3 4
      Outer Loop 4: 3 -> 4
      Notice how no valid combination is left out.

  • @amanullahshareef1768
    @amanullahshareef1768 2 ปีที่แล้ว

    why did we not loop till the end for the first loop, and did the len(nums)-1

    • @newyabba5756
      @newyabba5756 2 ปีที่แล้ว

      In 2nd loop, it will start at i+1.
      If first loop reach num , 2nd loop start at num+1 .. array out of index

    • @huynhwinnie7383
      @huynhwinnie7383 2 ปีที่แล้ว

      I had the same question but just figured it out. So let’s say you have an array of 2,3,5,7,4,8,12,1. If we loop first loop til the end without len(nums)-1 then there will be this case when 1 (of the first loop) + 1 (of the second loop). The requirement is not use the same element twice so…

    • @basedgod5881
      @basedgod5881 ปีที่แล้ว +1

      @@huynhwinnie7383 doesnt matter as long as u start the second loop from i + 1 you will never loop over the same two indices it will just return none

    • @huynhwinnie7383
      @huynhwinnie7383 ปีที่แล้ว

      @@basedgod5881 ah thanks for the explanation!!

  • @lorenagonzales2350
    @lorenagonzales2350 3 ปีที่แล้ว +1

    why -1 in the first loop? Without -1 works as well.

    • @huynhwinnie7383
      @huynhwinnie7383 2 ปีที่แล้ว +5

      Imagine you have [2, 7, 11, 15]. If you dont -1 the first loop then when you loop all the way to the end there will be this case when 15 of the 1st loop + 15 of the 2nd loop but the requirement said you can’t use same element twice.

    • @Miggy97
      @Miggy97 ปีที่แล้ว

      It will go to the end of the loop and give you an index error since the last element will be given index+1 on the second loop which will cause the error.

    • @anshurana9451
      @anshurana9451 11 หลายเดือนก่อน

      Can you give me your insta id

  • @m.c80
    @m.c80 2 ปีที่แล้ว

    What DS/a is being used here?

    • @Sam-yu4ve
      @Sam-yu4ve 10 หลายเดือนก่อน

      yo mama

    • @alfalink98
      @alfalink98 10 หลายเดือนก่อน

      @@Sam-yu4vethanks friend

  • @brandiblythcook754
    @brandiblythcook754 2 ปีที่แล้ว +3

    Thanks for this, the way you explained it makes sense. However, when I try to run it on leetcode, I get a syntax error
    class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:

    # don't want to look at the last index (i = index)
    for i in range(len(nums)-1):
    # dont need to look at indices we've already seen
    # -> i + 1, then go to end of nums
    for j in range(i+1, len(nums)):
    if nums[i] + nums[j] == target:
    return([i,j])


    This is exactly what I have :(

    • @brandiblythcook754
      @brandiblythcook754 2 ปีที่แล้ว

      well I removed type identifiers and it works. Not sure why it's saying Syntax error :/

  • @sangpark7656
    @sangpark7656 11 หลายเดือนก่อน

    hey, what's the purpose of enumerate here?

    • @Sam-yu4ve
      @Sam-yu4ve 10 หลายเดือนก่อน

      it gives you the index value as well as the number in the list

  • @YouTubeTOS
    @YouTubeTOS ปีที่แล้ว

    don't say easy! i only searched it up, cause i was confused why my code wasn't working right
    class Solution1:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
    for i in range(len(nums)):
    for j in range(i+1, len(nums)):
    if nums[i] + nums[j] == target:
    return [i, j]

  • @kvelez
    @kvelez 8 หลายเดือนก่อน

    def sum_index(arr):
    for i in range(len(arr)-1):
    now = arr[i]
    next = arr[i+1]
    sum = now + next
    print(f"Sum {i} = {sum}")
    sum_index([2,7,11,15])

  • @danielsun716
    @danielsun716 2 ปีที่แล้ว

    1. I just don't know the logic from 1st one to the 2nd one. I mean how can we jump up to the 2nd logical solution from the 1st one since I am a beginner for coding. I don't think this idea in the 2nd solution would come up in my mind. That is the biggest problem for me.
    2. elif num not in seen:
    seen[num] = i
    lets take an example, [ 3, 3]. target is 6. at first, since the seen dictionnary is empty, so seen should be {3:0} or {0 : 3} ? I just dont know "elif num not in seen" in the dictionary is pointed to the key or the value. that makes me so confused. Can someone help me to figure this out? Cause I searched all the information which not mentioned like this.

    • @huynhwinnie7383
      @huynhwinnie7383 2 ปีที่แล้ว

      It can’t be [3,3] because the requirement said that you may not use same element twice. So every single element in an array or list must be different

    • @DetectiveConan990v3
      @DetectiveConan990v3 2 หลายเดือนก่อน

      have you studied data structures? it is imperative that you do so.

    • @danielsun716
      @danielsun716 2 หลายเดือนก่อน

      @@DetectiveConan990v3 not yet. But I have learnt more than then. Thanks a lot.

    • @DetectiveConan990v3
      @DetectiveConan990v3 2 หลายเดือนก่อน

      @@danielsun716 yeah man good luck

  • @IMDash_freak002
    @IMDash_freak002 9 หลายเดือนก่อน

    I can't understand it 😭

    • @mryup6100
      @mryup6100 8 หลายเดือนก่อน

      I understand that feeling, that just means you really have to break down the problem to understand it. Walk your way through the code, step by step as if the code were executing in slow motion, then it should make more sense why the code is the way it is.

    • @DetectiveConan990v3
      @DetectiveConan990v3 2 หลายเดือนก่อน

      okay here's how I think of it, you basically go through the whole list and at each time you ask yourself, have we already seen the other number which we need to add to this number to get the target value? if yes, return the two indexes. if not, then keep looking until we come to a number where we have already found the number needed to make the first number add to the target. by the time we get to the second of the two numbers, it is guaranteed that the first number will be in there. btw the solution is guaranteed to be in there. maybe this doesn't make sense or maybe it does idk

  • @swworn
    @swworn ปีที่แล้ว

    i dont understand anything

    • @PseudoTertioo
      @PseudoTertioo ปีที่แล้ว

      that's how I feel revisiting this after 2 years and is funny i think i solved this problem before and just forgot

  • @tochimclaren
    @tochimclaren 2 ปีที่แล้ว

    While loop... Pathetic.

  • @addictedroaster1573
    @addictedroaster1573 2 ปีที่แล้ว +1

    U are just copying the code..... Peeky eyes

    • @DataDaft
      @DataDaft  2 ปีที่แล้ว +9

      Yes, I prepare the code ahead of time for presentation. It is impossible to come up with and code solutions to problems as fast as I do in these videos off the cuff.

    • @loden5677
      @loden5677 2 ปีที่แล้ว +3

      @@DataDaft reading this was reassuring, thought I was crazy unable to solve it so methodically and smoothly + quickly lol

    • @navjotsingh2251
      @navjotsingh2251 2 ปีที่แล้ว

      @@loden5677 if you practice data structures off by heart, you can start to think "hey, I can use an array and implement algorithm x" or "hey, I can use bubble sort then use a hashmap and use this structure"
      Python has got lots of data structures, so it's worth learning them and start to think in data structures. Then you can start building algorithms more easily. Java is also a language with lots of good data structures built in, so I'd recommend using java and python to get good with data structures and start understanding algorithms.
      The better you understand data structures, the better you smoothly build algorithms based on them.