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/sort-list/discuss/1795310/Python3-or-O(1)-Space-Simple-and-Concise-Solution-with-Explanation-or-MergeSort-or-Easy-to-Understand
class Solution: def findMid(self, node): slow = fast = node ''' Here the condition is till fast.next.next. Because, we need to should stop at first mid in case of even length, else we won't be breaking the array equally. Example: 1->2->3->4, here we have to break at 2 so that the list will become 1 -> 2 and 3 -> 4 if we break at 3 the list will become 1 -> 2 -> 3 and 4 which is incorrect ''' while(fast.next and fast.next.next): fast = fast.next.next slow = slow.next return slow def merge(self, node1, node2): dummy = cur = ListNode() intMax = float('inf') while(node1 or node2): value1, value2 = node1.val if(node1) else intMax, node2.val if(node2) else intMax if(value1 < value2): cur.next = node1 node1 = node1.next else: cur.next = node2 node2 = node2.next cur = cur.next return dummy.next def mergeSort(self, node): # Incase of single node or empty node we don't have to do anything. if(node is None or node.next is None): return node mid = self.findMid(node) #Find the mid nextNode = mid.next #Get the start of second half mid.next = None #Break at mid firstHalf = self.mergeSort(node) secondHalf = self.mergeSort(nextNode) return self.merge(firstHalf, secondHalf) def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]: return self.mergeSort(head)
sort-list
Python3 | O(1) Space, Simple and Concise Solution with Explanation | MergeSort | Easy to Understand
thoufic
4
922
sort list
148
0.543
Medium
2,200
https://leetcode.com/problems/sort-list/discuss/715273/Python3-merge-sort-O(NlogN)-time-O(1)-space
class Solution: def sortList(self, head: ListNode) -> ListNode: half = self.halve(head) if not half or head == half: return head return self.merge(self.sortList(head), self.sortList(half)) def halve(self, node: ListNode) -> ListNode: """Break the list into two parts and return the head of 2nd half""" fast = prev = slow = node while fast and fast.next: fast, prev, slow = fast.next.next, slow, slow.next if prev: prev.next = None #break linked list return slow def merge(self, list1: ListNode, list2: ListNode) -> ListNode: """Merge two sorted lists into a sorted list""" dummy = node = ListNode() while list1 and list2: if list1.val > list2.val: list1, list2 = list2, list1 node.next = list1 node, list1 = node.next, list1.next node.next = list1 or list2 return dummy.next
sort-list
[Python3] merge sort O(NlogN) time O(1) space
ye15
2
175
sort list
148
0.543
Medium
2,201
https://leetcode.com/problems/sort-list/discuss/715273/Python3-merge-sort-O(NlogN)-time-O(1)-space
class Solution: def sortList(self, head: ListNode) -> ListNode: nums = [] node = head while node: nums.append(node.val) node = node.next nums.sort() dummy = node = ListNode() for x in nums: node.next = ListNode(x) node = node.next return dummy.next
sort-list
[Python3] merge sort O(NlogN) time O(1) space
ye15
2
175
sort list
148
0.543
Medium
2,202
https://leetcode.com/problems/sort-list/discuss/715273/Python3-merge-sort-O(NlogN)-time-O(1)-space
class Solution: def sortList(self, head: ListNode) -> ListNode: if not head or not head.next: return head # boundary condition (null or single node) fast = prev = slow = head while fast and fast.next: fast, prev, slow = fast.next.next, slow, slow.next prev.next = None # break list into two pieces list1, list2 = self.sortList(head), self.sortList(slow) # sort two pieces repectively dummy = node = ListNode() # merge while list1 and list2: if list1.val > list2.val: list1, list2 = list2, list1 node.next = node = list1 list1 = list1.next node.next = list1 or list2 return dummy.next
sort-list
[Python3] merge sort O(NlogN) time O(1) space
ye15
2
175
sort list
148
0.543
Medium
2,203
https://leetcode.com/problems/sort-list/discuss/580219/Python-counting-sort-just-for-fun
class Solution: def sortList(self, head: ListNode) -> ListNode: if not head: return head num_dict = collections.defaultdict(int) tail = head min_val, max_val = float('inf'), -float('inf') while tail: num_dict[tail.val] += 1 min_val = min(min_val, tail.val) max_val = max(max_val, tail.val) tail = tail.next tail = head = ListNode(0) for num in range(min_val, max_val+1): for _ in range(num_dict[num]): tail.next = ListNode(num) tail = tail.next return head.next
sort-list
Python counting sort - just for fun
nobodynobody1234
2
343
sort list
148
0.543
Medium
2,204
https://leetcode.com/problems/sort-list/discuss/330331/Python3-merge-sort-top-down-(O(log-n)-space)-and-bottom-up-(O(1)-space)
class Solution: def sortList(self, head: ListNode) -> ListNode: # * merge sort def helper(head, dummy): if head.next is None: return head fast = head slow = head while fast and fast.next: prev = slow slow = slow.next fast = fast.next.next # slow now is at the center of the list # break the list into two sublists prev.next = None # merge-sort the two sublists list0 = helper(head, dummy) list1 = helper(slow, dummy) # merge the two sublists node = dummy while list0 is not None or list1 is not None: if list0 is not None and list1 is not None: if list0.val < list1.val: node.next = list0 list0 = list0.next else: node.next = list1 list1 = list1.next node = node.next elif list0 is None: node.next = list1 break elif list1 is None: node.next = list0 break return dummy.next if head is None: return head return helper(head, ListNode(-1))
sort-list
Python3 merge sort top-down (O(log n) space) and bottom-up (O(1) space)
luhao0522
2
344
sort list
148
0.543
Medium
2,205
https://leetcode.com/problems/sort-list/discuss/330331/Python3-merge-sort-top-down-(O(log-n)-space)-and-bottom-up-(O(1)-space)
class Solution: def sortList(self, head: ListNode) -> ListNode: # * merge sort constant space (bottom up) cnt = 0 node = head while node is not None: node = node.next cnt += 1 if cnt < 2: return head dummy = ListNode(-1) dummy.next = head merge_size = 1 # merging all sublists with size <merge_size> # this loop will go on for log n times while merge_size < cnt: pre = dummy end = None i = 0 # this loop takes O(n) time while cnt - i > merge_size: # find two sublists list0 = pre.next node = pre for _ in range(merge_size): node = node.next i += merge_size # mark the break point mid = node for _ in range(min(merge_size, cnt - i)): node = node.next i += min(merge_size, cnt - i) # break up the sublist from the nodes after it end = None if node is not None: end = node.next node.next = None # break the sublist into two parts list1 = mid.next mid.next = None # break the sublist from the nodes before it (optional) pre.next = None # merge the two sublists (and concatenate the new sublist to the nodes before) # the following steps take linear time because we are essentially concatenating nodes to ''pre'' while list0 is not None and list1 is not None: if list0.val < list1.val: pre.next = list0 list0 = list0.next else: pre.next = list1 list1 = list1.next pre = pre.next pre.next = list0 if list0 is not None else list1 while pre.next is not None: pre = pre.next # concatenate these nodes to the rest pre.next = end merge_size <<= 1 return dummy.next
sort-list
Python3 merge sort top-down (O(log n) space) and bottom-up (O(1) space)
luhao0522
2
344
sort list
148
0.543
Medium
2,206
https://leetcode.com/problems/sort-list/discuss/2672104/Python3.-Solution
class Solution: def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]: if head is None: return arr=[] while head: arr.append(head.val) head=head.next arr.sort() dummy=curr=ListNode(0) for i in arr: temp=ListNode(i) curr.next=temp curr=curr.next return dummy.next
sort-list
Python3. Solution
pranjalmishra334
1
344
sort list
148
0.543
Medium
2,207
https://leetcode.com/problems/sort-list/discuss/1795742/Python3-Solution-with-using-extra-space
class Solution: def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]: if not head: return arr = [] while head: arr.append(head.val) head = head.next arr.sort() prev = ListNode(arr[0]) dummy = prev for idx in range(1, len(arr)): curr = ListNode(arr[idx]) prev.next = curr prev = curr return dummy
sort-list
[Python3] Solution with using extra space
maosipov11
1
15
sort list
148
0.543
Medium
2,208
https://leetcode.com/problems/sort-list/discuss/1073400/Python-3-solution-using-merge-sort
class Solution: def sortList(self, head: ListNode) -> ListNode: def findMid(head,tail): fast=head slow=head while(fast!=tail and fast.next!=tail): fast=fast.next.next slow=slow.next return slow def mergeSort(lh,rh): if not lh: return rh elif not rh: return lh elif lh.val<=rh.val: lh.next=mergeSort(lh.next,rh) return lh else: rh.next=mergeSort(lh,rh.next) return rh def merge(head,tail): if(head==tail): br=ListNode(head.val) return br mid=findMid(head,tail) lh=merge(head,mid) rh=merge(mid.next,tail) cl=mergeSort(lh,rh) return cl if not head or not head.next: return head temp=head curr=head while(temp.next): temp=temp.next return merge(curr,temp)
sort-list
Python 3 solution using merge sort
samarthnehe
1
302
sort list
148
0.543
Medium
2,209
https://leetcode.com/problems/sort-list/discuss/2731001/Faster-than-92-and-easiest-solution-in-python
class Solution: def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]: temp = head res = [] while temp: res.append(temp.val) temp = temp.next res = sorted(res) i=0 temp = head while temp: temp.val = res[i] temp = temp.next i+=1 return head```
sort-list
Faster than 92% and easiest solution in python
IronmanX
0
15
sort list
148
0.543
Medium
2,210
https://leetcode.com/problems/sort-list/discuss/2612879/easy-and-simple-python3-solution
class Solution: def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]: # edge case if not head or not head.next: return head # general cases curr = head val_list = [] while curr: val_list.append(curr.val) curr = curr.next dummy = ListNode(0, head) curr = dummy.next val_list.sort() for i in range(len(val_list)): curr.val = val_list[i] curr = curr.next return dummy.next
sort-list
easy and simple python3 solution
codeSheep_01
0
28
sort list
148
0.543
Medium
2,211
https://leetcode.com/problems/sort-list/discuss/2544647/Python3-faster-than-82-500ms
class Solution: def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]: if head is None: return head elif head.next is None: return head pointer = head nums = [] while pointer is not None: nums.append(pointer.val) pointer = pointer.next nums.sort() currentNode = ListNode(nums[0], None) head = currentNode for x in nums[1:-1]: currentNode.next = ListNode(x, None) currentNode = currentNode.next currentNode.next = ListNode(nums[-1], None) return head
sort-list
Python3 faster than 82% 500ms
MariosCh
0
56
sort list
148
0.543
Medium
2,212
https://leetcode.com/problems/sort-list/discuss/2521851/Python-runtime-O(n-logn)-memory-O(n)
class Solution: def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]: if not head: return None cur = head d = {-1:ListNode()} index = 0 while cur: d[index] = cur d[index-1].next = d[index] cur = cur.next index += 1 d = self.mergeSort(d, 0, len(d)-2) d[len(d)-2].next = None return d[0] def mergeSort(self, d, low, high): if low < high: mid = (low+high)//2 left = self.mergeSort(d, low, mid) right = self.mergeSort(d, mid+1, high) lenLeft = len(left)-1 lenRight = len(right)-1 lp = rp = ap = 0 ans = {-1:ListNode()} while lp < lenLeft and rp < lenRight: if left[lp].val <= right[rp].val: ans[ap] = left[lp] lp += 1 else: ans[ap] = right[rp] rp += 1 ans[ap-1].next = ans[ap] ap += 1 while lp < lenLeft: ans[ap] = left[lp] lp += 1 ans[ap-1].next = ans[ap] ap += 1 while rp < lenRight: ans[ap] = right[rp] rp += 1 ans[ap-1].next = ans[ap] ap += 1 return ans return {-1:ListNode(), 0:d[low]}
sort-list
Python, runtime O(n logn), memory O(n)
tsai00150
0
90
sort list
148
0.543
Medium
2,213
https://leetcode.com/problems/sort-list/discuss/2521851/Python-runtime-O(n-logn)-memory-O(n)
class Solution: def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]: if not head: return None cur = head d = {-1:ListNode()} index = 0 while cur: d[index] = cur d[index-1].next = d[index] cur = cur.next index += 1 return self.mergeSort(d, 0, len(d)-2) def mergeSort(self, d, low, high): if low < high: mid = (low+high)//2 left = self.mergeSort(d, low, mid) right = self.mergeSort(d, mid+1, high) head = ListNode() cur = head while left and right: if left.val <= right.val: cur.next = left left = left.next else: cur.next = right right = right.next cur = cur.next while left: cur.next = left left = left.next cur = cur.next while right: cur.next = right right = right.next cur = cur.next cur.next = None return head.next d[low].next = None return d[low]
sort-list
Python, runtime O(n logn), memory O(n)
tsai00150
0
90
sort list
148
0.543
Medium
2,214
https://leetcode.com/problems/sort-list/discuss/2431640/Simple-Python-O(nlogn)-WITHOUT-merge-sort-OR-recursion-or-Beats-96.39
class Solution: # 345 ms, faster than 96.39% def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]: # return empty if linked list doesn't exist if not head: return None # convert linked list to python list l = [] while head: # O(n) l.append(head) head = head.next # sort python list by node values l.sort(key = lambda x: x.val) # O(nlogn) # re-link nodes by order in value-sorted python list for i in range(0, len(l) - 1): # O(n) l[i].next = l[i + 1] l[-1].next = None # set last node to point to none return l[0] # return head of newly linked list
sort-list
Simple Python O(nlogn) WITHOUT merge sort OR recursion | Beats 96.39%
Jonathanace
0
105
sort list
148
0.543
Medium
2,215
https://leetcode.com/problems/sort-list/discuss/2386289/Python-99-Faster-solution
class Solution: def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]: if head is None: return None ret = result = head sets = [] while head: sets.append(head.val) head = head.next sets = sorted(sets) counter = 0 while result: result.val = sets[counter] counter += 1 result = result.next return ret
sort-list
[Python] 99% Faster solution
jiarow
0
101
sort list
148
0.543
Medium
2,216
https://leetcode.com/problems/sort-list/discuss/2316248/Short-and-Fast-Python-Solution-Using-Heap
class Solution: def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]: dummy = ListNode() l = [] dummy.next = head while head: heapq.heappush(l, head.val) head = head.next head = dummy.next while head: head.val = heapq.heappop(l) head = head.next return dummy.next
sort-list
Short and Fast Python Solution Using Heap
zip_demons
0
54
sort list
148
0.543
Medium
2,217
https://leetcode.com/problems/sort-list/discuss/2241206/Merge-sort-Python-solution
class Solution(object): def sortList(self, head): if not head or not head.next: return head fast, slow = head.next, head while fast and fast.next: fast = fast.next.next slow = slow.next start = slow.next slow.next = None l, r = self.sortList(head), self.sortList(start) return self.merge(l, r) def merge(self, l, r): if not l or not r: return l or r dummy = p = ListNode(0) while l and r: if l.val < r.val: p.next = l l = l.next else: p.next = r r = r.next p = p.next p.next = l or r return dummy.next
sort-list
Merge sort Python solution
anirudh_22
0
24
sort list
148
0.543
Medium
2,218
https://leetcode.com/problems/max-points-on-a-line/discuss/1983010/Python-3-Using-Slopes-and-Hash-Tables-or-Clean-Python-solution
class Solution: def maxPoints(self, points: List[List[int]]) -> int: if len(points) <= 2: return len(points) def find_slope(p1, p2): x1, y1 = p1 x2, y2 = p2 if x1-x2 == 0: return inf return (y1-y2)/(x1-x2) ans = 1 for i, p1 in enumerate(points): slopes = defaultdict(int) for j, p2 in enumerate(points[i+1:]): slope = find_slope(p1, p2) slopes[slope] += 1 ans = max(slopes[slope], ans) return ans+1
max-points-on-a-line
[Python 3] Using Slopes and Hash Tables | Clean Python solution
hari19041
33
1,200
max points on a line
149
0.218
Hard
2,219
https://leetcode.com/problems/max-points-on-a-line/discuss/486725/Python-3-(fourteen-lines)-(beats-~94)
class Solution: def maxPoints(self, P: List[List[int]]) -> int: L, M, gcd = len(P), 1, math.gcd for i,(x1,y1) in enumerate(P): s, D = 1, collections.defaultdict(int, {0:0}) for (x2,y2) in P[i+1:]: g = gcd(y2-y1, x2-x1) if g == 0: s += 1 continue m = ((y2-y1)//g, (x2-x1)//g) if m[1] == 0: m = (1,0) if m[1] < 0: m = (-m[0],-m[1]) D[m] += 1 M = max(M, s + max(D.values())) return M if P else 0 - Junaid Mansuri - Chicago, IL
max-points-on-a-line
Python 3 (fourteen lines) (beats ~94%)
junaidmansuri
3
866
max points on a line
149
0.218
Hard
2,220
https://leetcode.com/problems/max-points-on-a-line/discuss/1407180/Python-3-Simple-Hashmap-Slope-and-Intercept
class Solution: def maxPoints(self, points: List[List[int]]) -> int: d1,out={},[1] for i in range(len(points)-1): for j in range(i+1,len(points)): x1,y1,x2,y2 = points[i][0],points[i][1],points[j][0],points[j][1] if x2-x1!=0: slope,intercept = (y2-y1)/(x2-x1),(y1*x2-x1*y2)/(x2-x1) else: slope,intercept = 'inf',(y1*x2-x1*y2)/(y1-y2) key = str(slope)+str(intercept) if key not in d1: d1[key]=[[x1,y1],[x2,y2]] else: if [x1,y1] not in d1[key]: d1[key].append([x1,y1]) if [x2,y2] not in d1[key]: d1[key].append([x2,y2]) for x in d1.values(): out.append(len(x)) return max(out)
max-points-on-a-line
Python 3 Simple, Hashmap, Slope and Intercept
user7387N
2
211
max points on a line
149
0.218
Hard
2,221
https://leetcode.com/problems/max-points-on-a-line/discuss/1993456/Python-easy-readable-solution
class Solution: def maxPoints(self, points: List[List[int]]) -> int: n = len(points) if n <= 1: return n def cal(x1, y1, x2, y2): # (gradient, y-intercept) if x1 == x2 and y1 != y2: return (float('inf'), x1) elif x1 != x2 and y1 == y2: return (0, y1) else: gradient = (y2-y1)/(x2-x1) intercept = (x2*y1-x1*y2)/(x2-x1) return (gradient, intercept) info = defaultdict(int) for i in range(n-1): for j in range(i+1, n): p1, p2 = points[i], points[j] grad, inter = cal(p1[0], p1[1], p2[0], p2[1]) info[(grad, inter)] += 1 k = max(info.values()) return int((1 + math.sqrt(1+8*k))/2) ## we want to get v, where k == v*(v-1)//2
max-points-on-a-line
Python easy-readable solution
byuns9334
1
149
max points on a line
149
0.218
Hard
2,222
https://leetcode.com/problems/max-points-on-a-line/discuss/1929620/Python3-or-Using-dictionary-and-hash-map
class Solution: def maxPoints(self, points: List[List[int]]) -> int: if len(points) <= 2: return len(points) sets = {} for i in range(len(points)): x1, y1 = points[i] for j in range(i+1, len(points)): x2, y2 = points[j] a = None b = None if x2 == x1: a = x1 else: a = (y2-y1)/(x2-x1) b = y1-a*x1 if (a,b) not in sets: sets[(a,b)] = set() sets[(a,b)].add((x1, y1)) sets[(a,b)].add((x2, y2)) return max([len(v) for v in sets.values()])
max-points-on-a-line
Python3 | Using dictionary and hash map
elainefaith0314
1
98
max points on a line
149
0.218
Hard
2,223
https://leetcode.com/problems/max-points-on-a-line/discuss/1596017/Python-Easy-Solution-or-Using-Slope
class Solution: def maxPoints(self, points: List[List[int]]) -> int: def find(target, points): res, final, count = {}, 0, 0 x1, y1 = target for x2, y2 in points: if x1 == x2 and y1 == y2: continue ans = (x2-x1)/(y2-y1) if y2 != y1 else "inf" count = res.get(ans, 0)+1 res[ans] = count final = max(final, count) return final+1 ans = 0 for x1, y1 in points: ans = max(ans, find((x1, y1), points)) return ans
max-points-on-a-line
Python Easy Solution | Using Slope ✔
leet_satyam
1
154
max points on a line
149
0.218
Hard
2,224
https://leetcode.com/problems/max-points-on-a-line/discuss/2842178/i
class Solution: def maxPoints(self,points): if not points: return 0 if len(points) in {1, 2}: return len(points) print(f'num of points = {len(points)}') lines = {} for p1 in range(len(points)): for p2 in range(len(points)): if p1 == p2: continue x1 = points[p1][0] y1 = points[p1][1] x2 = points[p2][0] y2 = points[p2][1] try: m = (y2 - y1) / (x2 - x1) b = y1 - m * x1 m = round(m, 7) b = round(b, 7) except ZeroDivisionError: lines[x1] = 0 else: lines[(m, b)] = 0 print(f'LINES: {lines}') for p in range(len(points)): x, y = points[p][0], points[p][1] for line in lines: try: m = line[0] b = line[1] except TypeError: if line == x: lines[line] += 1 else: if abs(y - (m * x + b)) < 0.0001: lines[line] += 1 print(lines) max1 = max([lines[line] for line in lines]) print(max1) return max1
max-points-on-a-line
i
ohadklr
0
1
max points on a line
149
0.218
Hard
2,225
https://leetcode.com/problems/max-points-on-a-line/discuss/2809514/Easy-Python-Solution-with-Detailed-Explanation
class Solution: def maxPoints(self, points: List[List[int]]) -> int: #if there is 2 or less points, return its length if len(points) <= 2: return len(points) lines = {} def intersection(p1, p2): #the line is vertical, thus slope is infinite if p2[0] == p1[0]: return (p1[0], 0, math.inf ) #otherwise, find intersection point and slope and return slope = (p2[1] - p1[1]) / (p2[0] - p1[0]) y = p1[1] - p1[0] * slope return (0, y, slope) #now iterate through every two points combination for i in range(len(points)): for j in range(i+1,len(points)): #find the info of the line connecting these two points info = intersection(points[i],points[j]) #if there is a key in hashmap matching the info, add these two points to it if hasn't already if info in lines.keys(): if points[i] not in lines[info]: lines[info].append(points[i]) if points[j] not in lines[info]: lines[info].append(points[j]) #otherwise, create a new key containing these two points else: lines[info] = [points[i], points[j]] #find the length of the longest line and return it length = 0 for a in lines.values(): if len(a) > length: length = len(a) return length
max-points-on-a-line
Easy Python Solution with Detailed Explanation
bobbyxq
0
5
max points on a line
149
0.218
Hard
2,226
https://leetcode.com/problems/max-points-on-a-line/discuss/2745302/Python-solution-or-hashmap
class Solution: def maxPoints(self, points: List[List[int]]) -> int: seen = defaultdict(set) res = 0 if len(points) == 1: return 1 for i in range(len(points)): for j in range(i+1, len(points)): x1, y1 = points[i][0], points[i][1] x2, y2 = points[j][0], points[j][1] if x2 == x1: seen[x1].add((x1,y1)) seen[x1].add((x2,y2)) else: a = (y2 - y1)/(x2-x1) b = y1 - a * x1 seen[(a,b)].add((x1,y1)) seen[(a,b)].add((x2,y2)) for key in seen.keys(): res = max(res, len(seen[key])) return res
max-points-on-a-line
Python solution | hashmap
maomao1010
0
10
max points on a line
149
0.218
Hard
2,227
https://leetcode.com/problems/max-points-on-a-line/discuss/2739966/easy-solution-%3A)
class Solution: def maxPoints(self, points: List[List[int]]) -> int: if not len(points): return 0 if len(points) == 1: return 1 if len(points) == 2: return 2 acum = 0 for i, point in enumerate(points): dic = {} j = i + 1 x_i, y_i = point[0], point[1] curr_point = 1 while j < len(points): x_j, y_j = points[j][0], points[j][1] if x_j == x_i and y_j == y_i: j += 1 curr_point += 1 continue angle = (x_j - x_i) / (y_j - y_i) if (y_j - y_i) != 0 else 1000000000 if angle in dic: dic[angle] += 1 else: dic[angle] = 1 j += 1 if len(dic): acum = max(acum, max(dic.values()) + curr_point) else: acum = max(acum, curr_point) if acum == len(points): return acum return acum
max-points-on-a-line
easy solution :)
MaryLuz
0
11
max points on a line
149
0.218
Hard
2,228
https://leetcode.com/problems/max-points-on-a-line/discuss/2738144/Very-concise-Python-solution
class Solution: def maxPoints(self, points: List[List[int]]) -> int: if len(points)==1: return 1 line= lambda x1,y1,x2,y2: ((y2-y1)/(x2-x1),y1+(y2-y1)/(x2-x1)*(-x1)) if x1!=x2 else ('inf',x1) Hash=collections.defaultdict(set) for (i,j),(l,m) in itertools.product(points,points): (val_slope,val_intercept)=line(i,j,l,m) Hash[(val_slope,val_intercept)].add((i,j)) Hash[(val_slope,val_intercept)].add((l,m)) return max(map(lambda x:len(x), Hash.values()))
max-points-on-a-line
Very concise Python solution
Constantine_MBK
0
4
max points on a line
149
0.218
Hard
2,229
https://leetcode.com/problems/max-points-on-a-line/discuss/2678145/Python-solution-beats-95-users-with-explaination
class Solution: def maxPoints(self, points: List[List[int]]) -> int: # We write max for i where i is a point and we are trying to find maximum # points in a line taking i into account def maxfori(i): # We need to calculate slope between points def sloper(x1, y1, x2, y2): deltax, deltay = x2 - x1, y2 - y1 if deltax == 0: return (0, 0) # vertical elif deltax < 0: deltax, deltay = -deltax, -deltay #always keeping deltax positive gcd = math.gcd(deltax, deltay) slope = (deltax // gcd, deltay // gcd) return slope # We add a line between i and j # if it is a horizontal line we note it faster without sloper call # for vertical lines the sloper returns before calculating gcd i.e faster def addLine(i, j, count, dupes): x1, y1 = points[i][0], points[i][1] x2, y2 = points[j][0], points[j][1] if x1 == x2 and y1 == y2: dupes += 1 # calculate duplicates with the original ith point elif y1 == y2: # calculate horizontally similar points here nonlocal horizontals horizontals += 1 count = max(horizontals, count) else: # normal elements on a slope here slope = sloper(x1, y1, x2, y2) lines[slope] += 1 count = max(lines[slope], count) return count, dupes lines, horizontals = defaultdict(lambda: 1), 1 count, dupes = 1, 0 for j in range(i + 1, n): count, dupes = addLine(i, j, count, dupes) return count + dupes # Total on a line for this i n = len(points) if n < 3: return n res = 1 for i in range(n - 1): res = max(maxfori(i), res) # maximum on a line using max return res
max-points-on-a-line
Python solution beats 95% users with explaination
mritunjayyy
0
14
max points on a line
149
0.218
Hard
2,230
https://leetcode.com/problems/max-points-on-a-line/discuss/2670987/Simple-Python-Code-with-Explanation
class Solution: # The key here is to segrate elements based on slope # An N2 solution here means we check each next point for # an ith point and store and segregate based on slope # If there are duplicate elements we simply add them to count # Because the duplicates will always lie on a line with the original i def maxPoints(self, points: List[List[int]]) -> int: # We write max for i where i is a point and we are trying to find maximum # points in a line taking i into account def maxfori(i): # We need to calculate slope between points def sloper(x1, y1, x2, y2): deltax, deltay = x2 - x1, y2 - y1 if deltax == 0: return (0, 0) # vertical elif deltax < 0: deltax, deltay = -deltax, -deltay #always keeping deltax positive gcd = math.gcd(deltax, deltay) slope = (deltax // gcd, deltay // gcd) return slope # We add a line between i and j # if it is a horizontal line we note it faster without sloper call # for vertical lines the sloper returns before calculating gcd i.e faster def addLine(i, j, count, dupes): x1, y1 = points[i][0], points[i][1] x2, y2 = points[j][0], points[j][1] if x1 == x2 and y1 == y2: dupes += 1 # calculate duplicates with the original ith point elif y1 == y2: # calculate horizontally similar points here nonlocal horizontals horizontals += 1 count = max(horizontals, count) else: # normal elements on a slope here slope = sloper(x1, y1, x2, y2) lines[slope] += 1 count = max(lines[slope], count) return count, dupes lines, horizontals = defaultdict(lambda: 1), 1 count, dupes = 1, 0 for j in range(i + 1, n): count, dupes = addLine(i, j, count, dupes) return count + dupes # Total on a line for this i n = len(points) if n < 3: return n res = 1 for i in range(n - 1): res = max(maxfori(i), res) # maximum on a line using max return res
max-points-on-a-line
🥶 Simple Python Code with Explanation
shiv-codes
0
52
max points on a line
149
0.218
Hard
2,231
https://leetcode.com/problems/max-points-on-a-line/discuss/2512259/simplest-python-solution-better-than-90-percent-time
class Solution: def maxPoints(self, points: List[List[int]]) -> int: h = {} n = len(points) ans = -sys.maxsize if(not points): return 0 if(len(points) == 1): return 1 for i in range(n-1): for j in range(i+1,n): if((points[j][0] - points[i][0]) == 0): slope = 99.99 else: slope = (points[j][1] - points[i][1]) / (points[j][0] - points[i][0]) if(slope not in h): h[slope] = [points[j],points[i]] else: if(points[j] not in h[slope]): h[slope].append(points[j]) if(points[i] not in h[slope]): h[slope].append(points[i]) # print(h) for i in h.values(): ans = max(ans,len(i)) h = {} return ans
max-points-on-a-line
simplest python solution better than 90 percent time
jagdishpawar8105
0
57
max points on a line
149
0.218
Hard
2,232
https://leetcode.com/problems/max-points-on-a-line/discuss/2336131/Python-easy-to-read-and-understand-or-hashmap
class Solution: def maxPoints(self, points: List[List[int]]) -> int: ans = 0 n = len(points) for i in range(n): d = collections.defaultdict(int) for j in range(n): if i != j: slope = float("inf") if (points[j][1] - points[i][1] != 0): slope = (points[j][0] - points[i][0]) / (points[j][1] - points[i][1]) d[slope] += 1 if d: ans = max(ans, max(d.values())+1) else: ans = max(ans, 1) return ans
max-points-on-a-line
Python easy to read and understand | hashmap
sanial2001
0
166
max points on a line
149
0.218
Hard
2,233
https://leetcode.com/problems/max-points-on-a-line/discuss/2048837/Python-or-Easy-Optimized-Solution-using-HashMap
class Solution: def maxPoints(self, points: List[List[int]]) -> int: d = {} Max = 0 for i in range(len(points)-Max-1): i_max = 0 x1,y1 = points[i] for j in range(i+1,len(points)): x2,y2 = points[j] if x2 == x1: slope = 100000001 else: slope = (y2 - y1) / (x2 - x1) if slope in d: d[slope] += 1 else: d[slope] = 1 i_max = i_max if i_max > d[slope] else d[slope] d.clear() Max = Max if Max > i_max else i_max return Max + 1
max-points-on-a-line
Python | Easy Optimized Solution using HashMap
__Asrar
0
74
max points on a line
149
0.218
Hard
2,234
https://leetcode.com/problems/max-points-on-a-line/discuss/1710722/python3-algebra-solution
class Solution: def maxPoints(self, points: List[List[int]]) -> int: def gcd(self, a, b): if a!=0: return gcd(self, b % a, a) else: return b pointsInLine = {} for i in range(len(points)): for j in range(i + 1, len(points)): x1, y1, x2, y2 = points[i][0], points[i][1], points[j][0], points[j][1] if x1 == x2: a, b, c = 1, 0, -x1 else: a, b, c = y2 - y1, x1 - x2, x2 * y1 - x1 * y2 if a < 0: a, b, c = -a, -b, -c gp = gcd(self,a,b) g = gcd(self,gp,c) a, b, c = a / g, b / g, c / g line = (a, b, c) pointsInLine.setdefault(line, set()) pointsInLine[line].add(i) pointsInLine[line].add(j) if not pointsInLine: return len(points) else: m = 2 for key in pointsInLine.keys(): m = max(m,len(pointsInLine[key])) return m
max-points-on-a-line
python3 algebra solution
eating
0
63
max points on a line
149
0.218
Hard
2,235
https://leetcode.com/problems/max-points-on-a-line/discuss/1676675/python3-super-easy-solution
class Solution: def maxPoints(self, points: List[List[int]]) -> int: res = 0 def find_max(x, y): dic = {} for cur_x, cur_y in points: slope = "Inf" if y == cur_y else (cur_x - x) / (cur_y - y) if slope == "Inf": dic[slope] = dic.get(slope, 0) + 1 ## need to offset 1 if we finally choose to use this "inf" vertical line (if we dont offset 1, we will count start point twice) else: dic[slope] = dic.get(slope, 1) + 1 ## otherwise count start point in return max(dic.values()) ## return cur_max for x, y in points: ## simply iterate through every point res = max(res, find_max(x, y)) return res
max-points-on-a-line
python3 super easy solution
LambertT
0
110
max points on a line
149
0.218
Hard
2,236
https://leetcode.com/problems/max-points-on-a-line/discuss/1571022/Python-without-Dictonary-or-Counter
class Solution: def maxPoints(self, points: List[List[int]]) -> int: def slope(a,b): dy = a[1]-b[1] dx = a[0]-b[0] if dx == 0: return float('inf') return round(dy/dx,8) res = 0 for i, ptI in enumerate(points): slpTo = [ slope(ptI, points[j]) for j in range(i+1,len(points)) ] slpTo.sort() last, cnt = None, 1 for s in slpTo: if s == last: cnt +=1 else: res = max(cnt,res) cnt, last = 2, s res = max(cnt,res) return res
max-points-on-a-line
Python without Dictonary or Counter
ericghara
0
51
max points on a line
149
0.218
Hard
2,237
https://leetcode.com/problems/max-points-on-a-line/discuss/1338254/8-Liner-Python3-Solution-48ms
class Solution: def maxPoints(self, points: List[List[int]]) -> int: max_occur = 0 for i in range(len(points) - 1): slopes = collections.defaultdict(int) for j in range(i + 1, len(points)): slope = (points[j][1] - points[i][1]) / (points[j][0] - points[i][0]) if points[j][0] != points[i][0] else 20001 slopes[slope] += 1 max_occur = max(max_occur, slopes[slope]) return max_occur + 1
max-points-on-a-line
8-Liner Python3 Solution, 48ms
ruiqianyu
0
71
max points on a line
149
0.218
Hard
2,238
https://leetcode.com/problems/max-points-on-a-line/discuss/724503/Python3-freq-table
class Solution: def maxPoints(self, points: List[List[int]]) -> int: ans = 0 for i, (x0, y0) in enumerate(points): #reference dupe = 1 #count of duplicates freq = dict() #frequency table for x, y in points[i+1:]: if x0 == x and y0 == y: dupe += 1 elif x0 == x: freq[0, inf] = 1 + freq.get((0, inf), 0) elif y0 == y: freq[inf, 0] = 1 + freq.get((inf, 0), 0) else: g = gcd(x-x0, y-y0) x, y = (x-x0)//g, (y-y0)//g if x < 0: x, y = -x, -y freq[x, y] = 1 + freq.get((x, y), 0) ans = max(ans, dupe + max(freq.values(), default=0)) return ans
max-points-on-a-line
[Python3] freq table
ye15
0
160
max points on a line
149
0.218
Hard
2,239
https://leetcode.com/problems/max-points-on-a-line/discuss/724503/Python3-freq-table
class Solution: def maxPoints(self, points: List[List[int]]) -> int: ans = 0 for i, (x, y) in enumerate(points): freq = defaultdict(int) for ii in range(i+1, len(points)): xx, yy = points[ii] if x == xx: dx, dy = 0, 1 elif y == yy: dx, dy = 1, 0 else: dx, dy = xx-x, yy-y g = gcd(dx, dy) if dx < 0: g *= -1 dx, dy = dx//g, dy//g freq[dx, dy] += 1 ans = max(ans, max(freq.values(), default=0)) return 1 + ans
max-points-on-a-line
[Python3] freq table
ye15
0
160
max points on a line
149
0.218
Hard
2,240
https://leetcode.com/problems/max-points-on-a-line/discuss/1094183/15-lines-of-Python-faster-than-96.90
class Solution: def maxPoints(self, points: List[List[int]]) -> int: def solve(p1, p2): if p2[0] == p1[0]: return math.inf, p1[0] m = (p2[1] - p1[1]) / (p2[0] - p1[0]) b = p2[1] - m*p2[0] return m, b n = len(points) if n == 1: return 1 lines = defaultdict(set) for i in range(n): for j in range(i+1, n): m, b = solve(points[i], points[j]) lines[(m,b)].add(i) lines[(m,b)].add(j) return max([len(v) for v in lines.values()])
max-points-on-a-line
15 lines of Python, faster than 96.90%
krawfy
-1
185
max points on a line
149
0.218
Hard
2,241
https://leetcode.com/problems/evaluate-reverse-polish-notation/discuss/1732651/Super-Simple-Python-stack-solution
class Solution: def evalRPN(self, tokens: List[str]) -> int: def update(sign): n2,n1=stack.pop(),stack.pop() if sign=="+": return n1+n2 if sign=="-": return n1-n2 if sign=="*": return n1*n2 if sign=="/": return int(n1/n2) stack=[] for n in tokens: if n.isdigit() or len(n)>1: stack.append(int(n)) else: stack.append(update(n)) return stack.pop()
evaluate-reverse-polish-notation
Super Simple Python 🐍 stack solution
InjySarhan
6
380
evaluate reverse polish notation
150
0.441
Medium
2,242
https://leetcode.com/problems/evaluate-reverse-polish-notation/discuss/2379396/Faster-than-89-and-the-simplest-solution-or-Python
class Solution: def evalRPN(self, tokens: List[str]) -> int: stack = [] for i in tokens: if i == "+": stack[-1] = stack[-2] + stack.pop() elif i == "-": stack[-1] = stack[-2] - stack.pop() elif i == "*": stack[-1] = stack[-2] * stack.pop() elif i == "/": stack[-1] = int(stack[-2] / stack.pop()) else: stack.append(int(i)) return stack.pop()
evaluate-reverse-polish-notation
Faster than 89% and the simplest solution | Python
Bec1l
2
139
evaluate reverse polish notation
150
0.441
Medium
2,243
https://leetcode.com/problems/evaluate-reverse-polish-notation/discuss/2720774/Evaluate-Reverse-Polish-Notation-oror-Java-oror-Python3-oror-Well-Explainedoror-Stack
class Solution: def evalRPN(self, tokens) -> int: stack = [] for ch in tokens: if ch == '+': op1,op2 = stack.pop(), stack.pop() stack.append(op2 + op1) elif ch == '-': op1,op2 = stack.pop(), stack.pop() stack.append(op2 - op1) elif ch == '*': op1,op2 = stack.pop(), stack.pop() stack.append(op2 * op1) elif ch == '/': op1,op2 = stack.pop(), stack.pop() # note // operator works as math.floor so if u divide 6// -132 = -1 stack.append(int(op2 / op1)) else: stack.append(int(ch)) return stack.pop()
evaluate-reverse-polish-notation
Evaluate Reverse Polish Notation || Java || Python3 || Well Explained|| Stack
NitishKumarVerma
1
17
evaluate reverse polish notation
150
0.441
Medium
2,244
https://leetcode.com/problems/evaluate-reverse-polish-notation/discuss/2702470/simple-solution-using-python
class Solution: def evalRPN(self, tokens: List[str]) -> int: stack=[] n=len(tokens) for i in tokens: if(i=="+" or i=="-" or i=='*' or i=="/"): b=stack.pop() a=stack.pop() if (i=="+"): stack.append(int(a+b)) if(i=="-"): stack.append(int(a-b)) if(i=="*"): stack.append(int(a*b)) if(i=="/"): stack.append(int(a/b)) else: stack.append(int(i)) return(stack[0])
evaluate-reverse-polish-notation
simple solution using python
nikhilgowda1312
1
652
evaluate reverse polish notation
150
0.441
Medium
2,245
https://leetcode.com/problems/evaluate-reverse-polish-notation/discuss/2104125/Python-solution-with-match
class Solution: def evalRPN(self, tokens: List[str]) -> int: stack = [] for token in tokens: if token not in ["+", "-", "*", "/"]: stack.append(int(token)) else: x, y = stack.pop(), stack.pop() match token: case "/": stack.append(int(y / x)) case "+": stack.append(y + x) case "-": stack.append(y - x) case "*": stack.append(y * x) return stack[0]
evaluate-reverse-polish-notation
Python solution with match
zhug3
1
47
evaluate reverse polish notation
150
0.441
Medium
2,246
https://leetcode.com/problems/evaluate-reverse-polish-notation/discuss/1974685/Python3-Runtime%3A73ms-72.84-Memory%3A-14.4mb-59.78
class Solution: def evalRPN(self, tokens: List[str]) -> int: stack = [] for num in tokens: if num in {'+', '-', '/', '*'}: num1 = stack.pop() num2 = stack.pop() stack.append(self.makeEquation(num1, num2, num)) else: stack.append(int(num)) return stack[len(stack)-1] def makeEquation(self, num1, num2, symbol): equation = { '+' : num1 + num2, '-' : num2 - num1, '*' : num1 * num2, } if not symbol in equation: return int(num2 / num1) return equation[symbol]
evaluate-reverse-polish-notation
Python3 Runtime:73ms 72.84% Memory: 14.4mb 59.78%
arshergon
1
50
evaluate reverse polish notation
150
0.441
Medium
2,247
https://leetcode.com/problems/evaluate-reverse-polish-notation/discuss/1961421/Python-Simple-Solution-or-Stack-or-beats-96.75
class Solution: def evalRPN(self, tokens: List[str]) -> int: operands = {"+", "-", "*", "/"} stack = [] for i in tokens: if i not in operands: stack.append(int(i)) else: b = stack.pop() a = stack.pop() if i == "+": stack.append(a+b) elif i == "-": stack.append(a-b) elif i == "*": stack.append(a*b) else: stack.append(trunc(a/b)) return stack[0]
evaluate-reverse-polish-notation
[Python] Simple Solution | Stack | beats 96.75%
jamil117
1
86
evaluate reverse polish notation
150
0.441
Medium
2,248
https://leetcode.com/problems/evaluate-reverse-polish-notation/discuss/1687364/faster-than-98.90-of-Python3-using-Postfix-notation-evaluation
class Operator: def __init__(self, left, right): self.left= left self.right = right def evaluate(self): pass class Plus(Operator): def evaluate(self): return self.left + self.right class Minus(Operator): def evaluate(self): return self.left - self.right class Multi(Operator): def evaluate(self): return self.left * self.right class Div(Operator): def evaluate(self): return int(self.left / self.right) class Solution: def evalRPN(self, tokens: List[str]) -> int: stack = [] operators = { "+": Plus, "-": Minus, "*": Multi, "/": Div } for token in tokens: if token in operators: right = stack.pop() left = stack.pop() res = operators[token](left, right).evaluate() stack.append(res) else: stack.append(int(token)) return stack[0]
evaluate-reverse-polish-notation
faster than 98.90% of Python3 using Postfix notation evaluation
takahiro2
1
92
evaluate reverse polish notation
150
0.441
Medium
2,249
https://leetcode.com/problems/evaluate-reverse-polish-notation/discuss/1332654/Why-doesn't-integer-division-work-here
class Solution: def evalRPN(self, tokens: List[str]) -> int: if not tokens: return 0 stack = [] for char in tokens: if not self.isOperator(char): stack.append(char) else: n1,n2 = stack.pop(),stack.pop() stack.append(self.calculate(int(n2),int(n1),char)) return stack[0] def isOperator(self,c): if c=="+" or c=="-" or c=="*" or c=="/": return True return False def calculate(self,a,b,op): if op=="+": return a+b elif op=="-": return a-b elif op=="*": return a*b elif op=="/": return a//b
evaluate-reverse-polish-notation
Why doesn't integer division work here?
psnehas
1
134
evaluate reverse polish notation
150
0.441
Medium
2,250
https://leetcode.com/problems/evaluate-reverse-polish-notation/discuss/1106060/Stack-method-or-Time-99-or-Easy-O(n)-complexity
class Solution: def evalRPN(self, tokens: List[str]) -> int: stack = [] for i in tokens: if i[-1].isdigit(): stack.append(int(i)) else: o2 = stack.pop() o1 = stack.pop() if i == '+': stack.append(o1 + o2) elif i == '-': stack.append(o1 - o2) elif i == '*': stack.append(o1 * o2) else: stack.append(int(float(o1) / o2)) return stack.pop()
evaluate-reverse-polish-notation
Stack method | Time 99% | Easy O(n) complexity
vanigupta20024
1
258
evaluate reverse polish notation
150
0.441
Medium
2,251
https://leetcode.com/problems/evaluate-reverse-polish-notation/discuss/1064929/Python-Stack-Straightforward-Solution
class Solution: def evalRPN(self, tokens: List[str]) -> int: stack=[] operator=["+","-","*","/","%"] for token in tokens: if token not in operator: stack.append((token)) else: first=int(stack.pop()) second=int(stack.pop()) if(token=="+"): stack.append(second + first) if (token == "-"): stack.append(second - first) if (token == "*"): stack.append(second * first) if (token == "/"): stack.append(int(second /first)) if (token == "%"): stack.append(second % first) return stack[-1]
evaluate-reverse-polish-notation
Python - Stack Straightforward Solution
tirucodes
1
185
evaluate reverse polish notation
150
0.441
Medium
2,252
https://leetcode.com/problems/evaluate-reverse-polish-notation/discuss/715308/Python3-stack
class Solution: def evalRPN(self, tokens: List[str]) -> int: stack = [] for token in tokens: if token in "+-*/": rr, ll = stack.pop(), stack.pop() if token == "+": stack.append(ll + rr) elif token == "-": stack.append(ll - rr) elif token == "*": stack.append(ll * rr) else: stack.append(int(ll/rr)) else: stack.append(int(token)) return stack.pop()
evaluate-reverse-polish-notation
[Python3] stack
ye15
1
88
evaluate reverse polish notation
150
0.441
Medium
2,253
https://leetcode.com/problems/evaluate-reverse-polish-notation/discuss/2800349/3-liners-and-eval-solutions
class Solution: def evalRPN(self, tokens: List[str]) -> int: z, stack = ["+","-","*","/"], [] for i in tokens: if i not in z: stack.append(int(i)) else: a = stack.pop() b = stack.pop() c = int(eval("b" + i + "a")) stack.append(c) return stack[0]
evaluate-reverse-polish-notation
3 liners and eval solutions
ebarykin
0
11
evaluate reverse polish notation
150
0.441
Medium
2,254
https://leetcode.com/problems/evaluate-reverse-polish-notation/discuss/2800349/3-liners-and-eval-solutions
class Solution: def evalRPN(self, tokens: List[str]) -> int: stack = [] Z = {'+': lambda a,b: a+b, "-": lambda a,b: a-b, "*": lambda a,b: a*b, "/": lambda a,b: int(a/b)} for i in tokens: if i not in Z: stack.append(int(i)) else: a = stack.pop() b = stack.pop() c = Z[i](b,a) stack.append(c) return stack[0]
evaluate-reverse-polish-notation
3 liners and eval solutions
ebarykin
0
11
evaluate reverse polish notation
150
0.441
Medium
2,255
https://leetcode.com/problems/evaluate-reverse-polish-notation/discuss/2800349/3-liners-and-eval-solutions
class Solution: def evalRPN(self, tokens: List[str]) -> int: Z, s = {'+': lambda b,a: a+b, "-": lambda b,a: a-b, "*": lambda b,a: a*b, "/": lambda b,a: int(a/b)}, [] [s.append(int(i)) if i not in Z else s.append(Z[i](s.pop(),s.pop())) for i in tokens][0] return s[0]
evaluate-reverse-polish-notation
3 liners and eval solutions
ebarykin
0
11
evaluate reverse polish notation
150
0.441
Medium
2,256
https://leetcode.com/problems/evaluate-reverse-polish-notation/discuss/2785067/python-solution-using-operator-and-dictionary
class Solution: def evalRPN(self, tokens: List[str]) -> int: operation_dict = { '+': operator.add, '-': operator.sub, '/': operator.truediv, '*': operator.mul } stack = [] answer = 0 for item in tokens: if operation_dict.__contains__(item): answer = int(operation_dict.get(item)(int(stack[-2]), int(stack[-1]))) stack.pop() stack.pop() stack.append(answer) else: stack.append(item) return stack[-1]
evaluate-reverse-polish-notation
python solution using operator and dictionary
Osama_Qutait
0
7
evaluate reverse polish notation
150
0.441
Medium
2,257
https://leetcode.com/problems/evaluate-reverse-polish-notation/discuss/2778730/Python-3-or-An-O(N)-elegant-solution-compact-code-and-extremely-readable
class Solution: def evalRPN(self, tokens: List[str]) -> int: stack = [] symbols = set('*/+-') compute = { '*': lambda a, b: a * b, '/': lambda a, b: int(a / b), '+': lambda a, b: a + b, '-': lambda a, b: a - b } for token in tokens: if token not in symbols: stack.append(int(token)) continue b = stack.pop() a = stack.pop() stack.append(compute[token](a, b)) return stack.pop()
evaluate-reverse-polish-notation
Python 3 | An O(N) elegant solution, compact code & extremely readable
fachrinfan
0
6
evaluate reverse polish notation
150
0.441
Medium
2,258
https://leetcode.com/problems/evaluate-reverse-polish-notation/discuss/2769938/Simple-Python-Solution
class Solution: def evalRPN(self, tokens: List[str]) -> int: stack = [] for c in tokens: if c == "+": stack.append(stack.pop() + stack.pop()) elif c == "-": a, b = stack.pop(), stack.pop() stack.append(b-a) # has to be in order, b is popped from the back last, making it the first elif c == "*": stack.append(stack.pop() * stack.pop()) elif c == "/": a, b = stack.pop(), stack.pop() stack.append(int(b/a)) # round down like // else: stack.append(int(c)) return stack[0]
evaluate-reverse-polish-notation
Simple Python Solution
ekomboy012
0
3
evaluate reverse polish notation
150
0.441
Medium
2,259
https://leetcode.com/problems/evaluate-reverse-polish-notation/discuss/2760601/evaluate-Reverse-Polish-Notation-Optimal-Solution-with-python.
class Solution: def evalRPN(self, tokens: List[str]) -> int: stack=[] for c in tokens: if c == "+": stack.append(stack.pop()+stack.pop()) elif c == "-": a,b=stack.pop(),stack.pop() stack.append(b-a) elif c == "*": stack.append(stack.pop() * stack.pop()) elif c == "/": a,b=stack.pop(),stack.pop() stack.append(int(b/a)) else: stack.append(int(c)) return stack[0]
evaluate-reverse-polish-notation
evaluate Reverse Polish Notation Optimal Solution with python.
ossamarhayrhay2001
0
2
evaluate reverse polish notation
150
0.441
Medium
2,260
https://leetcode.com/problems/evaluate-reverse-polish-notation/discuss/2726083/Python-or-Iterative-and-recursive-solutions-with-explanation
class Solution: def evalRPN(self, tokens: List[str]) -> int: nums = deque() for token in tokens: if token not in '+-*/': nums.append(token) else: y, x = nums.pop(), nums.pop() expression = f"{x} {token} {y}" if token != '/' else f"int({x} / {y})" nums.append(eval(expression)) return nums.pop()
evaluate-reverse-polish-notation
Python | Iterative and recursive solutions with explanation
ahmadheshamzaki
0
9
evaluate reverse polish notation
150
0.441
Medium
2,261
https://leetcode.com/problems/evaluate-reverse-polish-notation/discuss/2726083/Python-or-Iterative-and-recursive-solutions-with-explanation
class Solution: class Solution: def evalRPN(self, tokens: List[str]) -> int: def parse(): token = tokens.pop() if token not in '+-*/': return token y = parse() x = parse() return eval(f"{x} {token} {y}" if token != '/' else f"int({x} / {y})") return parse()
evaluate-reverse-polish-notation
Python | Iterative and recursive solutions with explanation
ahmadheshamzaki
0
9
evaluate reverse polish notation
150
0.441
Medium
2,262
https://leetcode.com/problems/evaluate-reverse-polish-notation/discuss/2726083/Python-or-Iterative-and-recursive-solutions-with-explanation
class Solution: def evalRPN(self, tokens: List[str]) -> int: idx = -1 def parse(): nonlocal idx token = tokens[idx] idx -= 1 if token not in '+-*/': return token y = parse() x = parse() return eval(f"{x} {token} {y}" if token != '/' else f"int({x} / {y})") return parse()
evaluate-reverse-polish-notation
Python | Iterative and recursive solutions with explanation
ahmadheshamzaki
0
9
evaluate reverse polish notation
150
0.441
Medium
2,263
https://leetcode.com/problems/evaluate-reverse-polish-notation/discuss/2716444/Python-Stack-Intuitive
class Solution: def evalRPN(self, tokens: List[str]) -> int: stack = [] for t in tokens: if t in '+-*/': n1 = stack.pop() n2 = stack.pop() if t == '+': stack.append(n2 + n1) elif t == '-': stack.append(n2 - n1) elif t == '*': stack.append(n2 * n1) elif t == '/': stack.append(int(n2 / n1)) else: stack.append(int(t)) return stack.pop()
evaluate-reverse-polish-notation
Python Stack Intuitive
jonathanbrophy47
0
3
evaluate reverse polish notation
150
0.441
Medium
2,264
https://leetcode.com/problems/evaluate-reverse-polish-notation/discuss/2711242/Python-or-Stack-%2B-lambda-expressions-solution
class Solution: def evalRPN(self, tokens: List[str]) -> int: stack = [] operations ={ "+": lambda x, y: x + y, "-": lambda x, y: x - y, "*": lambda x, y: x*y, "/": lambda x, y: int(float(x) / y) } for tk in tokens: try: stack.append(int(tk)) except ValueError: second, first = stack.pop(), stack.pop() stack.append(operations[tk](first, second)) return stack[0]
evaluate-reverse-polish-notation
Python | Stack + lambda expressions solution
LordVader1
0
12
evaluate reverse polish notation
150
0.441
Medium
2,265
https://leetcode.com/problems/evaluate-reverse-polish-notation/discuss/2683011/Simple-Python-Stack
class Solution: def evalRPN(self, tokens: List[str]) -> int: stack = [] for token in tokens: if token in '+-*/': b, a = stack.pop(), stack.pop() # int so that decimals are truncated to zero stack.append(int(eval(f'{a}{token}{b}'))) else: stack.append(token) return stack[0]
evaluate-reverse-polish-notation
Simple Python Stack
thelastprime
0
5
evaluate reverse polish notation
150
0.441
Medium
2,266
https://leetcode.com/problems/evaluate-reverse-polish-notation/discuss/2666539/Python-Efficient-and-clean-(Using-eval)
class Solution: def evalRPN(self, tokens: List[str]) -> int: stack = [] operators = ["+","-","*","/"] for token in tokens: if token in operators: a = stack.pop(-1) b = stack.pop(-1) stack.append(str(int(eval(b+token+a)))) else: stack.append(token) return stack.pop(0)
evaluate-reverse-polish-notation
[Python] Efficient and clean (Using eval)
sharaddargan
0
5
evaluate reverse polish notation
150
0.441
Medium
2,267
https://leetcode.com/problems/evaluate-reverse-polish-notation/discuss/2640311/Python-Simple-Solution-or-Stack-99%2B-Speed-or-Fix-Common-Errors-or-Explained-Code
class Solution: def evalRPN(self, tokens: List[str]) -> int: #operators[ord("*")](6, 6) = 36 for example operators = { 43: lambda x, y: x + y, 42: lambda x, y: x * y, 45: lambda x, y: x - y, 47: lambda x, y: int(x / y) } q = deque() # iterate over tokens for t in tokens: # if we find an operator, we need to multiple the top two numbers in our stack # when checking ints we need to check if t is numeric or t[1:] since isnumeric() returns false on negative nums if not (t.isnumeric() or t[1:].isnumeric()): y = q.pop() x = q.pop() #call our operators dict val = operators[ord(t)](x, y) # add our number to top q.append(int(val)) else: #else just a normal num, add it at an int to our stack q.append(int(t)) # result will be last item in q return q.pop()
evaluate-reverse-polish-notation
Python Simple Solution | Stack 99%+ Speed | Fix Common Errors | Explained Code
AlgosWithDylan
0
65
evaluate reverse polish notation
150
0.441
Medium
2,268
https://leetcode.com/problems/evaluate-reverse-polish-notation/discuss/2639437/Python-oror-Stack-O(n)-oror-easy-solution
class Solution: def evalRPN(self, tokens: List[str]) -> int: n = len(tokens) s = [] # stack def calc(a,o,b): # return a ... b, with ... = + or - or * or / if o == '+': return a + b elif o == '-': return a - b elif o == '*': return a * b elif o == '/': if b == 0: # avoid num / 0 return 0 tmp = a//b if a%b and tmp < 0: # -3 // 6 == -1 but we expect == 0 return tmp+1 return tmp for i in range(n): if tokens[i]=='+' or tokens[i] == '-' or tokens[i] == '*' or tokens[i] == '/': a = s.pop() b = s.pop() s.append(calc(b,tokens[i],a)) else: s.append(int(tokens[i])) return s.pop()
evaluate-reverse-polish-notation
Python || Stack O(n) || easy solution
LeeTun2k2
0
9
evaluate reverse polish notation
150
0.441
Medium
2,269
https://leetcode.com/problems/evaluate-reverse-polish-notation/discuss/2601538/Python-Efficient-Stack-method-%2B-Dictionary
class Solution: def evalRPN(self, tokens: List[str]) -> int: stack = [] opps = {"+": operator.add, "-": operator.sub, "*": operator.mul, "/": operator.truediv} for token in tokens: if token not in "+-*/": stack.append(int(token)) else: value2 = stack.pop() stack.append(int(opps[token](stack.pop(), value2))) return stack.pop()
evaluate-reverse-polish-notation
[Python] Efficient Stack method + Dictionary
DyHorowitz
0
19
evaluate reverse polish notation
150
0.441
Medium
2,270
https://leetcode.com/problems/evaluate-reverse-polish-notation/discuss/2594882/python-stack-solution
class Solution: def evalRPN(self, tokens: List[str]) -> int: stack = [] for val in tokens: if val not in "+-*/": stack.append(val) else: b = stack.pop() a = stack.pop() if val == "+": stack.append(int(a) + int(b)) elif val == "-": stack.append(int(a) - int(b)) elif val == "*": stack.append(int(a) * int(b)) else: stack.append(int(int(a) / int(b))) return stack[0]
evaluate-reverse-polish-notation
python stack solution
al5861
0
28
evaluate reverse polish notation
150
0.441
Medium
2,271
https://leetcode.com/problems/evaluate-reverse-polish-notation/discuss/2546429/EASY-UNDERSTANDING-USING-STACKS
class Solution: def evalRPN(self, tokens: List[str]) -> int: numDict = {"*", "/", "+", "-"} stack = [] i = 0 while i < len(tokens): if tokens[i] in numDict: if stack: second = stack.pop() first = stack.pop() if tokens[i] == "*": stack.append(first * second) elif tokens[i] == "/": stack.append(int(first / second)) elif tokens[i] == "+": stack.append(first + second) elif tokens[i] == "-": stack.append(first - second) else: stack.append(int(tokens[i])) i += 1 return int(stack.pop())
evaluate-reverse-polish-notation
EASY UNDERSTANDING USING STACKS
leomensah
0
18
evaluate reverse polish notation
150
0.441
Medium
2,272
https://leetcode.com/problems/evaluate-reverse-polish-notation/discuss/2543376/python-oror-STACK-oror-EASY-TO-UNDERSTAND
class Solution: def evalRPN(self, tokens: List[str]) -> int: stack = [] for c in tokens: if c == "+": val = stack.append(stack.pop() + stack.pop()) elif c == "-": a,b =stack.pop(),stack.pop() stack.append(b-a) elif c == "*": val = stack.append(stack.pop() * stack.pop()) elif c == "/": a,b =stack.pop(),stack.pop() stack.append(int(b/a)) else: stack.append(int(c)) return stack[0]
evaluate-reverse-polish-notation
python || STACK || EASY TO UNDERSTAND
Thisissaket
0
34
evaluate reverse polish notation
150
0.441
Medium
2,273
https://leetcode.com/problems/evaluate-reverse-polish-notation/discuss/2520707/Python-Solution-medium-que-feels-like-easy-with-this-solution-Faster-then-96-super-easy-Solution
class Solution: def evalRPN(self, tokens: List[str]) -> int: stack=[] for i in tokens: if i=="+": stack.append(stack.pop()+stack.pop()) elif i=="-": a,b=stack.pop(),stack.pop() stack.append(b-a) elif i=="*": stack.append(stack.pop()*stack.pop()) elif i=="/": a,b=stack.pop(),stack.pop() stack.append(int(b/a)) else: stack.append(int(i)) return stack[0]
evaluate-reverse-polish-notation
Python Solution medium que feels like easy with this solution Faster then 96% super easy Solution
pranjalmishra334
0
38
evaluate reverse polish notation
150
0.441
Medium
2,274
https://leetcode.com/problems/evaluate-reverse-polish-notation/discuss/2473587/Simple-O(N)-solution-With-Segregated-Easy-To-Understand-Functions
class Solution: def evalRPN(self, tokens: List[str]) -> int: stack = [] operators = ["+","-","*","/"] def add(n1, n2): return n1+n2 def subtract(n1, n2): return n1 - n2 def divide(n1, n2): return int(n1 / n2) def multiply(n1, n2): return n1*n2 def apply_operator(operator, n1, n2): if operator == "+": return add(n1, n2) elif operator == "-": return subtract(n1, n2) elif operator == "*": return multiply(n1, n2) else: return divide(n1, n2) for token in tokens: if token in operators and stack: n1 = stack.pop() n2 = stack.pop() result = apply_operator(token, n2, n1) stack.append(result) else: stack.append(int(token)) return stack[0]
evaluate-reverse-polish-notation
Simple O(N) solution - With Segregated Easy To Understand Functions
suhail03
0
34
evaluate reverse polish notation
150
0.441
Medium
2,275
https://leetcode.com/problems/evaluate-reverse-polish-notation/discuss/2398698/Evaluate-Reverse-Polish-Notation-using-stack
class Solution: def evalRPN(self, nums: List[str]) -> int: import math stack=[] for i in range(len(nums)): if nums[i] not in ["+","-","/","*"]: stack.append(nums[i]) else: node1=stack.pop() node2=stack.pop() if nums[i]=="+": ans=int(node2)+int(node1) elif nums[i]=="-": ans=int(node2)-int(node1) elif nums[i]=="*": ans=int(node2)*int(node1) elif nums[i]=="/": ans=(int(node2)/int(node1)) if ans<0: ans=math.ceil(ans) else: ans=math.floor(ans) stack.append(ans) return stack[0]
evaluate-reverse-polish-notation
Evaluate Reverse Polish Notation using stack
deepanshu704281
0
31
evaluate reverse polish notation
150
0.441
Medium
2,276
https://leetcode.com/problems/evaluate-reverse-polish-notation/discuss/2342477/Simple-Python-Solution-oror-Easy-to-Understand
class Solution: def evalRPN(self, tokens: List[str]) -> int: stack = [] for i in tokens: if i not in '+*/-': stack.append(int(i)) else: x = stack.pop() y = stack.pop() if i == '+': r = x + y elif i == '-': r = (y - x) elif i == '/': r = int(y/x) else: r = x * y stack.append(r) return stack.pop() # An upvote will be encouraging
evaluate-reverse-polish-notation
Simple Python Solution || Easy to Understand
rajkumarerrakutti
0
36
evaluate reverse polish notation
150
0.441
Medium
2,277
https://leetcode.com/problems/evaluate-reverse-polish-notation/discuss/2319515/Spicy-it-up-with-some-functional-programming-in-Python!-(dictionary-of-functions-as-values)
class Solution: def evalRPN(self, tokens: List[str]) -> int: nums, ops = deque(), deque() evaluate = {"+": lambda x,y: x+y, "-": lambda x,y: y-x, "*":lambda x,y: y*x, "/": lambda x,y: math.ceil(y/x) if y*x<0 else y//x} for tk in tokens: if tk in evaluate: ops.append(tk) else: nums.append(int(tk)) if len(nums) >= 2 and len(ops) >= 1: a, b = nums.pop(), nums.pop() oper = ops.pop() nums.append(evaluate[oper](a,b)) return nums[0]
evaluate-reverse-polish-notation
Spicy it up with some functional programming in Python! (dictionary of functions as values???)
smoothpineberry
0
20
evaluate reverse polish notation
150
0.441
Medium
2,278
https://leetcode.com/problems/evaluate-reverse-polish-notation/discuss/2306338/Python3-Easy-to-understand-solution-O(N)-Beats-98
class Solution: def evalRPN(self, tokens: List[str]) -> int: operands = [] operators = {'+', '*', '/', '-'} def evaluate(num1, num2, operator) -> int: num1 = int(num1) num2 = int(num2) if operator == '+': return num1 + num2 elif operator == '-': return num1 - num2 elif operator == '*': return num1 * num2 else: return num1 / num2 for token in tokens: if token in operators: num2, num1 = operands.pop(), operands.pop() result = evaluate(num1, num2, token) operands.append(result) else: operands.append(token) return int(operands.pop())
evaluate-reverse-polish-notation
[Python3] ✔️Easy to understand solution O(N) ✔️ Beats 98%
shrined
0
62
evaluate reverse polish notation
150
0.441
Medium
2,279
https://leetcode.com/problems/evaluate-reverse-polish-notation/discuss/2304151/Python3%3A-Faster-than-90-and-simple
class Solution: def evalRPN(self, tokens: List[str]) -> int: def evalualte(x, y, op): if op == '+': return x + y elif op == '-': return x - y elif op == '*': return x * y else: return int(x/y) stack = [] ops = ('+', '-', '*', '/') for t in tokens: if t in ops: y = stack.pop() x = stack.pop() stack.append(evalualte(x, y, t)) else: stack.append(int(t)) return stack.pop()
evaluate-reverse-polish-notation
Python3: Faster than 90% and simple
pradyumna04
0
39
evaluate reverse polish notation
150
0.441
Medium
2,280
https://leetcode.com/problems/evaluate-reverse-polish-notation/discuss/2265278/Python-Dead-easy-with-single-stack-readable
class Solution: OPERATION_MAP = { "+": lambda a, b: a + b, "-": lambda a, b: b - a, "*": lambda a, b: a * b, "/": lambda a, b: int(b / a) if abs(a) < abs(b) else 0 } def evalRPN(self, tokens: List[str]) -> int: if len(tokens) == 1: return tokens[0] operand_stack = [] result = 0 for token in tokens: if token not in Solution.OPERATION_MAP: operand_stack.append(int(token)) else: result = Solution.OPERATION_MAP[token](operand_stack.pop(), operand_stack.pop()) operand_stack.append(result) return result
evaluate-reverse-polish-notation
[Python] Dead easy with single stack, readable
julenn
0
33
evaluate reverse polish notation
150
0.441
Medium
2,281
https://leetcode.com/problems/evaluate-reverse-polish-notation/discuss/2247410/Simple-Python-Solution-oror-O(n)-Time-oror-O(n)-Space
class Solution: def evalRPN(self, tokens: List[str]) -> int: stack = [] for i in tokens: if i.lstrip('-+').isdigit(): stack.append(int(i)) else: a = stack.pop() b = stack.pop() if i == '+': stack.append(a+b) elif i == '-': stack.append(b-a) elif i == '*': stack.append(a*b) else: stack.append(int(b/a)) return stack[-1] # An Upvote will be encouraging
evaluate-reverse-polish-notation
Simple Python Solution || O(n) Time || O(n) Space
rajkumarerrakutti
0
57
evaluate reverse polish notation
150
0.441
Medium
2,282
https://leetcode.com/problems/evaluate-reverse-polish-notation/discuss/2209280/Easy-python-solution-with-comments
class Solution: def evalRPN(self, tokens: List[str]) -> int: # Initialize the set of valid operators s = {'+', '-', '*', '/'} # The last element left out is the final answer while len(tokens) != 1: # Set pointer to 2 because the first two tokens cannot be operators curr = 2 # Find the first token that appears in the tokens while curr < len(tokens) and tokens[curr] not in s: curr += 1 # Calculate the new element to be replaced if tokens[curr] == '+': new = int(tokens[curr-2]) + int(tokens[curr-1]) elif tokens[curr] == '-': new = int(tokens[curr-2]) - int(tokens[curr-1]) elif tokens[curr] == '/': new = int(int(tokens[curr-2]) / int(tokens[curr-1])) elif tokens[curr] == '*': new = int(tokens[curr-2]) * int(tokens[curr-1]) # Delete the elements we just dealt with for _ in range(3): tokens.pop(curr-2) # Insert the number we just calculated tokens.insert(curr-2, str(new)) # The last element left out is the final answer return tokens[0]
evaluate-reverse-polish-notation
Easy python solution with comments
knishiji
0
62
evaluate reverse polish notation
150
0.441
Medium
2,283
https://leetcode.com/problems/evaluate-reverse-polish-notation/discuss/2181360/Python3-Using-dictionary-of-lambda-expressions-or-Stack
class Solution: def evalRPN(self, tokens: List[str]) -> int: evaluate = { '+': lambda a,b : a+b, '-': lambda a,b : a-b, '*': lambda a,b : a*b, '/': lambda a,b : int(a/b) } stack = [] for c in tokens: if c in evaluate: val2, val1 = stack.pop(), stack.pop() stack.append(evaluate[c](val1,val2)) else: stack.append(int(c)) return stack.pop()
evaluate-reverse-polish-notation
[Python3] Using dictionary of lambda expressions | Stack
__PiYush__
0
25
evaluate reverse polish notation
150
0.441
Medium
2,284
https://leetcode.com/problems/evaluate-reverse-polish-notation/discuss/2176877/Python3-straightforward-solution-using-Stack-and-eval-function
class Solution: def evalRPN(self, tokens: List[str]) -> int: stack = [] for token in ["+", "-", "*", "/"]: if token in operators: num2 = stack.pop() num1 = stack.pop() stack.append(int(eval(f'{num1}{token}{num2}'))) else: stack.append(int(token)) return stack[0]
evaluate-reverse-polish-notation
[Python3] straightforward solution using Stack and eval function
brightmzb
0
35
evaluate reverse polish notation
150
0.441
Medium
2,285
https://leetcode.com/problems/evaluate-reverse-polish-notation/discuss/2107061/Python3orstack
class Solution: def div(self,b,a): if(b*a<0 and b/a%1!=0): return b//a +1 else: return b//a def evalRPN(self, tokens: List[str]) -> int: stack=[] for i in tokens: if i in ["+","-","*","/"]: # print(stack) if(i=="+"): a=stack.pop() b=stack.pop() stack.append(str(int(a)+int(b))) elif(i=="-"): a=stack.pop() b=stack.pop() stack.append(str(int(b)-int(a))) elif(i=="*"): a=stack.pop() b=stack.pop() stack.append(str(int(b)*int(a))) else: a=stack.pop() b=stack.pop() stack.append(str(self.div(int(b),int(a)))) else: stack.append(i) return stack.pop()
evaluate-reverse-polish-notation
Python3|stack
parthjindl
0
39
evaluate reverse polish notation
150
0.441
Medium
2,286
https://leetcode.com/problems/evaluate-reverse-polish-notation/discuss/2052239/Python3-stack-%2B-operator-dict
class Solution: def evalRPN(self, tokens: List[str]) -> int: # push nums onto the stack # if token is a + - * / pop the last two nums and perform operation and push back onto the stack operations = {'+': operator.add, '-': operator.sub, '*': operator.mul, '/': operator.truediv} stack = [] output = tokens[0] #for edge case like tokens = [18] for element in tokens: if element in operations: # element is + - * / b = stack.pop() a = stack.pop() output = int(operations[element](a, b)) #for handling int div stack.append(output) else: #element is operand stack.append(int(element)) return output
evaluate-reverse-polish-notation
Python3 stack + operator dict
thakurshadman
0
70
evaluate reverse polish notation
150
0.441
Medium
2,287
https://leetcode.com/problems/evaluate-reverse-polish-notation/discuss/2049492/Python3-Queue
class Solution: def evalRPN(self, tokens: List[str]) -> int: """ Notes: - operator follow their operands - when we see an operator, use it against last two values time complexity: o(n) space complexity: o(n) """ q = deque(tokens) while len(q) > 1: c = q.popleft() if self.is_operator(char=c): second = q.pop() first = q.pop() value = self.find_value(first=first, second=second, operator=c) q.append(value) else: q.append(c) return int(q.pop()) def is_operator(self, char: str) -> bool: return char == "+" or char == "-" or char == "*" or char == "/" def find_value(self, first: str, second: str, operator: str) -> int: f, s = int(first), int(second) if operator == "+": return f+s if operator == "-": return f-s if operator == "*": return f*s if operator == "/": return int(f/s) raise ValueError(f"something is wrong, operator={operator}")
evaluate-reverse-polish-notation
[Python3] Queue
princekc2022
0
31
evaluate reverse polish notation
150
0.441
Medium
2,288
https://leetcode.com/problems/evaluate-reverse-polish-notation/discuss/2013992/Python-Solution
class Solution: def evalRPN(self, tokens: List[str]) -> int: def calculate(num1, num2, operator): if operator=='+': return num1+num2 if operator=='-': return num2-num1 if operator=='*': return num1*num2 if operator=='/': return int(num2/num1) return 0 stack=[] for i in range(len(tokens)): if tokens[i] == '+' or tokens[i] == '-' or tokens[i] == '*' or tokens[i] == '/': num1=stack.pop() num2=stack.pop() stack.append(calculate(num1, num2, tokens[i])) else: stack.append(int(tokens[i])) return stack.pop()
evaluate-reverse-polish-notation
Python Solution
Siddharth_singh
0
38
evaluate reverse polish notation
150
0.441
Medium
2,289
https://leetcode.com/problems/reverse-words-in-a-string/discuss/1632928/Intuitive-Two-Pointers-in-Python-without-strip()-or-split()
class Solution: def reverseWords(self, s: str) -> str: #Time: O(n) since we scan through the input, where n = len(s) #Space: O(n) words = [] slow, fast = 0, 0 #Use the first char to determine if we're starting on a " " or a word mode = 'blank' if s[0] == ' ' else 'word' while fast < len(s): #If we start on a word and our fast ptr lands on a white space #means that we have singled out a word if mode == 'word' and s[fast] == ' ': words.append(s[slow:fast]) slow = fast #Make the slow ptr catch up mode = 'blank' #If we start on a white space and our fast ptr runs into a character #means we are at the start of a word elif mode == 'blank' and s[fast] != ' ': slow = fast #Make the slow ptr catch up mode = 'word' fast += 1 #Increment the fast pointer #Append the last word #Edge cases where the last chunk of string are white spaces if (lastWord := s[slow:fast]).isalnum(): words.append(lastWord) return ' '.join(words[::-1])
reverse-words-in-a-string
Intuitive Two Pointers in Python without strip() or split()
surin_lovejoy
10
490
reverse words in a string
151
0.318
Medium
2,290
https://leetcode.com/problems/reverse-words-in-a-string/discuss/2808468/Python3-faster-than-97-without-using-split
class Solution: def reverseWords(self, s: str) -> str: res = [] temp = "" for c in s: if c != " ": temp += c elif temp != "": res.append(temp) temp = "" if temp != "": res.append(temp) return " ".join(res[::-1])
reverse-words-in-a-string
Python3 faster than 97%, without using split
discregionals
7
587
reverse words in a string
151
0.318
Medium
2,291
https://leetcode.com/problems/reverse-words-in-a-string/discuss/2808444/Python3-ONE-LINER-(-)-Explained
class Solution: def reverseWords(self, s: str) -> str: return ' '.join([ch for ch in reversed(s.split()) if ch])
reverse-words-in-a-string
✔️ [Python3] ONE-LINER (☝ ՞ਊ ՞)☝, Explained
artod
7
705
reverse words in a string
151
0.318
Medium
2,292
https://leetcode.com/problems/reverse-words-in-a-string/discuss/2809039/Python-3-Line-Solution-with-Explanation-or-99-Faster
class Solution: def reverseWords(self, s: str) -> str: s = s.strip() s = s.split() return " ".join(s[::-1])
reverse-words-in-a-string
✔️ Python 3 Line Solution with Explanation | 99% Faster 🔥
pniraj657
5
208
reverse words in a string
151
0.318
Medium
2,293
https://leetcode.com/problems/reverse-words-in-a-string/discuss/1703121/Reverse-Words-in-a-String-python-solution
class Solution: def reverseWords(self, s: str) -> str: s=list(s.split()) #split at spaces and convert to list s=s[::-1] #reverse the list return (" ".join(s)) #join the list with spaces
reverse-words-in-a-string
Reverse Words in a String python solution
veda_b10
3
427
reverse words in a string
151
0.318
Medium
2,294
https://leetcode.com/problems/reverse-words-in-a-string/discuss/2808675/Easy-Python-1-line-solution
class Solution: def reverseWords(self, s: str) -> str: return " ".join((s.split())[::-1])
reverse-words-in-a-string
Easy Python 1 line solution
Vistrit
2
121
reverse words in a string
151
0.318
Medium
2,295
https://leetcode.com/problems/reverse-words-in-a-string/discuss/2808521/All-Language-ONLY-1-Line-!-(Include-Java-Python-Rust-Kotlin-Swift-JavaScript-TypeScript)
class Solution: def reverseWords(self, s: str) -> str: return " ".join(s.split()[::-1])
reverse-words-in-a-string
[All Language] ONLY 1 Line ! (Include Java, Python, Rust, Kotlin, Swift, JavaScript, TypeScript)
ethanrao
2
332
reverse words in a string
151
0.318
Medium
2,296
https://leetcode.com/problems/reverse-words-in-a-string/discuss/2169482/Python-beats-92-two-pointers-with-full-working-explanation
class Solution: def reverseWords(self, s: str) -> str: result, i, n = '', 0, len(s) while i < n: while i < n and s[i] == ' ': # conditions will keep going till when the next character is not a space and i += 1 # i will point to the first letter of the word if i >= n: break j = i + 1 # j will begin from the next character where i point while j < n and s[j] != ' ': # j will keep going till when the next character is a space and j += 1 # j will point to the end of the word started with i sub = s[i:j] # creating a substring of that word from i=start to j=space after the last letter if len(result) == 0: # when adding the first letter to the result result = sub else: # let's say if there are two letters in the string s first and last, first will be added in the last and last will be added in the front result = sub + ' ' + result # adding the new substrings in front of the result i = j + 1 # now i will point to next index from the space possibly a word, cause after a space usually a word is there return result
reverse-words-in-a-string
Python beats 92% two pointers with full working explanation
DanishKhanbx
2
214
reverse words in a string
151
0.318
Medium
2,297
https://leetcode.com/problems/reverse-words-in-a-string/discuss/1891595/Using-two-pointers-oror-Eight-lines-of-code-oror-Full-Explanation
class Solution: def reverseWords(self, s: str) -> str: s = s.split(" ") #it splits the string s while "" in s: #it removes all the spaces from the s s.remove("") i,j = 0,len(s)-1 #taking two pointers i and j where i starts from 0th index and j starts from last index while i < j: s[i],s[j] = s[j],s[i] #swapping done i+=1 j-=1 s = " ".join(s) return s
reverse-words-in-a-string
✅Using two pointers || Eight lines of code || Full Explanation
Dev_Kesarwani
2
193
reverse words in a string
151
0.318
Medium
2,298
https://leetcode.com/problems/reverse-words-in-a-string/discuss/1618323/Clean-Python-O(n)-solution-without-using-split-join-strip-slice-etc
class Solution: def reverseWords(self, s: str) -> str: all_words = [] word = "" result = "" # Iterate the string to split words and append to list for end in range(len(s)): if s[end] != " ": # S is non space character if (end+1) >= len(s) or s[end+1] == " ": # Is word ending word += s[end] all_words.append(word) word = "" continue word += s[end] # Reverse the list and concat for w_idx in range(len(all_words)-1, -1, -1): result += all_words[w_idx] if w_idx > 0: result += " " return result
reverse-words-in-a-string
Clean Python O(n) solution without using split, join, strip, slice, etc
Arvindn
2
293
reverse words in a string
151
0.318
Medium
2,299