Solving Coding Interview Questions in Python on LeetCode (easy & medium problems)

แชร์
ฝัง
  • เผยแพร่เมื่อ 3 ต.ค. 2024

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

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

    Hey everyone! If you enjoy this video, I just created a new channel where I'll be posting problems like this pretty frequently. Check it out here: th-cam.com/channels/ge9kgmp38FIjGK4xdJsThw.htmlabout (will start posting when it hits 1000 subs)
    Also, we're getting so close to 100K!! So crazy. I really appreciate everyone's support and am super thankful to have a platform where the content can reach so many. Love ya'll!

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

      It's so funny coding with your tutorials and inspired me to learn more of python. Thanks for your videos. They are really useful

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

      subscribed! Looking forward to more great content.

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

      Thanks for motivating me to come with python

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

      class Solution:
      def destCity(self, paths):#: List[List[str]]) -> str:
      going_count = {}
      for i in paths:
      [*cities] = i
      for j in range(len(cities)-1):
      going_count[cities[j]] = going_count.get(cities[j], 0) + 1
      going_count[cities[-1]] = 0
      print(going_count)
      dest = []
      for city in going_count:
      if going_count[city] == 0:
      dest.append(city)
      return dest
      paths = [['a', 'b', 'c', 'd'], ['a', 'c', 'e', 'f'], ['b', 'c', 'f'], ['d', 'j']]#, ['d', 'c']] # should not use dict
      solution = Solution()
      solution.destCity(paths)

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

      May I know which software you use to do your video editing ? Thank you !

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

    We love the way you did this. I prefer this approach over youtubers that clearly comes prepared and solve it with no hesitancy and in a bit of complex way

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

      fun to watch people get stuck like me😁

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

      @@manyes7577 😅

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

    loved how you have labeled each segment of the video with the corresponding problem title , keep up the great work !!

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

      TO LEARN AND CRACK COMPETITIVE PROGRAMS
      th-cam.com/channels/yoFQsVztx2oHWq14nY8A6A.html

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

    Thankyou so much Keith! I just learned how to approach a problem. You made it looked so easy. Please post more content like this.

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

      Glad it was helpful! You're very welcome. Definitely going to be posting more content like this on the new channel I created :)

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

      @@KeithGalli what is that channel called?

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

      TechTrek by Keith Galli:
      th-cam.com/users/TechTrekbyKeithGalli

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

    I love my own solution to the second question on Destination City. I simply returned the cityB that doesn't occur anywhere else in the whole list.
    class Solution:
    def destCity(self, paths: List[List[str]]) -> str:
    for path in paths:
    lister = [x for x in paths if x != path]
    if not (any(path[1] in listeri for listeri in lister)):
    return path[1]

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

      that's code golfing, never do this if you work with team

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

      I’d rather say “succinct”.

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

      You could just zip the paths list, and find cities in the second zip chunk not in the first using set logic. I’m surprised he didn’t do this
      start_cities, dest_cities = list(zip(*paths))
      result = dest_cities.”notin”(start_cities)
      Ooh and the result he read does this

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

    Thank you Keith for great Videos. A couple of suggestions: If you can dissect the problems, that would be great. E.g. String command = string method in Python. In order to solve this problem, you need to know class, string methods, replace() and functions. Here are the links for class,...,functions.

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

    Problem 3 - list_ = [sum(1 for k in nums if k < nums[i]) for i in range(len(nums))]

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

    Hey Keith more videos on leetcode please, this video is super awesome, love the way how you explain each and every step, please do more videos on leetcode thank you

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

      TO LEARN AND CRACK COMPETITIVE PROGRAMS
      th-cam.com/channels/yoFQsVztx2oHWq14nY8A6A.html

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

    Great video!
    Please note the middle can overflow. Thus, we prefer to use mid=start+(end-start) / 2

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

    Hey Keith love your content👍, Can you do maybe a series of videos on algorithms in python

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

    I have an interview as an intern at amazon on the 11th I will comment if I made it or not wish me luck!!! I haven't taken any alogirthm class before so I know this is going to be hard
    UPDATE[1 year later]
    I did not get a return offer after internship but I went to smaller fortune 500 then into fintech. I am a Mid Level SWE now. Its crazy how a year ago i didnt know anything.

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

      How was it

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

      How did it go

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

      😂😂😂

    • @Luis-ef2zn
      @Luis-ef2zn 2 ปีที่แล้ว +6

      @@testa5687 i think he got rekt

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

      He got dumped, 101% sure

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

    Love your videos. Each time you upload a new one, its just like you read my mind and give me exactly what I need to become a data scientist. Please do a SQL tutorial or even better a "real world" example of how using SQL together with Python. Greetings from Sweden

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

    Hey Keith, well done video!
    For the palindrome problem, your solution wouldn't work properly if you have 2 different characters with odd number of appearances, you would add both of them to the count while only one could be used as the palindrome "center"

  • @ХристинаВисоцька-в7ж
    @ХристинаВисоцька-в7ж ปีที่แล้ว +1

    Hi, Keith! Thanks a lot for the video, it's awesome!
    I have an assumption of why performance is not that good in the last problem. You use a list to implement a queue, but as far as I know Python implements list as dynamic array and removing an element from the beginning has O(n) complexity (due to shifting), so lists are suitable to be used as stacks, but very slow when used as queues.
    Instead, we could use collections.deque which has amortized O(1) complexity of removing element from either the beginning or the end (so can be used efficiently both as a stack and a queue)

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

    you're brilliant bro. The way you think really helps me understand how to solve these questions

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

    The very first problem of Goal Parser Interpretation, I made a mess.
    1. First I didn't read the question properly. My mind started thinking of different edge cases, wherein different words might be given as test inputs. (e.g. F()()t(ball), etc)
    2. I started looping over the string, I'm much habituated to loop over things which is the worst approach ever.
    3. I started trying to figure out to how to replace the single brackets without creating blank spaces.
    4. I never read the constraints properly.
    Thanks Keith for this video, it help me analyze my problems and I can start working on fixing those whilst attempting these interview questions.

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

    It was really fun to walk through these with your video after trying each one myself. Some of my solutions were the same and others quite different. Overall a great video, thanks!

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

    21:27 you probably could have used sets to remove redundant elements, then sort it ( after converting the set into list) then you can proceed further

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

    For 33:13 - LeetCode 704 - Binary Search,this is the most optimal solution.
    class Solution(object):
    def search(self, nums, target):
    return -1 if target not in nums else nums.index(target)

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

      true but that is not binary search

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

    Bro PLZZ do continue this series....each week please do post 1hr videos on leetcode python solutions

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

      Going to try to post a problem or two a week on the new channel I created, make sure to check that out!

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

      TO LEARN AND CRACK COMPETITIVE PROGRAMS
      th-cam.com/channels/yoFQsVztx2oHWq14nY8A6A.html

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

    Thank you, learned a lot from this video, Please post more videos

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

      TO LEARN AND CRACK COMPETITIVE PROGRAMS
      th-cam.com/channels/yoFQsVztx2oHWq14nY8A6A.html

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

    Thanks keith. I've been looking for content like this.

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

      Glad to hear it! You're welcome :)

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

    I solved the first one very simple. You copy the input list and reverse sorted it. Then use a loop to put the data as keys into a dictionary with values equal to the loop index. You see right away that since its sorted, the loop index gives the correct numerical output values for each number.
    From there, to create the output , you just loop through the original array and use dictionary key search to put the corresponding values into an output array.

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

    This is very helpful. more of these please!!

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

    Thanks for the great video! How common are questions like this in data science interviews compared to the pandas type questions in your stratascratch video?

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

    Excellent video! Greatly helped me. Thank you very much!

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

      TO LEARN AND CRACK COMPETITIVE PROGRAMS
      th-cam.com/channels/yoFQsVztx2oHWq14nY8A6A.html

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

    30:20 I genuinely loves how he react to his mistakes.

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

    Love this!!! Pls more content in this direction.

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

      Glad you enjoyed! Planning to post content like this pretty frequently on the new channel i created :)

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

    Loved this 🔥 please do more of such leetcode questions. Let's hit that 100k and 1k😁

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

    If the language is Python and you are allowed to 'use' Python, for question 704. Binary Search my initial thought was 'return nums.index(target)'. Why reinvent the wheel unless it was specified that the solution should be faster than the built-in function. Great video and this did definitely get the brain thinking about possible solutions and ways to improve them.

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

      .index(target) iterates through the array starting from the 0th index until the array[i] == target. Its just linear search O(n) time. Binary search is O(logn) time.

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

    I've found this (rather elegant) pythonic solution to the longest_palindrome challenge:
    def longestPalindrome(self, s: str) -> int:
    d = Counter(s).values()
    return sum(2 * (c // 2) for c in d) + any(c % 2 == 1 for c in d)

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

    Thank you Keith

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

      You're welcome :)

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

    awesome!! btw congrats on 100k soon!

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

    Thank you, Keith! Best lessons , as usual!

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

    I applied for an SRE role with a company but they also wanted someone with some Python experience, other than building speech to text chatbots and local Jarvis virtual assistants I've never worked with Python on this type of level. I did horribly on the assessment which lead me to this video. Don't know why but I cannot wrap my head around this binary, data parsing or algorithm stuff with Python, it's next level type stuff... Big ups to all that understand this, I think I'll just stick with bash scripting and IAC- Orchestration/Automation and API's using Terraform, Ansible, Packer 😒

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

    Good stuff Keith.. learning from Kenya

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

    For Second Solution, I simply converted the nested list to the dictionary and iterated the dictionary to find the city which is not a key in that dictionary :
    cities = dict(cities)

    #{'London': 'New York', 'New York': 'Lima', 'Lima': 'Sao Paulo'}

    for city in cities.values() :
    if city not in cities.keys() :
    return city

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

    great tutorial, helped me a lot!

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

    My solution was:
    If the second index of any pair does not exist as the source of any other pairs, then that's the city.
    def destCity(self, paths: List[List[str]]) -> str:
    src=[]
    dst=[]
    for x in paths:
    src.append(x[0])
    dst.append(x[1])
    for d in dst:
    if not (d in src):
    return d

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

    for the 1436, the key point is using hash table.
    def destCity(self, paths: List[List[str]]) -> str:
    citiesA = {path[0] for path in paths}
    return next(path[1] for path in paths if path[1] not in citiesA)

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

    Great video! , but can you make a video on data structure and algorithms because I understand from you way better than any other TH-cam channel.

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

      There's a lot to teach with data structures and algorithms, but it is a topic that I would like to make videos on at some point.

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

      @@KeithGalli, I will wait until then. you are my favorite teacher

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

    For 1561 maximum number of coins:
    piles.sort()
    c = -2
    result = 0
    for i in range(len(piles)//3):
    result += piles[ c ]
    c -= 2
    return result
    Or in for loop
    piles.pop()
    result += piles.pop()

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

    close to 100k lets gooo

  • @angela_rodriguez
    @angela_rodriguez วันที่ผ่านมา

    Uhm this guy deserves a million dollars from TH-cam.

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

    Nice I always wanted to be a good Uber hacker dude dudette

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

    Thank you for doing this.

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

    interesting and tricky little prob:
    def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
    result = []
    for i in range(len(nums)):
    targets = [1 for (idx,x) in enumerate(nums) if idx != i and x < nums[i]]
    result.append(sum(targets))
    return result

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

    Love the video, but I dont think the longest palindrome problem is fully correct because if you have 2 instances of odd characters, you would need to only add the count of the largest number of a specific odd character. EX: "abbccccddeee" would need to ignore the odd "a" character but instead would include the 3 odd "e" characters.

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

      Yup and he forgot also to include cases with UpperCase letters (Racecar) will return 7 instead of the correct answer 5. But great video nonetheless !

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

    In example 1365 you could've changed: if j != i to: if j < i that would have made it right. Dont ask me why, lol. I cant come up with an answer for that since < is "less than"

  • @yt-1161
    @yt-1161 2 ปีที่แล้ว

    I think when index method won’t override if it encounters the same element in the list. here is my solution to the 3rd problem @25:00
    def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
    sorted_nums = sorted(nums)
    d = {}
    lst = []
    for num in sorted_nums:
    d[num] = sorted_nums.index(num)
    for num in nums:
    lst.append(d[num])
    return lst

  • @NK-hs7io
    @NK-hs7io 3 ปีที่แล้ว

    Thank you, you are the best

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

    For smallerNumbersThanCurrent() could you get rid of the if statement and just overwrite the dictionary values, because the last overwrite will be the correct one to save. Or does writing to a dictionary take more time than the if statement to check?

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

    Hi Keith,
    This is nit picking but in for i in range(len(x)) loops are anti-patterns, for index,value in enumerate(iterable), is the pythonic way to access the index in a for loop

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

      Thanks for the tip! Using enumerate would have been a better way for me to go about it.

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

      By using the clean builtins that singularly achieve the result you want, you might also piggyback on internal optimizations :]

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

    Ok, this one works in my condition
    class Solution:
    def destCity(self, paths):#: List[List[str]]) -> str:
    going_count = {}
    for i in paths:
    [*cities] = i
    for j in range(len(cities)-1):
    going_count[cities[j]] = going_count.get(cities[j], 0) + 1
    going_count[cities[-1]] = 0
    print(going_count)
    dest = []
    for city in going_count:
    if going_count[city] == 0:
    dest.append(city)
    return dest
    paths = [['a', 'b', 'c', 'd'], ['a', 'c', 'e', 'f'], ['b', 'c', 'f'], ['d', 'j']]#, ['d', 'c']] # should not use dict
    solution = Solution()
    solution.destCity(paths)

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

    a2
    class Solution:
    def destCity(self, paths: List[List[str]]) -> str:
    cat = []
    dog = []
    for i in range(0,len(paths)):
    cat.append(paths[i][0])
    dog.append(paths[i][1])
    for i in range(0,len(dog)):
    if dog[i] not in cat:
    return(dog[i])

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

    NEAT!

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

    Hey Keith, I'm not sure if you're still active on this channel but wanted to ask a quick question. Prior to hitting record and starting the video, how much of this knowledge do you already know? Like can you just look at a problem and know what to look up or is there more complex problems where it takes a couple searches? I'm fairly new and decided to watch a coding video and was immediately intimidated by my drastic lack of knowledge... is this normal? Great video and I'll be checking out that other channel!

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

    Thank you very much for the video, it helped a lot !!(:

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

    Que vídeo incrível. Surreal. Muito didático até para mim, brasileiro.

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

    Thank you

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

    For the destination question, would that still work if you made the first path last instead? Seems like New York would be set to 0

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

    Thanks Kieth for so many insights.
    However, for LongestPalindrome, I think the solution won't work for input 'aaabbb', i.e., when more than one letter have odd count

  • @akash-uy3uh
    @akash-uy3uh 2 ปีที่แล้ว

    destination city : (easier way) lazy way :P
    paths = [["London","New York"],["New York","Lima"],["Lima","Sao Paulo"]]
    dic = dict(paths)
    origin = list(dic.keys())
    destination = list(dic.values())
    ans = set(destination).difference(set(origin))

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

    confused on how in the example [-1,3,4,6,8,9,12,15,18] if the target is 10, it would break out of the while loop instead of being stuck inside the while loop

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

    Thank you so much

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

      you're welcome!

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

      TO LEARN AND CRACK COMPETITIVE PROGRAMS
      th-cam.com/channels/yoFQsVztx2oHWq14nY8A6A.html

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

    If you aren’t subbed to Keith’s new channel you are missing out on big brain learning

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

    Great tutorial..thankyou..how does self.history[0: self.current_index] clears history in the Design browser history problem? This seems to be creating a substring of array from 0 to current_index. Please clarify

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

    For the binary search question, couldnt you just do something like
    try:
    return (nums.index(target))
    except:
    return "-1"

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

      Python's .index method implements linear search

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

    Very informative content. It’d be even more awesome if you could explain a little more in depth for beginners

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

    18:00 Mistakes are a part of the process.

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

    Do you have any suggestions for the GME thing for me? Im getting started on this crap

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

    Is this required for backend python developers interview? Thnks

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

    If we are appending the root to the output array in each iteration. How did we end up having subarrays in the output ? This confused me any help is appreciated

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

    For the 1365 challenge... Why are you sorting this in the reversed order? If you do it in the ascending order, it'll be so much easier to get the number of numbers smaller than the current one! It'll be just the index of the first occurence of the current number in the sorted list. No need to do any mathematical (and obscure) operations on the indexes. Also, no need to append constantly to an array. You can initialize an array with the right size upfront and then just assign to the slots in it. This will be soooooo much faster as the list will not need to be resized (and copied!). Not a single time. By the way, the runtimes, when submitted, can vary wildly. This probably depends on the workload on the server. I've checked it and the same solution can be the fastest one or... far, far away from the fastest. This is hugely random, which is really sad as there's no consistency here.

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

    Another solution (shorter, maybe faster, using generators):
    class Solution:
    def destination_city(self, paths: List[List[str]]) -> str:
    for dest_city in (dest for start, dest in paths):
    if dest_city not in (start for start, dest in paths):
    return dest_city
    or
    class Solution:
    def destination_city(self, paths: List[List[str]]) -> str:
    from itertools import compress
    starts = set(start for start, dest in paths)
    destinations = tuple(set(dest for start, dest in paths))
    dest_city, *_ = compress(
    destinations,
    [dest not in starts for dest in destinations]
    )
    return dest_city
    or (the solution from the vid "optimized' a bit :)
    class Solution:
    def destination_city(self, paths: List[List[str]]) -> str:
    from collections import defaultdict
    outgoing_count = defaultdict(int)
    for path in paths:
    citya, cityb = path
    outgoing_count[citya] += 1
    outgoing_count[cityb] = outgoing_count[cityb]
    for city, count in outgoing_count.items():
    if count == 0:
    return city
    and maybe the shortest...
    class Solution:
    def destination_city(self, paths: FlightConnections) -> str:
    return next(iter(
    set(e for _, e in paths)
    .difference(set(s for s, _ in paths))
    ))

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

    SIMPLE SOLUTION:
    a=[8,1,2,2,3]
    m=[]
    b=0
    for i in range(0,len(a)):#0 to 4
    for j in range(0,len(a)):#0 to 4
    if a[i]>a[j]:
    b+=1
    m.append(b)
    b*=0
    print(m)

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

    Hi, I tried the sharing between friends question but got no output
    data = [2, 4, 1, 2, 7, 8]
    Alice = 0
    Roso = 0
    Bob =0
    def split_data(data, Alice, Roso, Bob):
    share = len(data)//2
    while len(data) != 0:
    Alice += data[0]
    Roso += data[1]
    Bob += data[2]
    return Alice
    return Roso
    return Bob

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

    Hey Keith or anyone care to explain what is going on in the function parameter(smallerNumberThanCurrent(self,nums ...) I dont understand what is going on there.Thanks

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

    You miss the use of a lot of simple, easy to read builtins

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

    cool! video

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

    He got drake eye brows

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

    a3
    class Solution:
    def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
    cat = sorted(nums)
    lol = []
    for i in range(0,len(nums)):
    lol.append(cat.index(nums[i]))
    return(lol)

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

    im not smart enough for this : ( are these really easy?

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

      Work your way up! They don't start out easy, but get easier & easier as you do more. A good place to start for problems like this is codingbat.com/python

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

    They assign these in gulags in lieu of hard labor.

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

      haha, I also heard that in order to enter Silicon Valley you have to answer several of these questions.

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

    Did he get a haircut?

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

    why do you need to see your face on the video?

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

    Destination City
    out_city = {path[0] for path in paths}
    for path in paths:
    if path[1] in out_city.keys():
    out_city.pop(path[1])
    The only remaining key would be the answer

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

    Problem: LeetCode 1365: leetcode.com/problems/how-man...
    class Solution:
    def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
    output = []
    for i in nums:
    count = 0
    for j in nums:
    if i != j and i > j:
    count += 1
    output.append(count)
    return output

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

    Dude , people are gonna think you are u/deepfuckingvalue .
    The guy who started the GME🚀🚀🚀

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

      Lmao yeah, our names are super similar and we're both from the boston area. Can't be just a coincidence. 🚀🚀🚀