Basic Calculator II | Leet code 227 | Theory explained + Python code

preview_player
Показать описание
This video is a solution to Leet code 227, Basic Calculator II. I explain the question, go over how the logic / theory behind solving the question and finally solve it using Python code.

Comment below if you have a better solution to this problem!

Let me know if you have any feedback and don't forget to subscribe for more videos!

Time stamps:
0:00 Question Explained
2:46 Solution Explained
10:17 Python Code

Code:

More leetcode questions solved:
Рекомендации по теме
Комментарии
Автор

This is the best explanation on the problem I've seen. After your explanation I was able to code it out on my own. Thank you so much.

symbol
Автор

For 18:30, the reason it wasn't coming out correct was because the question says "The integer division should truncate toward zero." When you perform integer division, you get the floor which would result in rounding -0.333 to -1 when it should round to 0 based on the description. int() however rounds towards 0 which is why it works.

jamesperalta
Автор

Great video! A further optimization would be to eliminate the stack altogether and keep a running sum. Instead of appending to the stack, just add. Instead of popping, just keep track of the most recent value and subtract it off. Then you can save yourself the extra loop to go through and sum all the values. Specifically, it will bring storage complexity from O(n) to O(1) and reduce time by a factor of 2 (though it will still be O(n)).

am_xa
Автор

Thank you Sai Anish. Great video and explanation.

anoops
Автор

this is one of the best coding teaching videos so far, nice voice, cadence, explanation, and visuals

MusicElectra
Автор

Great visualization! It helps build my intuition a lot for this challenge. There're a couple of ways to handle the edge case about the operator == "/", one way we can think of is to take advantage of the built-in function math.floor() and math.ceil(). Cheers!

n.h.son
Автор

Thanks for the nice explanation! Your videos are very helpful.
Integer division for negative number is the issue for stack[-1] //= curr_num. For example -3//4 returns -1 in python but 3//4 returns 0.
Following approach seems also to be working.
if stack[-1] >=0 :
stack[-1] //= curr_num
else:
stack[-1] = -(-stack[-1]//curr_num)

LARamones
Автор

if you're indian then your accent is realy too good

grovestreet
Автор

Thanks a lot! It's really helpful.

sakshiramsinghani
Автор

Bc int div round towards zero. So it gets weird when rounding neg num

shrimpo
Автор

thanks
i want to share this code
class Solution:
def myPow(self, x: float, n: int) -> float:
if n==0:
return 1
elif n<0:
return self.myPow(1/x, -n)
else:
temp=self.myPow(x, n//2)
if n%2==0:
return temp*temp
else:
return x*temp*temp

aminesfahani
Автор

you just stole the answer from the discussion you clearly do not understand the code

diegogarcia-plbt