post_href
stringlengths 57
213
| python_solutions
stringlengths 71
22.3k
| slug
stringlengths 3
77
| post_title
stringlengths 1
100
| user
stringlengths 3
29
| upvotes
int64 -20
1.2k
| views
int64 0
60.9k
| problem_title
stringlengths 3
77
| number
int64 1
2.48k
| acceptance
float64 0.14
0.91
| difficulty
stringclasses 3
values | __index_level_0__
int64 0
34k
|
---|---|---|---|---|---|---|---|---|---|---|---|
https://leetcode.com/problems/count-complete-tree-nodes/discuss/2816303/A-solution-where-time-complexity-log(N)*log(N)-is-clearly-visible-non-recursive | class Solution:
def countNodes(self, root: Optional[TreeNode]) -> int:
def getDepth(root: TreeNode) -> int:
cur = root
depth = 0
while cur is not None:
depth += 1
cur = cur.left
return depth
def walkTree(root: TreeNode, path: int, depth: int) -> TreeNode:
cur = root
while depth > 1:
if (path >> (depth-2)) & 1:
cur = cur.right
else:
cur = cur.left
depth -= 1
return cur
if root is None:
return 0
depth = getDepth(root)
leftPath = 0
rightPath = (2**(depth-1)) - 1
if walkTree(root, rightPath, depth) is not None:
return (2**depth) - 1
while rightPath > leftPath + 1:
midPath = (leftPath + rightPath) // 2
if walkTree(root, midPath, depth) is None:
rightPath = midPath
else:
leftPath = midPath
return ((2**(depth-1)) - 1) + rightPath | count-complete-tree-nodes | A solution where time complexity log(N)*log(N) is clearly visible, non-recursive | drevil_no1 | 0 | 4 | count complete tree nodes | 222 | 0.598 | Medium | 4,000 |
https://leetcode.com/problems/count-complete-tree-nodes/discuss/2816251/python-oror-A-little-optimization-to-avoid-solving-the-same-problem | class Solution:
def getDepth(self, root):
return 1 + self.getDepth(root.left) if root else 0
def handler(self, root, ld=None):
if not root:
return 0
ld = ld if ld is not None else self.getDepth(root.left)
rd = self.getDepth(root.right)
if ld == rd:
return 2**ld + self.handler(root.right, ld=rd - 1)
else:
return 2**rd + self.handler(root.left, ld=ld - 1)
def countNodes(self, root: Optional[TreeNode]) -> int:
return self.handler(root) | count-complete-tree-nodes | python || A little optimization to avoid solving the same problem | Aaron1991 | 0 | 1 | count complete tree nodes | 222 | 0.598 | Medium | 4,001 |
https://leetcode.com/problems/count-complete-tree-nodes/discuss/2816251/python-oror-A-little-optimization-to-avoid-solving-the-same-problem | class Solution:
def getDepth(self, root, r=False):
if not root:
return 0
if r:
return 1 + self.getDepth(root.right, r)
return 1 + self.getDepth(root.left)
def handler(self, root, ld=None, rd=None):
if not root:
return 0
ld = ld if ld is not None else self.getDepth(root)
rd = rd if rd is not None else self.getDepth(root, True)
if ld == rd:
return 2**ld - 1
return (
1 + self.handler(root.left, ld=ld - 1) + self.handler(root.right, rd=rd - 1)
)
def countNodes(self, root: Optional[TreeNode]) -> int:
return self.handler(root) | count-complete-tree-nodes | python || A little optimization to avoid solving the same problem | Aaron1991 | 0 | 1 | count complete tree nodes | 222 | 0.598 | Medium | 4,002 |
https://leetcode.com/problems/count-complete-tree-nodes/discuss/2816154/Python-Recursive-DFS-O(n) | class Solution:
def count(self,node):
if node is None: # travelled beyond a leaf
return 0
return 1 + self.count(node.left) + self.count(node.right) # all other cases
def countNodes(self, root: Optional[TreeNode]) -> int:
return self.count(root) | count-complete-tree-nodes | Python - Recursive DFS - O(n) | randyharnarinesingh | 0 | 5 | count complete tree nodes | 222 | 0.598 | Medium | 4,003 |
https://leetcode.com/problems/rectangle-area/discuss/2822409/Fastest-python-solution | class Solution:
def computeArea(self, ax1: int, ay1: int, ax2: int, ay2: int, bx1: int, by1: int, bx2: int, by2: int) -> int:
coxl=max(ax1,bx1)
coxr=min(ax2,bx2)
coyl=max(ay1,by1)
coyr=min(ay2,by2)
dx=coxr-coxl
dy=coyr-coyl
comm=0
if dx>0 and dy>0:
comm=dx*dy
a=abs(ax2-ax1)*abs(ay2-ay1)
b=abs(bx2-bx1)*abs(by2-by1)
area=a+b-comm
return area | rectangle-area | Fastest python solution | shubham_1307 | 9 | 569 | rectangle area | 223 | 0.449 | Medium | 4,004 |
https://leetcode.com/problems/rectangle-area/discuss/2824547/Python3-READABLE-CODE-Explained | class Solution:
def computeArea(self, ax1: int, ay1: int, ax2: int, ay2: int, bx1: int, by1: int, bx2: int, by2: int) -> int:
Sa = (ax2-ax1) * (ay2-ay1)
Sb = (bx2-bx1) * (by2-by1)
S = Sa + Sb
w_ov = min(ax2, bx2) - max(ax1, bx1)
if w_ov <= 0:
return S
h_ov = min(ay2, by2) - max(ay1, by1)
if h_ov <= 0:
return S
S_ov = w_ov * h_ov
return S - S_ov | rectangle-area | βοΈ [Python3] READABLE CODE, Explained | artod | 5 | 87 | rectangle area | 223 | 0.449 | Medium | 4,005 |
https://leetcode.com/problems/rectangle-area/discuss/2822660/Python-Professional-Solution-or-Fastest-or-99-Faster | class Solution:
def computeArea(self, ax1: int, ay1: int, ax2: int, ay2: int, bx1: int, by1: int, bx2: int, by2: int) -> int:
# Function to caculate area of rectangle (Length * width)
def area(x1,y1,x2,y2):
return (x2-x1)*(y2-y1)
# Finding the overlap rectangle length and width
overlapX = max(min(ax2,bx2)-max(ax1,bx1), 0)
overlapY = max(min(ay2,by2)-max(ay1,by1), 0)
# Area1 + Area2 - Overlap Rectangle Area
return area(ax1,ay1,ax2,ay2) + area(bx1,by1,bx2,by2) - overlapX * overlapY | rectangle-area | βοΈ Python Professional Solution | Fastest | 99% Faster π₯ | pniraj657 | 3 | 152 | rectangle area | 223 | 0.449 | Medium | 4,006 |
https://leetcode.com/problems/rectangle-area/discuss/2686395/Simple-Python-Solution-O(1) | class Solution:
def computeArea(self, ax1: int, ay1: int, ax2: int, ay2: int, bx1: int, by1: int, bx2: int, by2: int) -> int:
a_area = abs(ax1 - ax2) * abs(ay1 - ay2)
b_area = abs(bx1 - bx2) * abs(by1 - by2)
if (bx1 < ax2 and ax1 < bx2) and (by1 < ay2 and ay1 < by2): # Intersection
rx1 = max(ax1, bx1)
rx2 = min(ax2, bx2)
ry1 = max(ay1, by1)
ry2 = min(ay2, by2)
return a_area + b_area - abs(rx1 - rx2) * abs(ry1 - ry2)
return a_area + b_area # No Intersection | rectangle-area | Simple Python Solution O(1) β
| samirpaul1 | 2 | 276 | rectangle area | 223 | 0.449 | Medium | 4,007 |
https://leetcode.com/problems/rectangle-area/discuss/2825417/Python-oror-Easy-oror-95.39-Faster-oror-O(1)-Complexity | class Solution:
def computeArea(self, ax1: int, ay1: int, ax2: int, ay2: int, bx1: int, by1: int, bx2: int, by2: int) -> int:
a1=(ax2-ax1)*(ay2-ay1)
a2=(bx2-bx1)*(by2-by1)
x1=max(ax1,bx1)
x2=min(ax2,bx2)
y1=max(ay1,by1)
y2=min(ay2,by2)
if x2-x1<0 or y2-y1<0: #No intersection will occur if one of the side is negative
return a1+a2
a3=(x2-x1)*(y2-y1)
return a1+a2-a3 | rectangle-area | Python || Easy || 95.39% Faster || O(1) Complexity | DareDevil_007 | 1 | 9 | rectangle area | 223 | 0.449 | Medium | 4,008 |
https://leetcode.com/problems/rectangle-area/discuss/2822804/Python-(Faster-than-92)-or-O(1)-solution | class Solution:
def computeArea(self, ax1: int, ay1: int, ax2: int, ay2: int, bx1: int, by1: int, bx2: int, by2: int) -> int:
area1 = (ax2 - ax1) * (ay2 - ay1)
area2 = (bx2 - bx1) * (by2 - by1)
xOverlap = max(min(ax2, bx2) - max(ax1, bx1), 0)
yOverlap = max(min(ay2, by2) - max(ay1, by1), 0)
commonArea = xOverlap * yOverlap
totalArea = area1 + area2 - commonArea
return totalArea | rectangle-area | Python (Faster than 92%) | O(1) solution | KevinJM17 | 1 | 38 | rectangle area | 223 | 0.449 | Medium | 4,009 |
https://leetcode.com/problems/rectangle-area/discuss/2822547/Generic-Solution-Thought-process-explained. | class Solution:
def computeArea(self, ax1: int, ay1: int, ax2: int, ay2: int, bx1: int, by1: int, bx2: int, by2: int) -> int:
def sendpotentialcoordinates(a1,a2,b1,b2):
if b1>=a1 and b1<a2:
if b2>=a2:
return (b1,a2) #a case
else:
return (b1,b2) #c case
if b1<a1 and b2>a1:
if b2>=a2:
return (a1,a2) #d case
else:
return (a1,b2) #b case
return (None,None) #All other cases
x1,x2=sendpotentialcoordinates(ax1,ax2,bx1,bx2)
y1,y2=sendpotentialcoordinates(ay1,ay2,by1,by2)
# print(x1,x2,y1,y2)
if x1!=None and y1!=None:
return (abs(ax1-ax2)*abs(ay1-ay2))+(abs(bx1-bx2)*abs(by1-by2))-((abs(x1-x2)*abs(y1-y2)))
else:
return (abs(ax1-ax2)*abs(ay1-ay2))+(abs(bx1-bx2)*abs(by1-by2)) | rectangle-area | Generic Solution - Thought process explained. | yogeshwarb | 1 | 27 | rectangle area | 223 | 0.449 | Medium | 4,010 |
https://leetcode.com/problems/rectangle-area/discuss/2822225/Simplest-Solution-oror-Few-Lines-of-Code | class Solution:
def computeArea(self, ax1: int, ay1: int, ax2: int, ay2: int, bx1: int, by1: int, bx2: int, by2: int) -> int:
area_first = abs(ax1 - ax2) * abs(ay1 - ay2)
area_second = abs(bx1 - bx2) * abs(by1 - by2)
x_distance = (min(ax2, bx2) -max(ax1, bx1))
y_distance = (min(ay2, by2) -max(ay1, by1))
Area = 0
if x_distance > 0 and y_distance > 0:
Area = x_distance * y_distance
return (area_first + area_second - Area) | rectangle-area | Simplest Solution || Few Lines of Code | hasan2599 | 1 | 92 | rectangle area | 223 | 0.449 | Medium | 4,011 |
https://leetcode.com/problems/rectangle-area/discuss/2020094/1-Line-Python-Solution-oror-85-Faster-oror-Memory-less-than-99 | class Solution:
def computeArea(self, ax1: int, ay1: int, ax2: int, ay2: int, bx1: int, by1: int, bx2: int, by2: int) -> int:
return (ax2-ax1)*(ay2-ay1) + (bx2-bx1)*(by2-by1) - max(min(ax2,bx2)-max(ax1,bx1),0)*max(min(ay2,by2)-max(ay1,by1),0) | rectangle-area | 1-Line Python Solution || 85% Faster || Memory less than 99% | Taha-C | 1 | 126 | rectangle area | 223 | 0.449 | Medium | 4,012 |
https://leetcode.com/problems/rectangle-area/discuss/2830471/Total-area-of-two-rectangles-that-may-overlap | class Solution:
def computeArea(self, ax1: int, ay1: int, ax2: int, ay2: int, bx1: int, by1: int, bx2: int, by2: int) -> int:
pa = abs(ay2 - ay1) * abs(ax2 - ax1)
pb = abs(by2 - by1) * abs(bx2 - bx1)
dx = min(ax2, bx2) - max(ax1, bx1)
dy = min(ay2, by2) - max(ay1, by1)
if dx > 0 and dy > 0:
return (pa + pb) - (dx * dy)
return pa + pb | rectangle-area | Total area of two rectangles that may overlap | Milantex | 0 | 4 | rectangle area | 223 | 0.449 | Medium | 4,013 |
https://leetcode.com/problems/rectangle-area/discuss/2826847/Python3-solution-using-set-and-math-(it's-not-fast-but-a-different-aspect) | class Solution:
def computeArea(self, ax1: int, ay1: int, ax2: int, ay2: int, bx1: int, by1: int, bx2: int, by2: int) -> int:
a_points = {(i, j) for i in range(ax1, ax2) for j in range(ay1, ay2)}
b_points = {(i, j) for i in range(bx1, bx2) for j in range(by1, by2)}
return len(a_points.union(b_points)) | rectangle-area | Python3 solution using set and math (it's not fast but a different aspect) | karakarasuuuu | 0 | 4 | rectangle area | 223 | 0.449 | Medium | 4,014 |
https://leetcode.com/problems/rectangle-area/discuss/2826562/Very-simple-detailed-explanation-easy-to-understand-python-solution! | class Solution:
def computeArea(self, ax1: int, ay1: int, ax2: int, ay2: int, bx1: int, by1: int, bx2: int, by2: int) -> int:
area1 = (ax2 - ax1) * (ay2 - ay1)
area2 = (bx2 - bx1) * (by2 - by1)
overlapWidth = (min(ax2, bx2) - max(ax1, bx1))
overlapHeight = (min(ay2, by2) - max(ay1, by1))
return (area1 + area2 - (max(overlapHeight,0) * max(overlapWidth, 0))) | rectangle-area | Very simple, detailed explanation, easy to understand, python solution! | dkashi | 0 | 2 | rectangle area | 223 | 0.449 | Medium | 4,015 |
https://leetcode.com/problems/rectangle-area/discuss/2825256/python3-only-1-if-statement | class Solution:
def computeArea(self, ax1: int, ay1: int, ax2: int, ay2: int, bx1: int, by1: int, bx2: int, by2: int) -> int:
# Compute width and height of both rectangles
w1 = ax2-ax1
h1 = ay2-ay1
w2 = bx2-bx1
h2 = by2-by1
# Compute the most restrictive (x1,y1) bottom right and (x2,y2) top left point that are in common to both original rectangles, assuming that
# the intersection exists
x1 = max(ax1,bx1)
x2 = min(ax2, bx2)
y1 = max(ay1, by1)
y2 = min(ay2,by2)
# No intersection occurs if at least one of width or height of the intersection rectangle is negative
# This means that the hypotesis that the intersection rectangle exists is invalidated.
if x2 - x1 < 0 or y2-y1 < 0:
return w1*h1 + w2*h2
# Else, the intersection rectangle exists and we must subtract it to avoid double counting its area when summing the two rectangles
return w1*h1 + w2*h2 - (x2-x1)*(y2-y1) | rectangle-area | python3 only 1 if statement | chris1nexus | 0 | 5 | rectangle area | 223 | 0.449 | Medium | 4,016 |
https://leetcode.com/problems/rectangle-area/discuss/2825237/python3-calculate-intersection-area | class Solution:
def computeArea(self, ax1: int, ay1: int, ax2: int, ay2: int, bx1: int, by1: int, bx2: int, by2: int) -> int:
cx2 = min(ax2, bx2)
cy2 = min(ay2, by2)
cx1 = max(ax1, bx1)
cy1 = max(ay1, by1)
a = (ax2 - ax1) * (ay2 - ay1)
b = (bx2 - bx1) * (by2 - by1)
c = max(0, cx2 - cx1) * max(0, cy2 - cy1)
return a + b - c | rectangle-area | python3 calculate intersection area | remigere | 0 | 4 | rectangle area | 223 | 0.449 | Medium | 4,017 |
https://leetcode.com/problems/rectangle-area/discuss/2825229/Python-2-Line-Solution | class Solution:
def computeArea(self, ax1: int, ay1: int, ax2: int, ay2: int, bx1: int, by1: int, bx2: int, by2: int) -> int:
a= max(min(ax2, bx2) - max(ax1, bx1), 0) * max(min(ay2, by2) - max(ay1, by1), 0)
return (ax2 - ax1) * (ay2 - ay1) + (bx2 - bx1) * (by2 - by1) - a | rectangle-area | βοΈ [ Python ] ππ2 Line Solutionβ
β
| sourav638 | 0 | 6 | rectangle area | 223 | 0.449 | Medium | 4,018 |
https://leetcode.com/problems/rectangle-area/discuss/2825221/PythonCommentedSimple | class Solution:
def computeArea(self, ax1: int, ay1: int, ax2: int, ay2: int, bx1: int, by1: int, bx2: int, by2: int) -> int:
area_rect1 = (ax2 - ax1) * (ay2 - ay1)
area_rect2 = (bx2 - bx1) * (by2 - by1)
# Identify common area
# Widths are not overlapping ?
if ax2 < bx1 or ax1 > bx2:
return area_rect1 + area_rect2
# Heights are not overlapping ?
if ay2 < by1 or ay1 > by2:
return area_rect1 + area_rect2
# Compute overlaps
# Width overlap
width_overlap = min(ax2, bx2) - max(ax1, bx1)
# Height overlap
height_overlap = min(ay2, by2) - max(ay1, by1)
return area_rect1 + area_rect2 - (width_overlap * height_overlap) | rectangle-area | [Python][Commented][Simple] | rapidsmart | 0 | 3 | rectangle area | 223 | 0.449 | Medium | 4,019 |
https://leetcode.com/problems/rectangle-area/discuss/2825163/Simplest-Solution-The-Best | class Solution:
def computeArea(self, ax1: int, ay1: int, ax2: int, ay2: int, bx1: int, by1: int, bx2: int, by2: int) -> int:
a = (ax2 - ax1) * (ay2 - ay1)
b = (bx2 - bx1) * (by2 - by1)
cx = self.intersection(ax1, ax2, bx1, bx2)
cy = self.intersection(ay1, ay2, by1, by2)
return a + b - (cx * cy)
def intersection(self, a1, a2, b1, b2):
if b1 < a1:
a1, a2, b1, b2 = b1, b2, a1, a2
return min(a2, b2) - min(a2, b1) | rectangle-area | Simplest Solution, The Best | Triquetra | 0 | 4 | rectangle area | 223 | 0.449 | Medium | 4,020 |
https://leetcode.com/problems/rectangle-area/discuss/2825152/Asking-for-union | class Solution:
def computeArea(self, ax1: int, ay1: int, ax2: int, ay2: int, bx1: int, by1: int, bx2: int, by2: int) -> int:
area_a = self.area(ax1, ay1, ax2, ay2)
area_b = self.area(bx1, by1, bx2, by2)
x1 = max(ax1, bx1)
y1 = max(ay1, by1)
x2 = min(ax2, bx2)
y2 = min(ay2, by2)
print(inter, area_a , area_b)
union = area_a + area_b - inter
return union
def area(self, x1, y1, x2, y2):
if y2<=y1 or x2<= x1:
return 0 #, ' can not have negtive rectangle'
area = (y2-y1)*(x2-x1)
return area | rectangle-area | Asking for union | gurkirt | 0 | 2 | rectangle area | 223 | 0.449 | Medium | 4,021 |
https://leetcode.com/problems/rectangle-area/discuss/2825071/The-easiest-python3-solution-you-will-find.-O(n) | class Solution:
def computeArea(self, ax1: int, ay1: int, ax2: int, ay2: int, bx1: int, by1: int, bx2: int, by2: int) -> int:
a2 = (bx2 - bx1) * (by2 - by1) #area of second rectangle
a1 = (ax2 - ax1) * (ay2 - ay1) #area of first rectangle
x1 = max(ax1, bx1) # (x1,y1) and (x2,y2) are topright and bottomleft corners of overlapped rectangle
y1 = max(ay1, by1)
x2 = min(ax2, bx2)
y2 = min(ay2, by2)
a3 = max((x2 - x1), 0) * max((y2-y1), 0) #area of overlapped rectangle
return a1 + a2 - a3 #returning the resulting area. | rectangle-area | The easiest python3 solution you will find. O(n) | eleetcoderrakesh | 0 | 2 | rectangle area | 223 | 0.449 | Medium | 4,022 |
https://leetcode.com/problems/rectangle-area/discuss/2824790/Sum-of-areas-minus-intersection | class Solution:
def computeArea(self, ax1: int, ay1: int, ax2: int, ay2: int, bx1: int, by1: int, bx2: int, by2: int) -> int:
sa, sb, s_in = (ax2 - ax1)*(ay2 - ay1), (bx2 - bx1)*(by2 - by1), 0
if min(ax2, bx2) - max(ax1, bx1) > 0 and min(ay2, by2) - max(ay1, by1) > 0:
s_in = (min(ax2, bx2) - max(ax1, bx1))*(min(ay2, by2) - max(ay1, by1))
return sa + sb - s_in | rectangle-area | Sum of areas minus intersection | nonchalant-enthusiast | 0 | 2 | rectangle area | 223 | 0.449 | Medium | 4,023 |
https://leetcode.com/problems/rectangle-area/discuss/2824789/Python3-oror-O(1)-oror-Faster-than-96.18 | class Solution:
def computeArea(self, ax1: int, ay1: int, ax2: int, ay2: int, bx1: int, by1: int, bx2: int, by2: int) -> int:
aa = abs((ax1-ax2)*(ay1-ay2))
ab = abs((bx1-bx2)*(by1-by2))
if (ax1 <= bx1 <= ax2 or ax1 <= bx2 <= ax2 or bx1 <= ax1 <= bx2 or bx1 <= ax2 <= bx2) and (ay1 <= by1 <= ay2 or ay1 <= by2 <= ay2 or by1 <= ay1 <= by2 or by1 <= ay2 <= by2):
x1 = max(ax1, bx1)
x2 = min(ax2, bx2)
y1 = max(ay1, by1)
y2 = min(ay2, by2)
return aa+ab-abs((x1-x2)*(y1-y2))
return aa+ab | rectangle-area | β
Python3 || O(1) || Faster than 96.18% | PabloVE2001 | 0 | 10 | rectangle area | 223 | 0.449 | Medium | 4,024 |
https://leetcode.com/problems/rectangle-area/discuss/2824695/Best-Approch-or-Simple-Solution | class Solution:
def computeArea(self, ax1: int, ay1: int, ax2: int, ay2: int, bx1: int, by1: int, bx2: int, by2: int) -> int:
areaR1=(ax2-ax1)*(ay2-ay1)
areaR2=(bx2-bx1)*(by2-by1)
commonX1=max(ax1,bx1) #for common region both coodinates (X1,Y1) and (X2,Y2)
commonY1=max(ay1,by1)
commonX2=min(ax2,bx2)
commonY2=min(ay2,by2)
common_Rec_length=commonX2-commonX1
common_Rec_height=commonY2-commonY1
common_area= (common_Rec_length * common_Rec_height)
if common_Rec_length>0 and common_Rec_height>0:
return areaR1+areaR2-common_area
else:
return areaR1+areaR2 | rectangle-area | Best Approch | Simple Solution π―β
β
| adarshg04 | 0 | 4 | rectangle area | 223 | 0.449 | Medium | 4,025 |
https://leetcode.com/problems/rectangle-area/discuss/2824652/Easiest-Python-Solution-or-Beats-92.48 | class Solution:
def computeArea(self, ax1: int, ay1: int, ax2: int, ay2: int, bx1: int, by1: int, bx2: int, by2: int) -> int:
area_a = abs(ay1 - ay2) * abs(ax1 - ax2)
area_b = abs(by1 - by2) * abs(bx1 - bx2)
cx1 = max(ax1, bx1)
cy1 = max(ay1, by1)
cx2 = min(ax2, bx2)
cy2 = min(ay2, by2)
area_c = max((cy2 - cy1), 0) * max((cx2 - cx1), 0)
return area_a + area_b - area_c | rectangle-area | Easiest Python Solution | Beats 92.48% | sachinsingh31 | 0 | 10 | rectangle area | 223 | 0.449 | Medium | 4,026 |
https://leetcode.com/problems/rectangle-area/discuss/2824539/Python-Simple-Python-Solution-Using-Math-or-99-Faster | class Solution:
def computeArea(self, ax1: int, ay1: int, ax2: int, ay2: int, bx1: int, by1: int, bx2: int, by2: int) -> int:
overlap_area = 0
area1 = (ax2 - ax1) * (ay2 - ay1)
area2 = (by2 - by1) * (bx2 - bx1)
ax3 = max(ax1, bx1)
ax4 = min(ax2, bx2)
x_overlap = ax4 - ax3
bx3 = max(ay1, by1)
bx4 = min(ay2, by2)
y_overlap = bx4 - bx3
if x_overlap > 0 and y_overlap > 0:
overlap_area = x_overlap * y_overlap
total_area = area1 + area2 - overlap_area
return total_area | rectangle-area | [ Python ] β
β
Simple Python Solution Using Math | 99% Fasterπ₯³βπ | ASHOK_KUMAR_MEGHVANSHI | 0 | 15 | rectangle area | 223 | 0.449 | Medium | 4,027 |
https://leetcode.com/problems/rectangle-area/discuss/2824501/Runtime-58-ms-Beats-89.89-Memory-13.9-MB-Beats-98.15 | class Solution:
def computeArea(self, ax1: int, ay1: int, ax2: int, ay2: int, bx1: int, by1: int, bx2: int, by2: int) -> int:
x_disctance = max(min(ax2-bx1,ax2-ax1,bx2-bx1,bx2-ax1),0)
y_disctance = max(min(ay2-by1,ay2-ay1,by2-by1,by2-ay1),0)
return (ax2-ax1)*(ay2-ay1)+(bx2-bx1)*(by2-by1)-(y_disctance * x_disctance) | rectangle-area | Runtime 58 ms Beats 89.89% Memory 13.9 MB Beats 98.15% | dikketrien | 0 | 6 | rectangle area | 223 | 0.449 | Medium | 4,028 |
https://leetcode.com/problems/rectangle-area/discuss/2824406/Python3-Easy-to-understand-Solution-(Rectangle-Area) | class Solution:
def computeArea(self, ax1: int, ay1: int, ax2: int, ay2: int, bx1: int, by1: int, bx2: int, by2: int) -> int:
rect1=abs((ax1)-(ax2))*abs((ay1)-(ay2))#Area of 1st Rectangle
rect2=abs((bx1)-(bx2))*abs((by1)-(by2))#Area of 2nd Rectangle
l=min(ay2,by2)-max(ay1,by1) #Length of Rectangle formed by intersection
b=min(ax2,bx2)-max(ax1,bx1) #Length of Rectangle formed by intersection
inter=0 #Area of rectangle formed by intersection
if l>0 and b>0:
inter=l*b
return(rect1+rect2-inter) #Final overlapped area by 2 Rectangles | rectangle-area | Python3 Easy to understand Solution (Rectangle Area) | CypherBot-XT | 0 | 5 | rectangle area | 223 | 0.449 | Medium | 4,029 |
https://leetcode.com/problems/rectangle-area/discuss/2824315/Quick-Math-or-PIE-(Principle-of-Inclusion-Exclusion) | class Solution:
def computeArea(self, ax1: int, ay1: int, ax2: int, ay2: int, bx1: int, by1: int, bx2: int, by2: int) -> int:
def area(A: (int, int), B: (int, int)) -> int:
x1, y1 = A; x2, y2 = B
return (x2 - x1) * (y2 - y1)
# find intersection
x1 = max(ax1, bx1); y1 = max(ay1, by1)
x2 = min(ax2, bx2); y2 = min(ay2, by2)
if x2 <= x1 or y2 <= y1:
x1 = x2 # area of intersection is 0
return area((ax1, ay1), (ax2, ay2)) + area((bx1, by1), (bx2, by2)) - area((x1, y1), (x2, y2)) | rectangle-area | Quick Math | PIE (Principle of Inclusion-Exclusion) | sr_vrd | 0 | 11 | rectangle area | 223 | 0.449 | Medium | 4,030 |
https://leetcode.com/problems/rectangle-area/discuss/2824170/rectangle-area | class Solution:
def computeArea(self, ax1: int, ay1: int, ax2: int, ay2: int, bx1: int, by1: int, bx2: int, by2: int) -> int:
r1area=(ax2-ax1)*(ay2-ay1)
r2area=(bx2-bx1)*(by2-by1)
cx1=max(ax1,bx1)
cy1=max(ay1,by1)
cx2=min(ax2,bx2)
cy2=min(ay2,by2)
r3cmnarea=0
c1=(cx2-cx1)
c2=(cy2-cy1)
if c1>0 and c2>0:
r3cmnarea=c1*c2
return (r1area+r2area)-r3cmnarea | rectangle-area | rectangle-area | shivansh2001sri | 0 | 7 | rectangle area | 223 | 0.449 | Medium | 4,031 |
https://leetcode.com/problems/rectangle-area/discuss/2823988/PYTHON-ONE-LINER-O(1)-SOLUTION | class Solution:
def computeArea(self, ax1: int, ay1: int, ax2: int, ay2: int, bx1: int, by1: int, bx2: int, by2: int) -> int:
return (ax2-ax1)*(ay2-ay1) + (bx2-bx1)*(by2-by1) - max(min(ax2,bx2)-max(ax1,bx1), 0) * max(min(ay2,by2)-max(ay1,by1), 0) | rectangle-area | PYTHON ONE LINER O(1) SOLUTION | jagdtri2003 | 0 | 12 | rectangle area | 223 | 0.449 | Medium | 4,032 |
https://leetcode.com/problems/rectangle-area/discuss/2823940/Python-O(1)-solution-Accepted | class Solution:
def computeArea(self, ax1: int, ay1: int, ax2: int, ay2: int, bx1: int, by1: int, bx2: int, by2: int) -> int:
def get_area(x1: int, x2: int, y1: int, y2: int) -> int:
return (x2 - x1) * (y2 - y1)
def get_overlap(a1: int, a2: int, b1: int, b2: int) -> int:
res = min(a2, b2) - max(a1, b1)
return res if res > 0 else 0
a_area = get_area(ax1, ax2, ay1, ay2)
b_area = get_area(bx1, bx2, by1, by2)
x_overlap = get_overlap(ax1, ax2, bx1, bx2)
y_overlap = get_overlap(ay1, ay2, by1, by2)
return a_area + b_area - x_overlap * y_overlap | rectangle-area | Python O(1) solution [Accepted] | lllchak | 0 | 4 | rectangle area | 223 | 0.449 | Medium | 4,033 |
https://leetcode.com/problems/rectangle-area/discuss/2823937/Python-3-Solution-Beats-93.59 | class Solution:
def computeArea(self, ax1: int, ay1: int, ax2: int, ay2: int, bx1: int, by1: int, bx2: int, by2: int) -> int:
# Area for rectangle A:
length_a = ax2 - ax1
height_a = ay2 - ay1
area_a = length_a * height_a
# Area for rectange B:
length_b = bx2 - bx1
height_b = by2 - by1
area_b = length_b * height_b
# Area of overlap:
ax_range = range(ax1, ax2)
ay_range = range(ay1, ay2)
bx_range = range(bx1, bx2)
by_range = range(by1, by2)
if len(ax_range) == 0 or len(ay_range) == 0 or len(bx_range) == 0 or len(by_range) == 0:
overlap_area = 0
else:
x_overlap = range(max(ax_range[0], bx_range[0]), min(ax_range[-1], bx_range[-1])+1)
y_overlap = range(max(ay_range[0], by_range[0]), min(ay_range[-1], by_range[-1])+1)
x_overlap_len = len(x_overlap)
y_overlap_len = len(y_overlap)
overlap_area = x_overlap_len * y_overlap_len
# Total Area Covered:
total_area = area_a + area_b - overlap_area
return total_area | rectangle-area | Python 3 Solution; Beats 93.59% | WillDearden98 | 0 | 6 | rectangle area | 223 | 0.449 | Medium | 4,034 |
https://leetcode.com/problems/rectangle-area/discuss/2823910/Python3-solution | class Solution:
def computeArea(self, ax1: int, ay1: int, ax2: int, ay2: int, bx1: int, by1: int, bx2: int, by2: int) -> int:
area_1 = (ax2 - ax1) * (ay2 - ay1) # [1] area of the first rectangle
area_2 = (bx2 - bx1) * (by2 - by1) # [2] area of the second rectangle
x_over = max(min(ax2,bx2) - max(ax1,bx1),0) # [3] overlap of sides along x-axis
y_over = max(min(ay2,by2) - max(ay1,by1),0) # [4] overlap of sides along y-axis
area_0 = x_over * y_over # [5] area of the overlap region
return area_1 + area_2 - area_0 | rectangle-area | Python3 solution | avs-abhishek123 | 0 | 4 | rectangle area | 223 | 0.449 | Medium | 4,035 |
https://leetcode.com/problems/rectangle-area/discuss/2823890/Python-one-liner-with-explanation! | class Solution:
def computeArea(self, ax1: int, ay1: int, ax2: int, ay2: int, bx1: int, by1: int, bx2: int, by2: int) -> int:
return ((ax2-ax1)*(ay2-ay1)) + ((bx2-bx1)*(by2-by1)) - max(0, min(ax2, bx2) - max(ax1, bx1)) * max(0, min(ay2, by2) - max(ay1, by1)) | rectangle-area | Python one-liner with explanation! π» | sumNeatLeeter | 0 | 8 | rectangle area | 223 | 0.449 | Medium | 4,036 |
https://leetcode.com/problems/rectangle-area/discuss/2823844/Python-set-easy-solution | class Solution:
def computeArea(self, ax1: int, ay1: int, ax2: int, ay2: int, bx1: int, by1: int, bx2: int, by2: int) -> int:
# x and y is the cordinate of intersection area
# using & operation to get the intersection cordinate
x = set(range(ax1, ax2)) & set(range(bx1, bx2))
y = set(range(ay1, ay2)) & set(range(by1, by2))
# set A + set B - intersection area
return len(range(ax1, ax2)) * len(range(ay1, ay2)) + len(range(bx1, bx2)) * len(range(by1, by2)) - len(x) * len(y) | rectangle-area | Python set easy solution | victornanka | 0 | 6 | rectangle area | 223 | 0.449 | Medium | 4,037 |
https://leetcode.com/problems/rectangle-area/discuss/2823716/Python-Simple-Solution | class Solution:
def computeArea(self, ax1: int, ay1: int, ax2: int, ay2: int, bx1: int, by1: int, bx2: int, by2: int) -> int:
area1 = abs((ax1-ax2)*(ay1-ay2))
area2 = abs((bx1-bx2)*(by1-by2))
if ay1 >= by2 or by1 >= ay2 or ax1 >= bx2 or bx1 >= ax2:
return (area1+area2)
area3 = abs((max(ax1,bx1)-min(ax2,bx2))*(max(ay1,by1)-min(ay2,by2)))
return (area1+area2-area3) | rectangle-area | Python Simple Solution | saivamshi0103 | 0 | 6 | rectangle area | 223 | 0.449 | Medium | 4,038 |
https://leetcode.com/problems/rectangle-area/discuss/2823657/Python3-Clean-and-Readable-Solution | class Solution:
def computeArea(self, ax1: int, ay1: int, ax2: int, ay2: int, bx1: int, by1: int, bx2: int, by2: int) -> int:
# check whether rectangles overlap by check if they overlap in each dimensions
#
# Lines of a: ax1 - ax2, ay1-ay2
# Lines of b: bx1 - bx2, by1-by2
overlap_x = (bx1 <= ax1 <= bx2) or (ax1 <= bx1 <= ax2)
overlap_y = (by1 <= ay1 <= by2) or (ay1 <= by1 <= ay2)
# calculate area if they overlap
overlap_area = 0
if overlap_x and overlap_y:
# get the coordinates of the overlap
ox1 = max(ax1, bx1)
ox2 = min(ax2, bx2)
oy1 = max(ay1, by1)
oy2 = min(ay2, by2)
# calculate the area
overlap_area = Solution.rectangle_area(ox1, ox2, oy1, oy2)
# calculate area of both rectangles
area_a = Solution.rectangle_area(ax1, ax2, ay1, ay2)
area_b = Solution.rectangle_area(bx1, bx2, by1, by2)
# return the area minus the overlap
return area_a + area_b - overlap_area
@staticmethod
def rectangle_area(x1, x2, y1, y2):
return (x2-x1)*(y2-y1) | rectangle-area | [Python3] - Clean and Readable Solution | Lucew | 0 | 3 | rectangle area | 223 | 0.449 | Medium | 4,039 |
https://leetcode.com/problems/rectangle-area/discuss/2823638/Brute-forceNaive-python-solution-or-Geometry | class Solution:
def computeArea(self, ax1: int, ay1: int, ax2: int, ay2: int, bx1: int, by1: int, bx2: int, by2: int) -> int:
#24 + 27 - 6
width1, height1 = abs(ax2 - ax1), abs(ay2 - ay1)
width2, height2 = abs(bx2 - bx1), abs(by2 - by1)
startx, starty = 0, 0
endx, endy = 0, 0
if ax1 <= bx1 <= ax2:
startx = bx1
elif bx1 <= ax1 <= bx2:
startx = ax1
if ax1 <= bx2 <= ax2:
endx = bx2
elif bx1 <= ax2 <= bx2:
endx = ax2
if ay1 <= by1 <= ay2:
starty = by1
elif by1 <= ay1 <= by2:
starty = ay1
if ay1 <= by2 <= ay2:
endy = by2
elif by1 <= ay2 <= by2:
endy = ay2
total_area = (width1 * height1) + (width2 * height2)
width_rem, height_rem = abs(startx - endx), abs(starty - endy)
return total_area - (width_rem * height_rem) | rectangle-area | Brute-force/NaΓ―ve python solution | Geometry | Inceptionjps | 0 | 3 | rectangle area | 223 | 0.449 | Medium | 4,040 |
https://leetcode.com/problems/rectangle-area/discuss/2823506/Python.-Easy-to-understand | class Solution:
def computeArea(self, ax1: int, ay1: int, ax2: int, ay2: int, bx1: int, by1: int, bx2: int, by2: int) -> int:
area = (ay2-ay1) * (ax2-ax1) + (bx2-bx1) * (by2-by1)
if ax1 >= bx2 or ay1 >= by2 or bx1 >= ax2 or by1>=ay2:
return area
else:
cx1 = max(ax1,bx1)
cy1 = max(ay1,by1)
cx2 = min(ax2,bx2)
cy2 = min(ay2,by2)
return area - (cx2-cx1)*(cy2-cy1) | rectangle-area | Python. Easy to understand | yOlsen | 0 | 2 | rectangle area | 223 | 0.449 | Medium | 4,041 |
https://leetcode.com/problems/rectangle-area/discuss/2823445/oror-Python-oror-O(1)-oror | class Solution:
def computeArea(self, ax1: int, ay1: int, ax2: int, ay2: int, bx1: int, by1: int, bx2: int, by2: int) -> int:
area_a = (ay2 - ay1) * (ax2 - ax1)
area_b = (by2 - by1) * (bx2- bx1)
ans = area_a + area_b
# X overlap
x_overlap = min(ax2, bx2) - max(bx1, ax1)
# Y overlap
y_overlap = min(ay2, by2) - max(ay1, by1)
if x_overlap > 0 and y_overlap > 0:
ans -= (x_overlap * y_overlap)
return ans | rectangle-area | π― || Python || O(1) || π― | parth_panchal_10 | 0 | 1 | rectangle area | 223 | 0.449 | Medium | 4,042 |
https://leetcode.com/problems/rectangle-area/discuss/2823437/Python-O(1) | class Solution:
def computeArea(self, ax1: int, ay1: int, ax2: int, ay2: int, bx1: int, by1: int, bx2: int, by2: int) -> int:
ix2 = min(ax2, bx2)
ix1 = max(bx1, ax1)
iy2 = min(ay2, by2)
iy1 = max(ay1, by1)
intersection_area = 0
if (ix2 - ix1) > 0 and (iy2 - iy1) > 0:
intersection_area = (ix2 - ix1) * (iy2 - iy1)
area1 = (ax2 - ax1) * (ay2 - ay1)
area2 = (bx2 - bx1) * (by2 - by1)
return area1 + area2 - intersection_area | rectangle-area | Python O(1) | chingisoinar | 0 | 3 | rectangle area | 223 | 0.449 | Medium | 4,043 |
https://leetcode.com/problems/rectangle-area/discuss/2823422/Python-easy | class Solution:
def computeArea(self, ax1: int, ay1: int, ax2: int, ay2: int, bx1: int, by1: int, bx2: int, by2: int) -> int:
l = min(bx2, ax2) - max(bx1, ax1) if (bx2 > ax1) & (bx1 < ax2) else 0
h = min(by2, ay2) - max(by1, ay1) if (ay1 < by2) & (ay2 > by1) else 0
s = (by2 - by1)*(bx2 - bx1) + (ay2 - ay1)*(ax2 - ax1)
s -= l*h
return s | rectangle-area | Python easy | rudyivt | 0 | 3 | rectangle area | 223 | 0.449 | Medium | 4,044 |
https://leetcode.com/problems/rectangle-area/discuss/2823391/EZ-to-understand-solution | class Solution:
def computeArea(self, ax1: int, ay1: int, ax2: int, ay2: int, bx1: int, by1: int, bx2: int, by2: int) -> int:
# overlapped area
if bx1 <= ax2 <= bx2:
x2 = ax2
if bx1 >= ax1:
x1 = bx1
else:
x1 = ax1
elif ax2 > bx2 > ax1:
x2 = bx2
if bx1 >= ax1:
x1 = bx1
else:
x1 = ax1
else:
x2 = 0
x1 = 0
if ay2 >= by2 >= ay1:
y2 = by2
if ay1 >= by1:
y1 = ay1
else:
y1 = by1
elif by1 <= ay2 <= by2:
y2 = ay2
if ay1 >= by1:
y1 = ay1
else:
y1 = by1
else:
y2 = 0
y1 = 0
x = x2 - x1
y = y2 - y1
res_overlap = x * y
# total area
area_a = (ax2 - ax1) * (ay2 - ay1)
area_b = (bx2 - bx1) * (by2 - by1)
res = abs(area_a + area_b - res_overlap)
return res | rectangle-area | EZ to understand solution | dalinwang | 0 | 1 | rectangle area | 223 | 0.449 | Medium | 4,045 |
https://leetcode.com/problems/rectangle-area/discuss/2823222/PYTHON-or-EASY-1-LINER-or-TM-8878 | class Solution:
def computeArea(self, ax1: int, ay1: int, ax2: int, ay2: int, bx1: int, by1: int, bx2: int, by2: int) -> int:
return ((ax2 - ax1) * (ay2 - ay1)+(bx2 - bx1) * (by2 - by1))-(max((min(ay2, by2) - max(ay1, by1)),0)*max((min(ax2, bx2) - max(ax1, bx1)),0)) | rectangle-area | π PYTHON | EASY 1 LINER | T/M - 88%/78% β | dclerici | 0 | 2 | rectangle area | 223 | 0.449 | Medium | 4,046 |
https://leetcode.com/problems/rectangle-area/discuss/2823154/Fast-and-Easy-Solution | class Solution:
def computeArea(self, ax1: int, ay1: int, ax2: int, ay2: int, bx1: int, by1: int, bx2: int, by2: int) -> int:
area_A = (ay2 - ay1) * (ax2 - ax1)
area_B = (by2 - by1) * (bx2 - bx1)
x_overlapped = max(min(ax2 , bx2) - max(ax1 , bx1) , 0)
y_overlapped = max(min(ay2 , by2) - max(ay1 , by1) , 0)
area_overlapped = x_overlapped * y_overlapped
return area_A + area_B - area_overlapped | rectangle-area | Fast and Easy Solution | user6770yv | 0 | 4 | rectangle area | 223 | 0.449 | Medium | 4,047 |
https://leetcode.com/problems/rectangle-area/discuss/2823093/Python-3-Simple-solution-based-on-Leetcode's-solution | class Solution:
def computeArea(self, ax1: int, ay1: int, ax2: int, ay2: int, bx1: int, by1: int, bx2: int, by2: int) -> int:
area_a = abs((ax1 - ax2) * (ay1 - ay2))
area_b = abs((bx1 - bx2) * (by1 - by2))
x_intersec = min(ax2, bx2) - max(ax1, bx1)
y_intersec = min(ay2, by2) - max(ay1, by1)
if x_intersec > 0 and y_intersec > 0:
return area_a + area_b - x_intersec*y_intersec
else:
return area_a + area_b | rectangle-area | [Python 3] Simple solution based on Leetcode's solution | nguyentangnhathuy | 0 | 6 | rectangle area | 223 | 0.449 | Medium | 4,048 |
https://leetcode.com/problems/rectangle-area/discuss/2823071/Solution-of-sum-of-two-rectangles-subtracing-overlapped-area | class Solution:
def computeArea(self, ax1: int, ay1: int, ax2: int, ay2: int, bx1: int, by1: int, bx2: int, by2: int) -> int:
def area_of_rectangle(x1, y1, x2, y2):
return (x2-x1) * (y2 - y1)
area_A = area_of_rectangle(ax1, ay1, ax2, ay2)
area_B = area_of_rectangle(bx1, by1, bx2, by2)
overlapped_area = max(min(ax2, bx2) - max(ax1, bx1), 0) * \
max(min(ay2, by2) - max(ay1, by1), 0)
return ((area_A + area_B) - overlapped_area) | rectangle-area | Solution of sum of two rectangles subtracing overlapped area | prashantghi8 | 0 | 1 | rectangle area | 223 | 0.449 | Medium | 4,049 |
https://leetcode.com/problems/rectangle-area/discuss/2822983/Python-or-mathematical-solution | class Solution:
def computeArea(self, ax1: int, ay1: int, ax2: int, ay2: int, bx1: int, by1: int, bx2: int, by2: int) -> int:
def find_area(x1, y1, x2, y2):
return abs(x1-x2) * abs(y1-y2)
if ax2 < bx1 or ax1 > bx2 or ay1 > by2 or ay2 < by1:
intersection_area = 0
else:
ix1, ix2 = sorted([ax1, ax2, bx1, bx2])[1:3]
iy1, iy2 = sorted([ay1, ay2, by1, by2])[1:3]
intersection_area = find_area(ix1, iy1, ix2, iy2)
return find_area(ax1, ay1, ax2, ay2) + find_area(bx1, by1, bx2, by2) - intersection_area | rectangle-area | Python | mathematical solution | xyp7x | 0 | 3 | rectangle area | 223 | 0.449 | Medium | 4,050 |
https://leetcode.com/problems/rectangle-area/discuss/2822982/python-one-liner-code-14.1-memory-used-O(1)-SOLUTION | class Solution:
def computeArea(self, ax1: int, ay1: int, ax2: int, ay2: int, bx1: int, by1: int, bx2: int, by2: int) -> int:
return (ax2-ax1)*(ay2-ay1) + (bx2-bx1)*(by2-by1) - max(min(ax2,bx2)-max(ax1,bx1), 0) * max(min(ay2,by2)-max(ay1,by1), 0) | rectangle-area | python one liner code 14.1 memory used O(1) SOLUTION | Aasthagupta7802 | 0 | 3 | rectangle area | 223 | 0.449 | Medium | 4,051 |
https://leetcode.com/problems/rectangle-area/discuss/2822967/or-Python-Easy-Code | class Solution:
def computeArea(self, ax1: int, ay1: int, ax2: int, ay2: int, bx1: int, by1: int, bx2: int, by2: int) -> int:
x_overlap = min(ax2, bx2) - max(ax1, bx1)
y_overlap = min(ay2, by2) - max(ay1, by1)
a_area = (ax2 - ax1) * (ay2 - ay1)
b_area = (bx2 - bx1) * (by2 - by1)
return a_area + b_area - (x_overlap * y_overlap if x_overlap > 0 and y_overlap > 0 else 0) | rectangle-area | βοΈ | Python Easy Code | code_alone | 0 | 3 | rectangle area | 223 | 0.449 | Medium | 4,052 |
https://leetcode.com/problems/rectangle-area/discuss/2822903/python3-easy-solution | class Solution:
def computeArea(self, ax1: int, ay1: int, ax2: int, ay2: int, bx1: int, by1: int, bx2: int, by2: int) -> int:
def get_coordinates(x1,x2,y1,y2):
return {0:[x1,y1],1:[x2,y1],2:[x2,y2],3:[x1,y2]}
first = get_coordinates(ax1,ax2,ay1,ay2)
second = get_coordinates(bx1,bx2,by1,by2)
def left_overlap(a,b):
if b[0][0]>=a[0][0] and b[0][0]<a[1][0] and b[1][0]>=a[1][0]:
return abs(b[0][0]-a[1][0])
if a[0][0]>=b[0][0] and a[0][0]<b[1][0] and a[1][0]>=b[1][0]:
return abs(a[0][0]-b[1][0])
if b[0][0]>=a[0][0] and b[0][0]<a[1][0] and b[1][0]<a[1][0]:
return abs(b[1][0]-b[0][0])
if a[0][0]>=b[0][0] and a[0][0]<b[1][0] and a[1][0]<b[1][0]:
return abs(a[1][0]-a[0][0])
def top_overlap(a,b):
if b[0][1]>=a[0][1] and b[0][1]<a[2][1] and b[2][1]>=a[2][1]:
return abs(b[0][1]-a[2][1])
if a[0][1]>=b[0][1] and a[0][1]<b[2][1] and a[2][1]>=b[2][1]:
return abs(a[0][1]-b[2][1])
if b[0][1]>=a[0][1] and b[0][1]<a[2][1] and b[2][1]<a[2][1]:
return abs(b[2][1]-b[0][1])
if a[0][1]>=b[0][1] and a[0][1]<b[2][1] and a[2][1]<b[2][1]:
return abs(a[2][1]-a[0][1])
l=left_overlap(first,second)
t=top_overlap(first, second)
total_area = (first[1][0]-first[0][0])*(first[2][1]-first[0][1])
total_area+=(second[1][0]-second[0][0])*(second[2][1]-second[0][1])
if l is not None and t is not None:
total_area -=l*t
return total_area | rectangle-area | python3 easy solution | shubham3 | 0 | 2 | rectangle area | 223 | 0.449 | Medium | 4,053 |
https://leetcode.com/problems/basic-calculator/discuss/2832718/Python-(Faster-than-98)-or-O(N)-stack-solution | class Solution:
def calculate(self, s: str) -> int:
output, curr, sign, stack = 0, 0, 1, []
for c in s:
if c.isdigit():
curr = (curr * 10) + int(c)
elif c in '+-':
output += curr * sign
curr = 0
if c == '+':
sign = 1
else:
sign = -1
elif c == '(':
stack.append(output)
stack.append(sign)
sign = 1
output = 0
elif c == ')':
output += curr * sign
output *= stack.pop() #sign
output += stack.pop() #last output
curr = 0
return output + (curr * sign) | basic-calculator | Python (Faster than 98%) | O(N) stack solution | KevinJM17 | 2 | 81 | basic calculator | 224 | 0.423 | Hard | 4,054 |
https://leetcode.com/problems/basic-calculator/discuss/1926465/Python-easy-to-read-and-understand-or-stack | class Solution:
def update(self, sign, num, stack):
if sign == "+":
stack.append(num)
if sign == "-":
stack.append(-num)
return stack
def solve(self, i, s):
stack, num, sign = [], 0, "+"
while i < len(s):
if s[i].isdigit():
num = num * 10 + int(s[i])
elif s[i] == "+" or s[i] == "-":
stack = self.update(sign, num, stack)
num, sign = 0, s[i]
elif s[i] == "(":
num, i = self.solve(i + 1, s)
elif s[i] == ")":
stack = self.update(sign, num, stack)
return sum(stack), i
i += 1
# print(num, sign)
stack = self.update(sign, num, stack)
return sum(stack)
def calculate(self, s: str) -> int:
return self.solve(0, s) | basic-calculator | Python easy to read and understand | stack | sanial2001 | 2 | 353 | basic calculator | 224 | 0.423 | Hard | 4,055 |
https://leetcode.com/problems/basic-calculator/discuss/1150750/Clean-python-solution | class Solution:
def calculate(self, s: str) -> int:
ops = {
'+': lambda x,y: x+y,
'-': lambda x,y: x-y,
}
digits=set('0123456789')
num=0
op = '+'
stack = []
i = 0
while i< len(s):
if s[i] == '(':
stack.append((num, op))
num = 0
op = '+'
elif s[i] == ')':
tmp = stack.pop()
num = ops[tmp[1]](tmp[0], num)
op = '+'
elif s[i] in '+-':
op = s[i]
elif s[i] in digits:
j = i
while j< len(s) and s[j] in digits:
j+=1
num = ops[op](num, int(s[i:j]))
i = j -1
else:
print("what", s[i])
i+=1
return num | basic-calculator | Clean python solution | stanley3 | 2 | 536 | basic calculator | 224 | 0.423 | Hard | 4,056 |
https://leetcode.com/problems/basic-calculator/discuss/749848/Python3-Dijkstra's-two-stack-algo | class Solution:
def calculate(self, s: str) -> int:
#pre-processing to tokenize input
s = s.replace(" ", "") #remote white space
tokens = [] #collect tokens
lo = hi = 0
while hi <= len(s):
if hi == len(s) or s[hi] in "+-()":
if lo < hi: tokens.append(s[lo:hi])
if hi < len(s): tokens.append(s[hi])
lo = hi + 1
hi += 1
#Dijkstra's two-stack algo
opd, opr = [], [] #operand & operator stacks
for token in tokens:
if token in "+-(": opr.append(token)
else:
if token == ")":
opr.pop()
token = opd.pop()
else:
token = int(token)
if opr and opr[-1] != "(":
op = opr.pop()
x = opd.pop()
if op == "+": token = x + token
else: token = x - token
opd.append(token)
return opd[-1] | basic-calculator | [Python3] Dijkstra's two-stack algo | ye15 | 2 | 186 | basic calculator | 224 | 0.423 | Hard | 4,057 |
https://leetcode.com/problems/basic-calculator/discuss/749848/Python3-Dijkstra's-two-stack-algo | class Solution:
def calculate(self, s: str) -> int:
ans, sign, val = 0, 1, 0
stack = []
for c in s:
if c.isdigit():
val = 10*val + int(c)
elif c in "+-":
ans += sign * val
val = 0
sign = 1 if c == "+" else -1
elif c == "(":
stack.append(ans)
stack.append(sign)
ans, sign = 0, 1
elif c == ")":
ans += sign * val
ans *= stack.pop()
ans += stack.pop()
val = 0
return ans + sign * val | basic-calculator | [Python3] Dijkstra's two-stack algo | ye15 | 2 | 186 | basic calculator | 224 | 0.423 | Hard | 4,058 |
https://leetcode.com/problems/basic-calculator/discuss/617973/Easy-understand-or-O(n)-or-Explanation-or-Stack | class Solution:
def calculate(self, s: str) -> int:
# temp_res & res
res = 0
# num's sign
sign = 1
# calculate num
num = 0
stack = []
# 1. digit
# 2. (
# 3. )
# 5. -
# 6. +
# other (no effect)
for i in range(len(s)):
# 1. digit (just for calculation)
if s[i].isdigit():
num = num*10 + int(s[i])
# 2.( push
elif s[i] == '(':
# append current res and current sign
stack.append(res)
# could be stored in other stack, but not necessary
stack.append(sign)
# reset res & sign
res = 0
sign = 1
# 3. ) pop
elif s[i] == ')':
# handle num stored in memory
res += num*sign
# handle num stored in stack
# pop sign first
res *= stack.pop()
# then pop num
res += stack.pop()
# res num
num = 0
# 4. & 5.: + , -
elif s[i] in '-+':
res += num*sign
sign = -1 if s[i]=='-' else 1
# res num
num = 0
# for situation1, we did't add the current res and num stored in memeory, so add it here
res+= num*sign
return res | basic-calculator | π₯Easy-understand | O(n) | Explanation | Stack π₯ | Get-Schwifty | 2 | 661 | basic calculator | 224 | 0.423 | Hard | 4,059 |
https://leetcode.com/problems/basic-calculator/discuss/2834479/Python3-O(n)-Stack-Solution | class Solution:
def calculate(self, s: str) -> int:
val_stack = []
cur_num = 0
total = 0
sign = 1
for c in s:
if c.isdigit():
cur_num*=10
cur_num+=int(c)
elif c=='+':
total+=cur_num*sign
cur_num = 0
sign = 1
elif c=='-':
total+=cur_num*sign
cur_num = 0
sign = -1
elif c=='(':
val_stack.append(total)
val_stack.append(sign)
sign = 1
total = 0
elif c==')':
total += sign * cur_num
cur_num = 0
total *= val_stack.pop()
total += val_stack.pop()
if cur_num: total += sign * cur_num
return total | basic-calculator | Python3 O(n) Stack Solution | keioon | 1 | 20 | basic calculator | 224 | 0.423 | Hard | 4,060 |
https://leetcode.com/problems/basic-calculator/discuss/2421552/Python-or-O(n)-or-Recursive-or-Comments-added | class Solution:
def calculate(self, expression: str) -> int:
#recurse when brackets encountered
def helper(s,index):
result = 0
sign = 1
currnum = 0
i = index
while i<len(s):
c = s[i]
if c.isdigit():
currnum = currnum*10+int(c)
elif c in '-+': #update the sign
result += sign*currnum
sign = 1 if c=='+' else -1
currnum = 0
elif c == '(': #pause and call helper for the next section
res, i = helper(s, i+1)
result += sign*res
elif c == ')': #return results, index to resume to caller
result += sign*currnum
break
i+=1
#return result and current index
return result, i
if not expression:
return 0
#enclose input with brackets and call helper
return helper('('+expression+')', 0)[0] | basic-calculator | Python | O(n) | Recursive | Comments added | eforean | 1 | 194 | basic calculator | 224 | 0.423 | Hard | 4,061 |
https://leetcode.com/problems/basic-calculator/discuss/1457830/Python-recursive-solution | class Solution:
def calculate(self, s: str) -> int:
exp=['('] #wrap the whole expression with brackets to easily mark the end of expression
#Line 5-14=>Changes the input string into a list (easy for evaluation) eg. "1 + 1"=>['(', 1, '+', 1, ')']
for c in s:
if c==' ':
continue
if not c.isdigit():
exp.append(c) #appends operator or bracket
elif isinstance(exp[-1],int):
exp[-1]=exp[-1]*10+int(c) #extending a integer
else:
exp.append(int(c)) #start of integer
exp.append(')')
res,_=self.evaluate(exp,1)# 1 indicates to start from next to the open parenthesis...
return res
def evaluate(self,exp,i):
calc,op=0,'+'
while exp[i]!=')': #evaluate from i onwards to closing parenthesis
ele=exp[i]
if ele=='+' or ele=='-': #if operator encountered then set op to ele
op=ele
else:
if isinstance(ele,int): #if number encountered then set num to ele
num=ele
else:
num,i=self.evaluate(exp,i+1) #if open parenthesis encountered then start recurring until the closing parenthesis for evaluating the expression between them...
if op=='+':
calc+=num
else:
calc-=num
i+=1
return calc,i #return the result of the expression between the open parenthesis and closing parenthesis and the index of closing parenthesis | basic-calculator | Python recursive solution | Umadevi_R | 1 | 262 | basic calculator | 224 | 0.423 | Hard | 4,062 |
https://leetcode.com/problems/basic-calculator/discuss/2834335/Python-multiple-stacks | class Solution:
def calculate(self, s: str) -> int:
stacks = [[1]]
cur_int = '0'
for i,c in enumerate(s):
if ord('0')<=ord(c)<=ord('9'):
cur_int+=c
if not (ord('0')<=ord(c)<=ord('9')) or i==len(s)-1:
if int(cur_int)!=0:
stacks[-1].append(stacks[-1][0]*int(cur_int))
cur_int = '0'
if c =='+':
stacks[-1][0] = 1
elif c=='-':
stacks[-1][0] = -1
elif c=='(':
stacks.append([1])
elif c==')':
innermost = sum(stacks.pop()[1:])
stacks[-1].append(stacks[-1][0]*innermost)
return sum(stacks[0][1:]) | basic-calculator | Python multiple stacks | li87o | 0 | 10 | basic calculator | 224 | 0.423 | Hard | 4,063 |
https://leetcode.com/problems/basic-calculator/discuss/2834136/Python-Solution-easy-to-understand | class Solution:
def calculate(self, s: str) -> int:
# Runtime89 ms
# Beats
# 92.38%
# Memory15.3 MB
# Beats
# 93.82%
result, sign, num, stack = 0, 1, 0, []
s += "+"
for c in s:
if c == " ": continue
if c.isdigit():
num = num*10 + int(c)
if c in "+-": # add num to result
result += num * sign
num = 0
sign = 1 if c == "+" else -1
if c == "(": # add current result, sign to stack
# num is already 0
stack.extend([result, sign])
result = 0
sign = 1
if c == ")":
# add num to result (inside bracket result)
# and prev_result from stack to result
result += num * sign
sign = stack.pop()
prev_result = stack.pop()
result = prev_result + result * sign
num = 0
return result | basic-calculator | Python Solution easy to understand | remenraj | 0 | 7 | basic calculator | 224 | 0.423 | Hard | 4,064 |
https://leetcode.com/problems/basic-calculator/discuss/2833866/Python3-solution | class Solution:
def calculate(self, s: str) -> int:
### num is the current number we are constructing
### sign is the '+' or '-' before the current number we are constructing/holding
### Note that we initialize sign with 1 to represent '+'
### The last element in the stack will be the number we are updating during the
### process, so put a 0 in it.
num, sign, stack = 0, 1, [0]
for c in s:
### Constructing the number.
if c.isdigit():
num = num*10 + int(c)
### Skip the space
elif c==' ':
continue
### When we see '+', we need to multiply the current number we are holding with the
### sign before this number, and update the last element in the stack.
### We also need to reset num to 0 and sign to 1
elif c == '+':
stack[-1] += num * sign
sign = 1
num = 0
### Doing the same thing as '+', but reset sign to -1
elif c == '-':
stack[-1] += num * sign
sign = -1
num = 0
### We add sign to stack which represent the sign of this ()
### We also add a 0 so we can keep update while evaluating the expression inside this ()
### Reset num and sign again
elif c == '(':
stack.extend([sign,0])
sign = 1
num = 0
### pop the last element and combine it with the current num and sign we are holding (the last element inside this '()' ).
### pop the last element again which is the sign for this '()' and muitiply them together.
### add everything we get inside this '()' to the last element in the stack.
elif c == ')':
lastNum = (stack.pop() + num*sign) * stack.pop()
stack[-1] += lastNum
sign = 1
num = 0
### stack should only contain one element representing everything except the last number if the expression ended with a number, so add the current num we are holding to the result.
return stack[-1]+num*sign | basic-calculator | Python3 solution | avs-abhishek123 | 0 | 15 | basic calculator | 224 | 0.423 | Hard | 4,065 |
https://leetcode.com/problems/basic-calculator/discuss/2833697/Simple-solution-by-using-stack | class Solution:
def calculate(self, s: str) -> int:
number = 0
result = 0
sign = 1
stack = []
pos_neg = {'+', '-'}
for a in s:
if a.isdigit():
number = number*10 + int(a)
elif a in pos_neg:
result += number*sign
if a == '+':
sign = 1
else:
sign = -1
number = 0
elif a == '(':
result += number*sign
stack.append(result)
stack.append(sign)
number = 0
result = 0
sign = 1
elif a == ')':
result += number*sign
result = result*stack.pop()
result += stack.pop()
number = 0
sign = 1
return result + number*sign | basic-calculator | Simple solution by using stack | Tonmoy-saha18 | 0 | 11 | basic calculator | 224 | 0.423 | Hard | 4,066 |
https://leetcode.com/problems/basic-calculator/discuss/2833263/Python3 | class Solution:
def calculate(self, s: str) -> int:
# remove space
s = s.split(" ")
while "" in s:
s.remove("")
list_s = "".join(s)
# 4+5+2
def cal(tmp : str) -> str :
s = ''
pro = []
tmp = "".join(tmp)
tmp = tmp.replace('--','+')
tmp = tmp.replace('+-','-')
if tmp[0] == '+' :
tmp = tmp[1::]
for i in tmp:
if i == '-':
if s:
pro.append(s)
pro.append(i)
s = ''
elif i == '+':
pro.append(s)
pro.append(i)
s = ''
else:
s += i
pro.append(s)
i = 0
ans = 0
while i <= len(pro)-1 :
if i <= len(pro)-1 and pro[i] == '+' :
i += 1
ans += int(pro[i])
i += 1
elif i <= len(pro)-1 and pro[i] == '-':
i += 1
ans -= int(pro[i])
i += 1
else :
ans += int(pro[i])
i += 1
return str(ans)
stack = []
tmp = ''
for i in list_s:
if i != ')' :
stack.append(i)
else :
while stack[-1] != '(':
tmp = stack.pop() + tmp
stack.pop()
stack.append(cal(tmp))
tmp = ''
# "(1-(3-4))"
res = "".join(stack)
return int(cal(res)) | basic-calculator | Python3 | dad88htc816 | 0 | 16 | basic calculator | 224 | 0.423 | Hard | 4,067 |
https://leetcode.com/problems/basic-calculator/discuss/2833171/Basic-Calculator-or-Python-Easy-Solution | class Solution:
def calculate(self, s: str) -> int:
num, sign, stack = 0, 1, [0]
for c in s:
if c.isdigit():
num = num*10 + int(c)
elif c==' ':
continue
elif c == '+':
stack[-1] += num * sign
sign = 1
num = 0
elif c == '-':
stack[-1] += num * sign
sign = -1
num = 0
elif c == '(':
stack.extend([sign,0])
sign = 1
num = 0
elif c == ')':
lastNum = (stack.pop() + num*sign) * stack.pop()
stack[-1] += lastNum
sign = 1
num = 0
return stack[-1]+num*sign | basic-calculator | Basic Calculator | Python Easy Solution | jashii96 | 0 | 15 | basic calculator | 224 | 0.423 | Hard | 4,068 |
https://leetcode.com/problems/basic-calculator/discuss/2833149/Simple-Python-solution | class Solution:
def calculate(self, s: str) -> int:
res = 0
sign = 1
num = 0
stack = []
for c in s:
if c.isdigit():
num = 10 * num + int(c) # get the full number
elif c in "-+":
res += sign * num
num = 0 # reset to zero after calculation
sign = 1 if c == '+' else -1
elif c == '(': # prep for calculation
stack.append(res) # cache previous calculation in a stack
stack.append(sign) # cache the sign in a stack
sign, res = 1, 0 # reset sign and res
elif c == ')':
res += sign * num
res *= stack.pop() # calulate the sign before parentheses
res += stack.pop() # A sign (B)
num = 0 # reset to zero after calculation
return res + num * sign | basic-calculator | Simple Python solution | volopivoshenko | 0 | 14 | basic calculator | 224 | 0.423 | Hard | 4,069 |
https://leetcode.com/problems/basic-calculator/discuss/2832853/Python-Stack | class Solution:
def calculate(self, s: str) -> int:
def calc(exp):
stack = []
sign, e = 1, ''
for char in exp:
if char.isdigit():
e += char
else:
if e:
if sign: stack.append(int(e))
else: stack.append(-int(e))
sign = 1 if char == '+' else 0
e = ''
else:
sign = 1 if char == '+' else sign ^ 1
if sign: stack.append(int(e))
else: stack.append(-int(e))
return str(sum(stack))
stack = []
for char in s:
if char == ' ': continue
if char == ')':
exp = ''
while stack[-1] != '(':
exp = stack.pop() + exp
stack.pop()
stack.append(calc(exp))
else:
stack.append(char)
return calc(''.join(stack)) | basic-calculator | Python Stack | shiv-codes | 0 | 19 | basic calculator | 224 | 0.423 | Hard | 4,070 |
https://leetcode.com/problems/basic-calculator/discuss/2832795/Very-easy-to-understand-commented-code-with-explanations-using-recursion.-Python3! | class Solution:
def calculate(self, s: str) -> int:
def helper(i):
ans = 0
operator = '+'
prev = 0
num = ''
while i < len(s):
if s[i] == ' ':
i += 1
continue
elif s[i] == '+' or s[i] == '-':
operator = s[i]
i += 1
num = ''
else: #it is number or bracket
if s[i].isdigit():
while i < len(s) and s[i].isdigit():
num += s[i]
i += 1
num = int(num)
elif s[i] == '(':
#recursively solve sub expression
num, i = helper(i + 1)
elif s[i] == ')':
#increment i since it is pointing to ')' and return index so previous call can continue from that index
i += 1
return ((ans + prev), i)
if operator == '+':
ans += prev
prev = num
elif operator == '-':
ans += prev
prev = -num
return ans+prev, i
a, ind = helper(0)
return a | basic-calculator | Very easy to understand, commented code with explanations using recursion. Python3! | dkashi | 0 | 11 | basic calculator | 224 | 0.423 | Hard | 4,071 |
https://leetcode.com/problems/basic-calculator/discuss/2832397/Python-Solution | class Solution:
calculate_sign = {'-': -1, '+': 1}
def sum_num(self, s):
s = s.replace('--', '+').replace('+-', '-')
calculate, nums, result = '+', '0', 0
for n in s:
if n.isdigit():
nums += n
else:
result += self.calculate_sign[calculate] * int(nums)
calculate = n
nums = '0'
result += self.calculate_sign[calculate] * int(nums)
return result
def calculate(self, s: str) -> int:
s = s.replace(' ', '')
i = 0
while i < len(s):
if s[i] == ')':
j = i - 1
while s[j] != '(':
j -= 1
temp = s[j + 1:i]
s = s.replace(f'({temp})', str(self.sum_num(s=temp)))
i -= (2 + len(temp))
i += 1
return self.sum_num(s) | basic-calculator | Python Solution | hgalytoby | 0 | 21 | basic calculator | 224 | 0.423 | Hard | 4,072 |
https://leetcode.com/problems/basic-calculator/discuss/2832170/Python3-Solution-oror-Easy-To-Understand-oror-O(N) | class Solution:
def calculate(self, s: str) -> int:
output, curr, sign , stack = 0,0,1,[]
for ch in s:
if ch.isdigit():
curr = curr * 10 + int(ch)
elif ch in "+-":
output += (curr * sign)
curr = 0
if ch == "-":
sign = -1
else:
sign = 1
elif ch =="(":
stack.append(output)
stack.append(sign)
output = 0
sign = 1
elif ch == ")":
output += curr*sign
output *= stack.pop()
output += stack.pop()
curr = 0
return output +(curr*sign) | basic-calculator | Python3 Solution || Easy To Understand || O(N) | ghanshyamvns7 | 0 | 21 | basic calculator | 224 | 0.423 | Hard | 4,073 |
https://leetcode.com/problems/basic-calculator/discuss/2832060/python-solution-using-stack | class Solution:
def calculate(self, s: str) -> int:
res,cur,sign,stack=0,0,1,[]
for c in s:
if c.isdigit():
cur=cur*10+int(c)
elif c in "+-":
res+=(cur*sign)
cur=0
if c == "-":
sign= -1
else:
sign= 1
elif c =="(":
stack.append(res)
stack.append(sign)
res=0
sign=1
elif c == ")":
res+=(cur*sign)
res*=stack.pop()
res+=stack.pop()
cur=0
return res+(cur*sign) | basic-calculator | python solution using stack | ashishneo | 0 | 5 | basic calculator | 224 | 0.423 | Hard | 4,074 |
https://leetcode.com/problems/basic-calculator/discuss/2831919/Calculator-method-2-python-O(n) | class Solution:
def calculate(self, s: str) -> int:
self.l = len(s)
self.ini = 0
return self.calculateOpe(s)
def calculateOpe(self,s):
result = 0
signo = 1
while self.ini < self.l:
char = s[self.ini]
if char == '+':
signo = 1
elif char == '-':
signo = -1
elif char == '(':
self.ini +=1
result += signo*self.calculateOpe(s)
elif char == ')':
return result
elif char == ' ':
self.ini +=1
continue
else:
num = ''
while self.ini < self.l and s[self.ini].isnumeric():
num += s[self.ini]
self.ini+=1
result += signo*int(num)
continue
self.ini +=1
return result | basic-calculator | Calculator - method 2 - python - O(n) | DavidCastillo | 0 | 12 | basic calculator | 224 | 0.423 | Hard | 4,075 |
https://leetcode.com/problems/basic-calculator/discuss/2831829/Recursion-approach | class Solution:
def calculate(self, s):
def calc(it):
def update(op, v):
if op == "+": stack.append(v)
if op == "-": stack.append(-v)
num, stack, sign = 0, [], "+"
while it < len(s):
if s[it].isdigit():
num = num * 10 + int(s[it])
elif s[it] in "+-*/":
# store existing num onto stack
update(sign, num)
# start new num with 0
num, sign = 0, s[it]
elif s[it] == "(":
num, it = calc(it + 1) # start new recursion
elif s[it] == ")":
# num ends here, store it on stack
update(sign, num)
# unwind recursion
return sum(stack), it
it += 1
update(sign, num)
return sum(stack)
return calc(0) | basic-calculator | Recursion approach | remidinishanth | 0 | 8 | basic calculator | 224 | 0.423 | Hard | 4,076 |
https://leetcode.com/problems/basic-calculator/discuss/2831717/Calculator-python-O(n) | class Solution:
def calculate(self, s: str) -> int:
stack = []
l = len(s)
signo = 1
i= 0
while i < l:
char = s[i]
if char == '+':
signo = 1
elif char == '-':
signo = -1
elif char == '(':
stack.append([signo, 0])
signo = 1
elif char == ')':
sg, val = stack.pop(-1)
if stack:
stack[-1][1] += sg*val
else:
stack.append([1, sg*val])
elif char == ' ':
i += 1
continue
else:
number = ''
while i< l and s[i].isnumeric():
number += s[i]
i += 1
if stack:
stack[-1][1] += signo*int(number)
else:
stack.append([1, signo*int(number)])
continue
i += 1
return sum([sg*val for sg, val in stack]) | basic-calculator | Calculator - python O(n) | DavidCastillo | 0 | 12 | basic calculator | 224 | 0.423 | Hard | 4,077 |
https://leetcode.com/problems/basic-calculator/discuss/2831574/python3-Stack-solution-for-reference | class Solution:
def evaluate(self, ops):
total = 0
op = "+"
for c in ops:
if c == "+" or c== "-":
op = c
elif op == "+":
total += int(c)
elif op == "-":
total -= int(c)
return total
def calculate(self, s: str) -> int:
st = []
s = "(" + s + ")"
isOp = lambda c: c == "+" or c == "-" or c == "(" or c == ")"
for c in s:
if c == ' ':
continue
if not isOp(c):
if st and not isOp(st[-1]):
st[-1] += c
continue
st.append(c)
stack = []
for c in st:
if c == ")":
string = []
while stack and stack[-1] != "(":
string.append(stack.pop())
stack.pop()
stack.append(self.evaluate(string[::-1]))
else:
stack.append(c)
return stack[0] | basic-calculator | [python3] Stack solution for reference | vadhri_venkat | 0 | 9 | basic calculator | 224 | 0.423 | Hard | 4,078 |
https://leetcode.com/problems/basic-calculator/discuss/2831486/Easy-Python3-Solution-using-stack | class Solution:
def calculate(self, s: str) -> int:
cur=res=0
sign=1
stack=[]
for char in s:
if char.isdigit():
cur=cur*10 +int(char)
elif char in ["+","-"]:
res+=sign*cur
sign=1 if char =="+" else -1
cur=0
elif char=="(":
stack.append(res)
stack.append(sign)
sign=1
res=0
elif char==")":
res+=sign*cur
res*=stack.pop()
res+=stack.pop()
cur=0
return res+sign*cur | basic-calculator | Easy Python3 Solution using stack | Motaharozzaman1996 | 0 | 24 | basic calculator | 224 | 0.423 | Hard | 4,079 |
https://leetcode.com/problems/basic-calculator/discuss/2831462/Python-Using-stack | class Solution:
def calculate(self, s: str) -> int:
stack = []
sign = 1
res = 0
num = 0
for c in s:
if c.isdigit():
num = num * 10 + int(c)
elif c == "+":
res += sign * num
sign = 1
num = 0
elif c == "-":
res += sign * num
sign = -1
num = 0
elif c == "(":
stack.extend((res, sign))
sign = 1
res = 0
elif c == ")":
res += sign * num
res *= stack.pop()
res += stack.pop()
num = 0
return res + sign * num | basic-calculator | [Python] Using stack | vishrutkmr7 | 0 | 6 | basic calculator | 224 | 0.423 | Hard | 4,080 |
https://leetcode.com/problems/basic-calculator/discuss/2761029/Python3-Stack%2BRecursion | class Solution:
def calculate(self, s: str) -> int:
def update(v, op):
if op == '+':
stack.append(v)
elif op == '-':
stack.append(-v)
i, num, stack, sign = 0, 0, [], '+'
while i < len(s):
# number may contain multiple sequential characters
if s[i].isdigit():
num = num*10 + int(s[i])
# recursively calculate the inner expression
elif s[i] == '(':
num, j = self.calculate(s[i+1:])
i += j
# push the current number onto the stack
elif s[i] in '+-':
update(num, sign)
num, sign = 0, s[i]
# return answer and location for this expression
elif s[i] == ')':
update(num, sign)
return sum(stack), i+1
i += 1
update(num, sign)
return sum(stack) | basic-calculator | Python3 Stack+Recursion | jonathanbrophy47 | 0 | 24 | basic calculator | 224 | 0.423 | Hard | 4,081 |
https://leetcode.com/problems/basic-calculator/discuss/2729464/Python3-Commented-and-clear-Recursive-Stack-Calculator | class Solution:
# define an operation set
operations = set("+-*/")
def calculate(self, s: str) -> int:
return self.recursiveCalc(s, 0)
def recursiveCalc(self, s: str, idx: int) -> int:
# intitialize some variables
current_value = 0
stack = collections.deque()
operation = '+'
# go through the string
while idx < len(s):
# check whether we found a digit
if s[idx].isdigit():
# update our current value
current_value = current_value * 10 + int(s[idx])
# check whether we found an operation
elif s[idx] in self.operations:
# update our stack
self.update(operation, current_value, stack)
# set the operation and reset the current value
# as they have been processed
current_value = 0
operation = s[idx]
# recurse deeper as we found an open bracket
elif s[idx] == "(":
# recurse deeper
current_value, idx = self.recursiveCalc(s, idx + 1)
elif s[idx] == ")":
# update our value if there is some value left
self.update(operation, current_value, stack)
# calculate the result of this layer and go
# up the recursion again
return sum(stack), idx
# go further in the string
idx += 1
# make a last update before returning
self.update(operation, current_value, stack)
# return the value
return sum(stack)
def update(self, operation: str, value: int, stack):
if operation == "+": stack.append(value)
if operation == "-": stack.append(-value)
if operation == "*": stack.append(stack.pop() * value)
if operation == "/": stack.append(int(stack.pop() / value)) | basic-calculator | [Python3] - Commented and clear Recursive-Stack-Calculator | Lucew | 0 | 9 | basic calculator | 224 | 0.423 | Hard | 4,082 |
https://leetcode.com/problems/basic-calculator/discuss/2661152/Python-Simple-Solutions-Stack-98 | class Solution:
def calculate(self, s: str) -> int:
stack = []
p = 0
sign = 1
total = 0
while p < len(s):
char = s[p]
if char.isdigit():
num = 0
while p < len(s) and s[p].isdigit():
num = num*10 + int(s[p])
p += 1
p -= 1
num *= sign
total += num
sign = 1
elif char == '(':
stack.append(total)
stack.append(sign)
total, sign = 0, 1
elif char == ')':
total *= stack.pop()
total += stack.pop()
elif char == '-':
sign = -1
p += 1
return total | basic-calculator | β
[Python] Simple Solutions Stack [ 98%] | Kofineka | 0 | 62 | basic calculator | 224 | 0.423 | Hard | 4,083 |
https://leetcode.com/problems/basic-calculator/discuss/2624833/Simple-Python-solution-with-recursion-and-stack | class Solution:
def calculate(self, s: str) -> int:
def helper(s):
stack = []
sign = '+'
num = 0
while len(s) > 0:
c = s.pop(0)
if c.isdigit():
num = num * 10 + int(c)
# start recursion when meeting left bracket
if c == '(':
num = helper(s)
if (not c.isdigit() and c != ' ') or len(s) == 0:
if (sign == '+'):
stack.append(num)
elif (sign == '-'):
stack.append(-num)
elif (sign == '*'):
stack[-1] *= num
elif (sign == '/'):
stack[-1] = int(stack[-1] / num)
num = 0
sign = c
# end recursion when meeting right bracket
if c == ')': break
return sum(stack)
return helper(list(s)) | basic-calculator | Simple Python solution with recursion and stack | leqinancy | 0 | 48 | basic calculator | 224 | 0.423 | Hard | 4,084 |
https://leetcode.com/problems/basic-calculator/discuss/2491869/Breaking-the-problem-down-EASY-TO-UNDERSTAND-python-solution | class Solution:
def calculate(self, s: str) -> int:
#SOLUTION: use a stack, break down problem into parts
#have a function that converts a string (no parenthesis) to array correctly
#"1 + 10 - 11 + 12" -> [1, +, 10, -, 11, +, 12]
#have a function that can evaluate a converted array (no parenthesis)
#[1, +, 10, -, 11, +, 12] -> 12
#have a for loop with stack that evaluates the non-parenthesis expressions
#splits string (no parenthesis) to array
def split_arr(s):
s = s.replace(" ", '')
i = 0
curr = ""
arr = []
while i != len(s):
if s[i] in ['+', '-']:
if curr != "":
arr.append(curr)
arr.append(s[i])
i += 1
curr = ""
curr += s[i]
i += 1
#dont forget to add last element
arr.append(curr)
return arr
#evaluates an expression WITHOUT parenthesis
#adds a "+" to the front if needed
#evaluates by taking 2 elements at a time
#["+", "2"]
#since the symbol == "+", we add 2 to curr
def eval_norm(s):
#split the string using helper function
arr = split_arr(s)
curr = 0
#first num is positive, otherwise there already is a negative sign in front
if arr[0].isnumeric():
arr = ['+'] + arr
for i in range(0, len(arr), 2):
symbol = arr[i]
num = int(arr[i + 1])
if symbol == '+':
curr += num
else:
curr -= num
return curr
#wrap string with ()
s = "(" + s + ")"
stack = []
res = 0
for ch in s:
if ch == ")":
to_eval = ""
while stack[-1] != "(":
to_eval += str(stack.pop())
stack.pop()
#don't forget to reverse since we are popping off stack
to_eval = to_eval[::-1]
#replace double negatives with +
to_eval = to_eval.replace("--", "+")
#add the INDIVIDUAL CHARACTERS (not the entire string) back to the stack
stack += list(str(eval_norm(to_eval)))
'''
for ch in str(eval_norm(to_eval)):
stack.append(ch)
'''
else:
stack.append(ch)
return int("".join(stack)) | basic-calculator | Breaking the problem down - EASY TO UNDERSTAND python solution | yaahallo | 0 | 109 | basic calculator | 224 | 0.423 | Hard | 4,085 |
https://leetcode.com/problems/basic-calculator/discuss/2355734/Python-recursion-solution | class Solution:
def calculate(self, s: str) -> int:
done = False
def recurse(start_index):
nonlocal done
if start_index >= len(s):
done = True
return 0, start_index
index = start_index
negative = False
num_stack = []
res = 0
while not done and index < len(s) and s[index] != ")":
if s[index].isdigit():
num_stack.append(s[index])
index += 1
else:
if s[index] == " ":
index += 1
else: # +, -, (
if len(num_stack) > 0:
curr_number = int("".join(num_stack))
num_stack = []
if negative:
curr_number *= -1
negative = False
res += curr_number
if s[index] == "(":
result, new_index = recurse(index + 1)
index = new_index
if negative:
result *= -1
negative = False
res += result
elif s[index] == "+":
index += 1
elif s[index] == "-":
negative = True
index += 1
if len(num_stack) > 0:
curr_number = int("".join(num_stack))
num_stack = []
if negative:
curr_number *= -1
negative = False
res += curr_number
return res, index + 1
res, index = recurse(0)
return res | basic-calculator | Python recursion solution | lau125 | 0 | 48 | basic calculator | 224 | 0.423 | Hard | 4,086 |
https://leetcode.com/problems/basic-calculator/discuss/1919708/Python-or-Recursion-or-Stack | class Solution:
def calculate(self, s: str) -> int:
def dfs(i):
stk=[]
ops='+'
currnum=0
while i<len(s):
ch=s[i]
if ch=='(':
currnum,i=dfs(i+1)
elif ch==')':
return sum(stk),i
##The lower Portion is similar to Calculator II, starts
if ch.isdigit():
currnum=currnum*10+int(ch)
if not ch.isdigit() and ch!=' ' or i==len(s)-1 or (i<len(s)-1 and s[i+1]==')'):
if ops=='+':
stk.append(currnum)
elif ops=='-':
stk.append(-currnum)
elif ops=='*':
stk.append(stk.pop()*currnum)
elif ops=='/':
x=stk.pop()
if x<0:
x*=-1
stk.append((x//currnum)*-1)
else:
stk.append(x//currnum)
currnum=0
ops=ch
##Ends
i+=1
return sum(stk)*-1 if ops=='-' else sum(stk)
return dfs(0) | basic-calculator | Python | Recursion | Stack | heckt27 | 0 | 73 | basic calculator | 224 | 0.423 | Hard | 4,087 |
https://leetcode.com/problems/basic-calculator/discuss/1437408/Python3Python-Solution-using-recursion-w-comments | class Solution:
def calculate(self, s: str) -> int:
# Strip and replace all the spaces
s = s.strip().replace(" ","")
# Evaluate
def update(stack: List, curr: str, operator: str):
if curr:
if operator == "-":
stack.append(-1 * int(curr))
elif operator == "*":
n = stack.pop()
m = int(curr)
stack.append(n*m)
elif operator == "/":
n = stack.pop()
m = int(curr)
stack.append(int(n/m))
else:
stack.append(int(curr))
return
# Function to evaluate current
def evaluate(s: str, idx: int = 0):
stack = []
operator = ""
curr = ""
while idx < len(s):
# next char
char = s[idx]
# End of current expression
if char == ")":
break
# If new expression, evaluate it first
elif char == "(":
v, idx = evaluate(s,idx+1)
update(stack, str(v), operator)
# If digit keep on appending
elif char.isdigit():
curr = curr + char
else: # update stack
update(stack, curr, operator)
operator = char
curr = ""
# increment index
idx = idx + 1
# Update stack for last operation
update(stack, curr, operator)
return (sum(stack), idx)
return evaluate(s)[0] | basic-calculator | [Python3/Python] Solution using recursion w/ comments | ssshukla26 | 0 | 191 | basic calculator | 224 | 0.423 | Hard | 4,088 |
https://leetcode.com/problems/basic-calculator/discuss/1386937/Reverse-Polish-Notation | class Solution:
def operation(self, a, op, b):
if op == "+":
return a + b
elif op == "-":
return a - b
elif op == "*":
return a * b
elif op == "/":
return a / b
elif op == "**":
return a ** b
return -1
def calculate(self, s: str) -> int:
s = re.sub(r"\d+", lambda m: f" {m.group()} ", s)
s = re.sub(r"\(", " ( ", s)
s = re.sub(r"\)", " ) ", s)
s = s.strip()
expr_lst = s.split()
precedence = {
'**': [4, 'right'], '*': [3, 'left'], '/': [3, 'left'],
'+': [2, 'left'], '-': [2, 'left']}
output = []
operator_stack = []
for token in expr_lst:
if token.isnumeric():
output.append(int(token))
elif token in precedence:
while (operator_stack and operator_stack[-1] != '('
and (precedence[operator_stack[-1]][0]
> precedence[token][0]
or (precedence[operator_stack[-1]][0]
== precedence[token][0] and precedence[token][1]
== 'left'))):
output.append(operator_stack.pop())
operator_stack.append(token)
elif token == '(':
operator_stack.append(token)
elif token == ')':
while operator_stack[-1] != '(':
output.append(operator_stack.pop())
if operator_stack[-1] == '(':
operator_stack.pop()
if operator_stack:
operator_stack.reverse()
output.extend(operator_stack)
stack = []
for x in output:
if x in precedence:
b = stack.pop()
if stack:
a = stack.pop()
stack.append(self.operation(a, x, b))
elif x == "-":
stack.append(-b)
else:
stack.append(x)
return stack.pop() | basic-calculator | Reverse Polish Notation | EvgenySH | 0 | 243 | basic calculator | 224 | 0.423 | Hard | 4,089 |
https://leetcode.com/problems/basic-calculator/discuss/1595157/Python-Easy-Approach-or-Using-Stack | class Solution(object):
def calculate(self, s):
"""
:type s: str
:rtype: int
"""
stack = []
sum = 0
sign = 1
i = 0
while i < len(s):
ch = s[i]
if ch.isdigit():
res = 0
while i < len(s) and s[i].isdigit():
res = res*10+int(s[i])
i += 1
i -= 1
sum += res*sign
sign = 1
elif ch == "-":
sign *= -1
elif ch == "(":
stack.append(sum)
stack.append(sign)
sum = 0
sign = 1
elif ch == ")":
sum *= stack.pop()
sum += stack.pop()
i += 1
# For Handling 32-bit Integers...
if sum <= (1 << 31):
return sum
return (1 << 31)-1 | basic-calculator | Python Easy Approach | Using Stack β | leet_satyam | -1 | 337 | basic calculator | 224 | 0.423 | Hard | 4,090 |
https://leetcode.com/problems/invert-binary-tree/discuss/2463600/Easy-oror-100-oror-Fully-Explained-oror-Java-C%2B%2B-Python-JS-C-Python3-oror-Recursive-and-Iterative | class Solution(object):
def invertTree(self, root):
# Base case...
if root == None:
return root
# swapping process...
root.left, root.right = root.right, root.left
# Call the function recursively for the left subtree...
self.invertTree(root.left)
# Call the function recursively for the right subtree...
self.invertTree(root.right)
return root # Return the root... | invert-binary-tree | Easy || 100% || Fully Explained || Java, C++, Python, JS, C, Python3 || Recursive & Iterative | PratikSen07 | 54 | 3,300 | invert binary tree | 226 | 0.734 | Easy | 4,091 |
https://leetcode.com/problems/invert-binary-tree/discuss/2746210/100-fastest-and-shortest-solution-oror-recursive-approach-oror-5-lines-solution | class Solution:
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
if(root==None):return
root.left,root.right=root.right,root.left
self.invertTree(root.left)
self.invertTree(root.right)
return root | invert-binary-tree | 100% fastest and shortest solution || recursive approach || 5 lines solution | droj | 6 | 1,400 | invert binary tree | 226 | 0.734 | Easy | 4,092 |
https://leetcode.com/problems/invert-binary-tree/discuss/2176643/Python3-DFS-solution | class Solution:
def get_result(self,root):
if (root==None) or (root.left==None and root.right==None):
return root
temp = root.right
root.right = self.get_result(root.left)
root.left = self.get_result(temp)
return root
def invertTree(self, root: TreeNode) -> TreeNode:
return self.get_result(root) | invert-binary-tree | π Python3 DFS solution | Dark_wolf_jss | 4 | 106 | invert binary tree | 226 | 0.734 | Easy | 4,093 |
https://leetcode.com/problems/invert-binary-tree/discuss/2046089/Python-Recursive-and-Iterative-Solutions | class Solution:
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
if root is None:
return None
root.left, root.right = self.invertTree(root.right), self.invertTree(root.left)
return root | invert-binary-tree | Python Recursive and Iterative Solutions | PythonicLava | 3 | 534 | invert binary tree | 226 | 0.734 | Easy | 4,094 |
https://leetcode.com/problems/invert-binary-tree/discuss/1553591/Queue-Solution-with-Time-Complexity-O(N)-and-Space-Complexity-O(N) | class Solution:
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
queue=[root]
while len(queue)>0:
currentNode=queue.pop(0)
if currentNode is None:
continue
self.swapLeftRight(currentNode)
queue.append(currentNode.left)
queue.append(currentNode.right)
return root
def swapLeftRight(self,currentNode):
currentNode.left,currentNode.right=currentNode.right,\
currentNode.left | invert-binary-tree | Queue Solution with Time Complexity O(N) and Space Complexity O(N) | Qyum | 2 | 59 | invert binary tree | 226 | 0.734 | Easy | 4,095 |
https://leetcode.com/problems/invert-binary-tree/discuss/1047942/Python3-simple-solution-using-recursion | class Solution:
def invertTree(self, root: TreeNode) -> TreeNode:
if root:
root.left, root.right = root.right, root.left
self.invertTree(root.left)
self.invertTree(root.right)
return root | invert-binary-tree | Python3 simple solution using recursion | EklavyaJoshi | 2 | 85 | invert binary tree | 226 | 0.734 | Easy | 4,096 |
https://leetcode.com/problems/invert-binary-tree/discuss/2834901/python-oror-simple-solution-oror-recursive | class Solution:
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
# if node null
if not root:
return None
# flip right and left children
root.left, root.right = root.right, root.left
# run on children
self.invertTree(root.left)
self.invertTree(root.right)
return root | invert-binary-tree | python || simple solution || recursive | wduf | 1 | 20 | invert binary tree | 226 | 0.734 | Easy | 4,097 |
https://leetcode.com/problems/invert-binary-tree/discuss/2099297/Fastest-Optimal-Solution-oror-Recursive-Post-Order-Approach | class Solution:
def swapBranches(self, node):
if not node:
return
self.swapBranches(node.left)
self.swapBranches(node.right)
node.left, node.right = node.right, node.left
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
self.swapBranches(root)
return root | invert-binary-tree | Fastest Optimal Solution || Recursive Post Order Approach | Vaibhav7860 | 1 | 95 | invert binary tree | 226 | 0.734 | Easy | 4,098 |
https://leetcode.com/problems/invert-binary-tree/discuss/1808278/Python-Simple-Python-Solution-Using-Recursion-oror-DFS | class Solution:
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
def InvertTree(node):
if node == None:
return None
InvertTree(node.left)
InvertTree(node.right)
node.left, node.right = node.right, node.left
InvertTree(root)
return root | invert-binary-tree | [ Python ] ββ Simple Python Solution Using Recursion || DFS π₯β | ASHOK_KUMAR_MEGHVANSHI | 1 | 83 | invert binary tree | 226 | 0.734 | Easy | 4,099 |
Subsets and Splits