In this video we walk through a series of eight coding interview questions on leetcode. These are algorithms problems that cover topics including data structures, time & space complexity, sorting, binary search, object oriented programming, breadth first search, tree traversals, and more. The difficulty of problems range from easy to medium and get gradually harder as you go through the video.
Practice your Python Pandas data science skills with problems on StrataScratch!
https://stratascratch.com/?via=keith
/>
Join the Python Army to get access to perks!
YouTube – https://www.youtube.com/channel/UCq6XkhO5SZ66N04IcPbqNcw/join
Patreon – https://www.patreon.com/keithgalli
If you enjoy this video, make sure to SUBSCRIBE to not miss future videos.
Checkout out my new channel where I will frequently be posting problems like these: https://www.youtube.com/channel/UCge9kgmp38FIjGK4xdJsThw/about
Feel free to recommend the next problems that I should solve on YouTube!
Links to problems:
LeetCode 1678: https://leetcode.com/problems/goal-parser-interpretation/
LeetCode 1436: https://leetcode.com/problems/destination-city/
LeetCode 1365: https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/
LeetCode 704: https://leetcode.com/problems/binary-search/
LeetCode 409: https://leetcode.com/problems/longest-palindrome/
LeetCode 1561: https://leetcode.com/problems/maximum-number-of-coins-you-can-get/
LeetCode 1472: https://leetcode.com/problems/design-browser-history/
LeetCode 1110: https://leetcode.com/problems/delete-nodes-and-return-forest/
————————-
Timeline!
0:00 – Introduction
2:02 – LeetCode 1678 – Goal Parser Interpretation
6:04 – LeetCode 1436 – Destination City
14:07 – LeetCode 1365 – How Many Numbers Are Smaller Than the Current Number
33:13 – LeetCode 704 – Binary Search
46:13 – LeetCode 409 – Longest Palindrome
55:01 – LeetCode 1561 – Maximum Number of Coins You Can Get
1:10:09 – LeetCode 1472 – Design Browser History
1:22:32 – LeetCode 1110 – Delete Nodes And Return Forest
1:38:23 – Conclusion & Announcement!
————————-
Follow me on social media!
Instagram | https://www.instagram.com/keithgalli/
Twitter | https://twitter.com/keithgalli
————————-
If you are curious to learn how I make my tutorials, check out this video: https://youtu.be/LEO4igyXbLs
*I use affiliate links on the products that I recommend. I may earn a purchase commission or a referral bonus from the usage of these links.
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: https://www.youtube.com/channel/UCge9kgmp38FIjGK4xdJsThw/about (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!
Thank you Keith
Nice I always wanted to be a good Uber hacker dude dudette
close to 100k lets gooo
awesome!! btw congrats on 100k soon!
NEAT!
Hey Keith love your content👍, Can you do maybe a series of videos on algorithms in python
Thank you, Keith! Best lessons , as usual!
Thankyou so much Keith! I just learned how to approach a problem. You made it looked so easy. Please post more content like this.
Did he get a haircut?
Love this!!! Pls more content in this direction.
Thank you so much
Great video! , but can you make a video on data structure and algorithms because I understand from you way better than any other YouTube channel.
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]
Bro PLZZ do continue this series….each week please do post 1hr videos on leetcode python solutions
Thanks keith. I've been looking for content like this.
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"
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.
If you aren’t subbed to Keith’s new channel you are missing out on big brain learning
Dude , people are gonna think you are u/deepfuckingvalue .
The guy who started the GME🚀🚀🚀
Do you have any suggestions for the GME thing for me? Im getting started on this crap
Loved this 🔥 please do more of such leetcode questions. Let's hit that 100k and 1k😁
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
For the binary search question, couldnt you just do something like
try:
return (nums.index(target))
except:
return "-1"
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
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?
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
loved how you have labeled each segment of the video with the corresponding problem title , keep up the great work !!
Thank you, you are the best
Great job Keith! Thanks a lot.
In case someone finds the maxCoin solution too confusing with all those i and indexes, here is simpler one I came up with:
def maxCoins(piles):
sorted_piles = sorted(piles)
# sorted = [1, 2, 3, 4, 5, 6, 7, 8, 9]
my_score = 0
while len(sorted_piles) > 0:
del sorted_piles[-1] #deleting the biggest
my_score += sorted_piles.pop(-1)
del sorted_piles[0] #deleting the smallest
return my_score
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"
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
Good Video.
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.
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
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])
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)
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()
He got drake eye brows
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
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.
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
Thank you, learned a lot from this video, Please post more videos
Excellent video! Greatly helped me. Thank you very much!
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
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.
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)
Que vídeo incrível. Surreal. Muito didático até para mim, brasileiro.
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
Great video!
Please note the middle can overflow. Thus, we prefer to use mid=start+(end-start) / 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
Thank you very much for the video, it helped a lot !!(:
You miss the use of a lot of simple, easy to read builtins
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
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)
Thank you for doing this.
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
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)
Very informative content. It’d be even more awesome if you could explain a little more in depth for beginners
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)
you're brilliant bro. The way you think really helps me understand how to solve these questions
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
im not smart enough for this : ( are these really easy?
18:00 Mistakes are a part of the process.
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 😒
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
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
This is very helpful. more of these please!!
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
destination city : (easier way) lazy way 😛
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))