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/cut-off-trees-for-golf-event/discuss/1204000/Python-normal-and-priority-BFS-faster-than-99-and-faster-than-77
class Solution: def cutOffTree(self, forest: List[List[int]]) -> int: forest.append([0] * len(forest[0])) for row in forest: row.append(0) def bfs(end, start): if end == start: return 0 visited, queue = set(), {start} visited.add(start) step = 0 while queue: s = set() step += 1 for p in queue: for dr, dc in ((-1, 0), (1, 0), (0, 1), (0, -1)): r, c = p[0] + dr, p[1] + dc if not forest[r][c] or (r, c) in visited: continue if (r, c) == end: return step visited.add((r, c)) s.add((r, c)) queue = s trees = [(height, r, c) for r, row in enumerate(forest) for c, height in enumerate(row) if forest[r][c] > 1] # check queue = [(0, 0)] reached = set() reached.add((0, 0)) while queue: r, c = queue.pop() for dr, dc in ((-1, 0), (1, 0), (0, -1), (0, 1)): row, col = r + dr, c + dc if forest[row][col] and (row, col) not in reached: queue.append((row, col)) reached.add((row,col)) if not all([(i, j) in reached for (height, i, j) in trees]): return -1 trees.sort() return sum([bfs((I,J),(i,j)) for (_, i, j), (_, I, J) in zip([(0, 0, 0)] + trees, trees)])
cut-off-trees-for-golf-event
Python, normal and priority BFS, faster than 99% and faster than 77%
dustlihy
4
681
cut off trees for golf event
675
0.342
Hard
11,200
https://leetcode.com/problems/cut-off-trees-for-golf-event/discuss/1204000/Python-normal-and-priority-BFS-faster-than-99-and-faster-than-77
class Solution: def cutOffTree(self, forest: List[List[int]]) -> int: forest.append([0] * len(forest[0])) for row in forest: row.append(0) # distance def distance(i, j, I, J): manhattan = abs(i - I) + abs(j - J) detour = 0 good, bad = [(i, j)], [] visited = set() while True: if not good: good, bad = bad, [] detour += 1 i, j = good.pop() if i == I and j == J: return manhattan + detour * 2 if (i, j) in visited: continue visited.add((i, j)) for i, j, closer in ((i-1, j, i > I), (i+1, j, i < I), (i, j+1, j < J), (i, j-1, j > J)): if forest[i][j]: (good if closer else bad).append((i, j)) trees = [(height, r, c) for r, row in enumerate(forest) for c, height in enumerate(row) if forest[r][c] > 1] # check queue = [(0, 0)] reached = set() reached.add((0, 0)) while queue: r, c = queue.pop() for dr, dc in ((-1, 0), (1, 0), (0, -1), (0, 1)): row, col = r + dr, c + dc if forest[row][col] and (row, col) not in reached: queue.append((row, col)) reached.add((row,col)) if not all([(i, j) in reached for (height, i, j) in trees]): return -1 trees.sort() return sum([distance(i, j, I, J) for (_, i, j), (_, I, J) in zip([(0, 0, 0)] + trees, trees)])
cut-off-trees-for-golf-event
Python, normal and priority BFS, faster than 99% and faster than 77%
dustlihy
4
681
cut off trees for golf event
675
0.342
Hard
11,201
https://leetcode.com/problems/cut-off-trees-for-golf-event/discuss/449346/Python3-BFS-and-A-star
class Solution: def cutOffTree(self, forest: List[List[int]]) -> int: Valid_target=sorted([(val,r,c)for r,row in enumerate(forest) for c,val in enumerate(row) if val>1],key=lambda x:x[0]) sc=sr=ans=0 for x in Valid_target: _,tr,tc=x d=self.dist_bfs(forest,sr,sc,tr,tc) if d<0:return -1 ans+=d sr,sc=tr,tc return ans def dist_bfs(self,forest,sr,sc,tr,tc): R,C=len(forest),len(forest[0]) Queue=collections.deque([(sr,sc,0)]) seen={(sr,sc)} while Queue: r,c,d=Queue.popleft() if tr==r and tc==c: return d for nr,nc in [(r-1,c),(r+1,c),(r,c-1),(r,c+1)]: if 0<=nr<R and 0<=nc<C and (nr,nc) not in seen and forest[nr][nc]: seen.add((nr,nc)) Queue.append((nr,nc,d+1)) return -1
cut-off-trees-for-golf-event
Python3 BFS and A star
Blank__
1
609
cut off trees for golf event
675
0.342
Hard
11,202
https://leetcode.com/problems/cut-off-trees-for-golf-event/discuss/449346/Python3-BFS-and-A-star
class Solution: def cutOffTree(self, forest: List[List[int]]) -> int: Valid_target=sorted([(val,r,c)for r,row in enumerate(forest) for c,val in enumerate(row) if val>1],key=lambda x:x[0]) sc=sr=ans=0 for x in Valid_target: _,tr,tc=x d=self.dist_Astar(forest,sr,sc,tr,tc) if d<0:return -1 ans+=d sr,sc=tr,tc return ans def dist_Astar(self,forest,sr,sc,tr,tc): R,C=len(forest),len(forest[0]) heap=[(0,0,sr,sc)] cost={(sr,sc):0} while heap: f,g,r,c=heapq.heappop(heap) if tr==r and tc==c: return g for nr,nc in [(r-1,c),(r+1,c),(r,c-1),(r,c+1)]: if 0<=nr<R and 0<=nc<C and forest[nr][nc]: New_cost=g+1+abs(nr-tr)+abs(nc-tr) if New_cost<cost.get((nr,nc),99999): cost[(nr,nc)]=New_cost heapq.heappush(heap,(New_cost,g+1,nr,nc)) return -1
cut-off-trees-for-golf-event
Python3 BFS and A star
Blank__
1
609
cut off trees for golf event
675
0.342
Hard
11,203
https://leetcode.com/problems/cut-off-trees-for-golf-event/discuss/1582108/Python3-repeated-bfs
class Solution: def cutOffTree(self, forest: List[List[int]]) -> int: m, n = len(forest), len(forest[0]) def fn(start, end): """Return min steps to move from start to end.""" ans = 0 seen = {start} queue = deque([start]) while queue: for _ in range(len(queue)): i, j = queue.popleft() if (i, j) == end: return ans for ii, jj in (i-1, j), (i, j-1), (i, j+1), (i+1, j): if 0 <= ii < m and 0 <= jj < n and forest[ii][jj] != 0 and (ii, jj) not in seen: seen.add((ii, jj)) queue.append((ii, jj)) ans += 1 return -1 ans = 0 start = (0, 0) for _, i, j in sorted((forest[i][j], i, j) for i in range(m) for j in range(n) if forest[i][j] > 1): val = fn(start, (i, j)) if val == -1: return -1 ans += val start = (i, j) return ans
cut-off-trees-for-golf-event
[Python3] repeated bfs
ye15
0
210
cut off trees for golf event
675
0.342
Hard
11,204
https://leetcode.com/problems/cut-off-trees-for-golf-event/discuss/1988961/Python-sort-BFS
class Solution: def cutOffTree(self, forest: List[List[int]]) -> int: a = [] n = len(forest) m = len(forest[0]) for i in range(n): for j in range(m): if forest[i][j] > 1: a.append(forest[i][j]) a.sort() s = 0 ux = 0 uy = 0 for h in a: if forest[ux][uy] == h: continue dist = [[None] * m for i in range(n)] q = deque() q.append((ux, uy)) dist[ux][uy] = 0 found = False while q and not found: ux, uy = q.popleft() d = [(-1, 0), (0, 1), (1, 0), (0, -1)] for dx, dy in d: vx = ux + dx vy = uy + dy if vx < 0 or vx >= n or vy < 0 or vy >= m: continue if forest[vx][vy] == 0: continue if dist[vx][vy] is None: dist[vx][vy] = dist[ux][uy] + 1 # It's important to stop here! Otherwise there will be TLE if forest[vx][vy] == h: s += dist[vx][vy] ux = vx uy = vy found = True break q.append((vx, vy)) if not found: return -1 return s
cut-off-trees-for-golf-event
[Python] sort, BFS
princess1211
-1
353
cut off trees for golf event
675
0.342
Hard
11,205
https://leetcode.com/problems/valid-parenthesis-string/discuss/584655/Python-O(n)-by-stack.-85%2B-w-Comment
class Solution: def checkValidString(self, s: str) -> bool: # store the indices of '(' stk = [] # store the indices of '*' star = [] for idx, char in enumerate(s): if char == '(': stk.append( idx ) elif char == ')': if stk: stk.pop() elif star: star.pop() else: return False else: star.append( idx ) # cancel ( and * with valid positions, i.e., '(' must be on the left hand side of '*' while stk and star: if stk[-1] > star[-1]: return False stk.pop() star.pop() # Accept when stack is empty, which means all braces are paired # Reject, otherwise. return len(stk) == 0
valid-parenthesis-string
Python O(n) by stack. 85%+ [w/ Comment]
brianchiang_tw
23
813
valid parenthesis string
678
0.339
Medium
11,206
https://leetcode.com/problems/valid-parenthesis-string/discuss/1902405/Python-Time-O(n)-Space-O(1)-Greedy-Solution-with-Detailed-Explanation-and-some-proof
class Solution: def checkValidString(self, s: str) -> bool: leftmin = leftmax = 0 for c in s: if c == "(": leftmax += 1 leftmin += 1 if c == ")": leftmax -= 1 leftmin = max(0, leftmin-1) if c == "*": leftmax +=1 leftmin = max(0, leftmin-1) if leftmax < 0: return False if leftmin == 0: return True
valid-parenthesis-string
Python Time O(n) Space O(1) Greedy Solution with Detailed Explanation and some proof
jlu56
11
347
valid parenthesis string
678
0.339
Medium
11,207
https://leetcode.com/problems/valid-parenthesis-string/discuss/1815483/Python-easy-solution-with-comment
class Solution: def checkValidString(self, s: str) -> bool: left_par_stack = [] # store the index of "(" star_stack = [] # store the index of "*" for i in range(len(s)): if s[i] == "(": # When encounter "(" or "*", we store it separately as "money" for future use. left_par_stack.append(i) elif s[i] == "*": star_stack.append(i) elif s[i] == ")": # When encounter ")", it's time we need to pay, if left_par_stack: # we give priority to pay with "(", so the right-most "(" will be consumed. left_par_stack.pop() elif star_stack: # Otherwise, we pay with "*". star_stack.pop() else: return False # We don't have enough money to pay, game over. while left_par_stack: # In situ that some "(" haven't been consumed. if not star_stack: break elif star_stack[-1] > left_par_stack[-1]: # Only when the idx of "*" is greater than idx of "(" that can we apply "*" as ")" star_stack.pop() left_par_stack.pop() elif star_stack[-1] < left_par_stack[-1]: break return not left_par_stack
valid-parenthesis-string
Python easy solution with comment
byroncharly3
4
221
valid parenthesis string
678
0.339
Medium
11,208
https://leetcode.com/problems/valid-parenthesis-string/discuss/2677649/Python-with-2-stacks-O(n)orO(n)
class Solution: def checkValidString(self, s: str) -> bool: s1 = [] s2 = [] for i, c in enumerate(s): if c == '(': s1.append(i) elif c == '*': s2.append(i) else: if s1: s1.pop() elif s2: s2.pop() else: return False while s1 and s2: if s1[-1] > s2[-1]: # ( is closer to the end than * return False s1.pop() s2.pop() return s1 == [] # O(n)|O(n)
valid-parenthesis-string
Python with 2 stacks, O(n)|O(n)
certman
2
89
valid parenthesis string
678
0.339
Medium
11,209
https://leetcode.com/problems/valid-parenthesis-string/discuss/989891/python-10-lines-beats-80
class Solution: def checkValidString(self, s: str) -> bool: counts = {0} for ch in s: if ch == "(": counts = set(prev+1 for prev in counts) elif ch == ")": counts = set(prev-1 for prev in counts if prev > 0) elif ch == "*": counts = set([prev+1 for prev in counts] + [prev-1 for prev in counts] + list(counts)) return 0 in counts
valid-parenthesis-string
python 10 lines beats 80%
ChiCeline
2
281
valid parenthesis string
678
0.339
Medium
11,210
https://leetcode.com/problems/valid-parenthesis-string/discuss/1767212/Python3-or-Stack
class Solution: def checkValidString(self, s: str) -> bool: leftPar,aste=[],[] n=len(s) for i in range(n): if s[i]=="(": leftPar.append(i) elif s[i]=="*": aste.append(i) else: if leftPar: leftPar.pop() elif aste: aste.pop() else: return False while leftPar: if leftPar and aste: if leftPar[-1]<aste[-1]: leftPar.pop() aste.pop() else: return False else: return False return True
valid-parenthesis-string
[Python3] | Stack
swapnilsingh421
1
111
valid parenthesis string
678
0.339
Medium
11,211
https://leetcode.com/problems/valid-parenthesis-string/discuss/2841557/Python.-Stack-(validity-of-the-string)-%2B-max-balance-checking.
class Solution: def checkValidString(self, s: str) -> bool: s, stack = list(s), [] hi, lo = 0,0 for i in range(len(s)): if s[i] == "(" or s[i] == "*": hi += 1 elif s[i] == ")": hi -= 1 if hi < 0: return False for i in range(len(s)-1, -1, -1): if s[i] == "(": if not stack : return False else: stack.pop() else: stack.append(s[i]) return hi >= 0
valid-parenthesis-string
Python. Stack (validity of the string) + max balance checking.
ebarykin
0
1
valid parenthesis string
678
0.339
Medium
11,212
https://leetcode.com/problems/valid-parenthesis-string/discuss/2825404/Recursion-formula-with-comments
class Solution: def checkValidString(self, s: str) -> bool: weight = {'(': 1, ')': -1} @lru_cache(None) def is_valid(i, w): # weight should be zero, means all chars have pairs if i >= len(s): return w == 0 # any left parenthesis '(' must have a corresponding right parenthesis ')' or # any right parenthesis ')' must have a corresponding left parenthesis '(' if (s[i] == '(' and w < 0) or (s[i] == ')' and w <= 0): return False # '*' could be treated as a single right parenthesis ')' or # a single left parenthesis '(' or an empty string "" if s[i] == '*': return is_valid(i + 1, w + 1) or is_valid(i + 1, w - 1) or is_valid(i + 1, w) return is_valid(i + 1, weight[s[i]] + w) return is_valid(0, 0)
valid-parenthesis-string
Recursion formula with comments
fachrinfan
0
2
valid parenthesis string
678
0.339
Medium
11,213
https://leetcode.com/problems/valid-parenthesis-string/discuss/2751136/using-two-stack
class Solution: def checkValidString(self, s): num_left=0 num_star=0 stack1=[] stack2=[] length=len(s) num_right=0 for i in range(length): if s[i]=='(': stack1.append([s[i],i]) num_left+=1 elif s[i]=='*': stack2.append([s[i],i]) num_star+=1 elif s[i]==')': if stack1!=[]: stack1.pop() num_left-=1 elif stack2!=[]: stack2.pop() num_star-=1 else: return False #print(stack1,stack2) while stack1!=[] and stack2!=[]: #print(stack1,stack2) if stack1[0][1]<stack2[0][1]: stack1.pop(0) stack2.pop(0) else: stack2.pop(0)####return False if stack1!=[]: return False return True
valid-parenthesis-string
using two stack
shahzdor
0
5
valid parenthesis string
678
0.339
Medium
11,214
https://leetcode.com/problems/valid-parenthesis-string/discuss/2645993/Python3-Solution-%3A-Recursive-function-%2B-DP
class Solution: def checkValidString(self, s: str) -> bool: n = len(s) @cache def recur(indx, num_open): # print(indx, num_open) if indx == n: if num_open == 0: return True else: return False curr_chr = s[indx] if curr_chr == ')': if num_open > 0: return recur(indx+1, num_open-1) else: return False elif curr_chr == '(': return recur(indx+1, num_open+1) else: # treat as '(' open_bracket_bool = recur(indx+1, num_open+1) if open_bracket_bool: return True # treat as ')' if num_open > 0: closed_bracket_bool = recur(indx+1, num_open-1) if closed_bracket_bool: return True # treat as '' empty_str_bool = recur(indx+1, num_open) if empty_str_bool: return True return False return recur(0, 0)
valid-parenthesis-string
Python3 Solution : Recursive function + DP
vinaychetu
0
7
valid parenthesis string
678
0.339
Medium
11,215
https://leetcode.com/problems/valid-parenthesis-string/discuss/2553431/Python3-solution-using-stack-and-bisect
class Solution: def checkValidString(self, s: str) -> bool: stack = [] stars = [] for i in range(len(s)): if s[i] == "(": stack.append((s[i], i)) elif s[i] == ")": if stack and stack[-1][0] == "(": stack.pop() else: stack.append((s[i], i)) else: stars.append(i) if not stack: return True else: for i in range(len(stack)): if stack[i][0] == "(": index = bisect.bisect_left(stars, stack[i][1]) if index >= len(stars): return False stars.pop(index) elif stack[i][0] == ")": index = bisect.bisect_left(stars, stack[i][1]) if index-1 >= 0: stars.pop(index-1) else: return False else: return False return True
valid-parenthesis-string
Python3 solution using stack and bisect
FlorinnC1
0
43
valid parenthesis string
678
0.339
Medium
11,216
https://leetcode.com/problems/valid-parenthesis-string/discuss/2538595/Python-easy-to-read-and-understand-or-DP
class Solution: def solve(self, s, i, left): if left < 0: return False if i == len(s): if left == 0: return True return False if (i, left) in self.d: return self.d[(i, left)] if s[i] == '(': self.d[(i, left)] = self.solve(s, i+1, left+1) return self.d[(i, left)] elif s[i] == ')': self.d[(i, left)] = self.solve(s, i+1, left-1) return self.d[(i, left)] else: self.d[(i, left)] = self.solve(s, i+1, left+1) or self.solve(s, i+1, left-1) or self.solve(s, i+1, left) return self.d[(i, left)] def checkValidString(self, s: str) -> bool: self.d = {} return self.solve(s, 0, 0)
valid-parenthesis-string
Python easy to read and understand | DP
sanial2001
0
49
valid parenthesis string
678
0.339
Medium
11,217
https://leetcode.com/problems/valid-parenthesis-string/discuss/2046466/Python-Brute-Force-and-Memo
class Solution: def checkValidString(self, s: str) -> bool: LENGTH = len(s) OPEN, CLOSED, STAR = "(", ")", "*" def isValid(index, num_open_parens): # Base Case: Shouldn't have any open parens remaining at the end, return true if no open parens if index == LENGTH: return num_open_parens == 0 # Recursive Case current_char = s[index] if current_char == OPEN: return isValid(index + 1, num_open_parens + 1) elif current_char == CLOSED: if num_open_parens == 0: return False return isValid(index + 1, num_open_parens - 1) elif current_char == STAR: open_paren = isValid(index + 1, num_open_parens + 1) close_paren = False if num_open_parens > 0: close_paren = isValid(index + 1, num_open_parens - 1) empty = isValid(index + 1, num_open_parens) return open_paren or close_paren or empty raise Exception("Should never get here") return isValid(0, 0)
valid-parenthesis-string
Python Brute Force and Memo
doubleimpostor
0
75
valid parenthesis string
678
0.339
Medium
11,218
https://leetcode.com/problems/valid-parenthesis-string/discuss/2046466/Python-Brute-Force-and-Memo
class Solution: def checkValidString(self, s: str) -> bool: LENGTH = len(s) OPEN, CLOSED, STAR = "(", ")", "*" def isValid(index, num_open_parens, memo): # Base Case: Shouldn't have any open parens remaining at the end, return true if no open parens if index == LENGTH: return num_open_parens == 0 # Recursive Case key = (index, num_open_parens) if key not in memo: current_char = s[index] if current_char == OPEN: memo[key] = isValid(index + 1, num_open_parens + 1, memo) elif current_char == CLOSED: if num_open_parens == 0: return False memo[key] = isValid(index + 1, num_open_parens - 1, memo) elif current_char == STAR: open_paren = isValid(index + 1, num_open_parens + 1, memo) close_paren = False if num_open_parens > 0: close_paren = isValid(index + 1, num_open_parens - 1, memo) empty = isValid(index + 1, num_open_parens, memo) memo[key] = open_paren or close_paren or empty return memo[key] return isValid(0, 0, {})
valid-parenthesis-string
Python Brute Force and Memo
doubleimpostor
0
75
valid parenthesis string
678
0.339
Medium
11,219
https://leetcode.com/problems/valid-parenthesis-string/discuss/1757014/Simple-Python-Sol-with-Explanation
class Solution: def checkValidString(self, s: str) -> bool: open = 0 closed = 0 any = 0 for c in s: if c == '(': open += 1 elif c == ')': closed += 1 else: any += 1 # at the end of each loop check to see if the number of closed brackets # up until that point are greater than the number of open brackets # also check to see if we can change that by changing the *'s to # open brackets if closed > open + any: return False # at the very end of the first loop do a similar check but to see if there are # too many open brackets if closed + any < open: return False open, closed, any = 0, 0, 0 for c in s[::-1]: if c == '(': open += 1 elif c == ')': closed += 1 else: any += 1 # this time iterate backwards and check to see if the number of # open brackets is greater than the number of max closed brackets # we can produce. If it is, then an excess amount of brackets were # "opened" without being able to be closed by the end if open > closed + any: return False #don't have to recheck again because open, closed, and any since the same # values from the first loop return True
valid-parenthesis-string
Simple Python Sol with Explanation
dnadella787
0
69
valid parenthesis string
678
0.339
Medium
11,220
https://leetcode.com/problems/valid-parenthesis-string/discuss/1692764/Python3-Two-pass-check-extreme-cases
class Solution: def checkValidString(self, s: str) -> bool: balNum = 0 # all * will be used as left parenthesis for c in s: if c == '(': balNum += 1 elif c == ')': balNum -= 1 else: balNum += 1 # check as pointer goes if balNum < 0: return False balNum = 0 # all * will be used as right parenthesis for c in s[::-1]: if c == ')': balNum += 1 elif c == '(': balNum -= 1 else: balNum += 1 # check as pointer goes if balNum < 0: return False return True
valid-parenthesis-string
[Python3] Two pass check extreme cases
Rainyforest
0
51
valid parenthesis string
678
0.339
Medium
11,221
https://leetcode.com/problems/valid-parenthesis-string/discuss/701642/Python.-WA-on-submit-but-correct-OP-in-custom-Testcases.-Need-help!
class Solution: def valid(self, s, stack=[]): i, l = 0, len(s) if not l: return True while i<l: c = s[i] if c == '(': stack.append(c) elif c == ')': if stack and stack[-1] == '(': stack.pop() else: return False else: sub = s[i+1:] return (self.valid('('+sub, stack[:]) or self.valid(')'+sub, stack[:]) or self.valid(sub, stack[:])) i += 1 return True if len(stack)==0 else False def checkValidString(self, s: str) -> bool: return self.valid(s)
valid-parenthesis-string
Python. WA on submit but correct O/P in custom Testcases. Need help!
mkatehara
0
43
valid parenthesis string
678
0.339
Medium
11,222
https://leetcode.com/problems/valid-palindrome-ii/discuss/1409641/Python-3-oror-Two-Pointer-Approach-oror-Self-Understandable
class Solution: def validPalindrome(self, s: str) -> bool: p1=0 p2=len(s)-1 while p1<=p2: if s[p1]!=s[p2]: string1=s[:p1]+s[p1+1:] string2=s[:p2]+s[p2+1:] return string1==string1[::-1] or string2==string2[::-1] p1+=1 p2-=1 return True
valid-palindrome-ii
Python 3 || Two Pointer Approach || Self-Understandable
bug_buster
85
5,500
valid palindrome ii
680
0.393
Easy
11,223
https://leetcode.com/problems/valid-palindrome-ii/discuss/1474792/Python-3-Recursion
class Solution: def validPalindrome(self, s: str) -> bool: def isPalindrome(left, right, changed): while left < right: if s[left] != s[right]: if not changed: return isPalindrome(left + 1, right, True) or isPalindrome(left, right - 1, True) else: return False else: left += 1 right -= 1 return True return isPalindrome(0, len(s) - 1, False)
valid-palindrome-ii
Python 3 Recursion
fai555
7
915
valid palindrome ii
680
0.393
Easy
11,224
https://leetcode.com/problems/valid-palindrome-ii/discuss/1310424/Python-Solution
class Solution: def validPalindrome(self, s: str) -> bool: i,j = 0, len(s)-1 while i < j: if s[i] != s[j]: return s[i+1:j+1] == s[i+1:j+1][::-1] or s[i:j] == s[i:j][::-1] i += 1 j -= 1 return True
valid-palindrome-ii
Python Solution
5tigerjelly
5
539
valid palindrome ii
680
0.393
Easy
11,225
https://leetcode.com/problems/valid-palindrome-ii/discuss/1906221/Python-or-5-Solutions
class Solution: def validPalindrome(self, s: str) -> bool: isPal = lambda s: s == s[::-1] if isPal(s): return True for i in range(len(s)): if isPal(s[:i] + s[i+1:]): return True return False
valid-palindrome-ii
✅ Python | 5 Solutions
dhananjay79
3
299
valid palindrome ii
680
0.393
Easy
11,226
https://leetcode.com/problems/valid-palindrome-ii/discuss/1906221/Python-or-5-Solutions
class Solution: def validPalindrome(self, s: str) -> bool: def isPal(s): lo, hi = 0, len(s) - 1 while lo < hi: if s[lo] != s[hi]: return False lo += 1 hi -= 1 return True lo, hi = 0, len(s) - 1 while lo < hi: if s[lo] != s[hi]: return isPal(s[lo+1:hi+1]) or isPal(s[lo:hi]) lo += 1 hi -= 1 return True
valid-palindrome-ii
✅ Python | 5 Solutions
dhananjay79
3
299
valid palindrome ii
680
0.393
Easy
11,227
https://leetcode.com/problems/valid-palindrome-ii/discuss/1906221/Python-or-5-Solutions
class Solution: def validPalindrome(self, s: str) -> bool: lo, hi, isPal = 0, len(s) - 1, lambda s: s == s[::-1] while lo < hi: if s[lo] != s[hi]: return isPal(s[lo+1:hi+1]) or isPal(s[lo:hi]) lo += 1 hi -= 1 return True
valid-palindrome-ii
✅ Python | 5 Solutions
dhananjay79
3
299
valid palindrome ii
680
0.393
Easy
11,228
https://leetcode.com/problems/valid-palindrome-ii/discuss/1906221/Python-or-5-Solutions
class Solution: def validPalindrome(self, s: str) -> bool: def validPal(lo, hi, flag): if lo >= hi: return True if s[lo] == s[hi]: return validPal(lo+1,hi-1, flag) if flag: return validPal(lo+1,hi, False) or validPal(lo, hi-1, False) return False return validPal(0, len(s)-1, True)
valid-palindrome-ii
✅ Python | 5 Solutions
dhananjay79
3
299
valid palindrome ii
680
0.393
Easy
11,229
https://leetcode.com/problems/valid-palindrome-ii/discuss/1906221/Python-or-5-Solutions
class Solution: def validPalindrome(self, s: str) -> bool: def validPal(s, flag): if len(s) < 2: return True if s[0] == s[-1]: return validPal(s[1:-1], flag) if flag: return validPal(s[1:], False) or validPal(s[:-1], False) return False return validPal(s, True)
valid-palindrome-ii
✅ Python | 5 Solutions
dhananjay79
3
299
valid palindrome ii
680
0.393
Easy
11,230
https://leetcode.com/problems/valid-palindrome-ii/discuss/1906221/Python-or-5-Solutions
class Solution: def validPalindrome(self, s: str) -> bool: isPal, n = lambda s: s == s[::-1], len(s) for i in range(n // 2): if s[i] != s[n-i-1]: return isPal(s[i+1:n-i]) or isPal(s[i:n-i-1]) return True
valid-palindrome-ii
✅ Python | 5 Solutions
dhananjay79
3
299
valid palindrome ii
680
0.393
Easy
11,231
https://leetcode.com/problems/valid-palindrome-ii/discuss/1451296/Python3-Nice-Solution-Faster-Than-96.60-Memory-Less-Than-91.12
class Solution: def validPalindrome(self, s: str) -> bool: if s == s[::-1]: return True i, j = 0, len(s) - 1 while i <= j: if s[i] != s[j]: s1, s2 = s[i + 1: j + 1], s[i: j] break i , j = i + 1, j - 1 return s1 == s1[::-1] or s2 == s2[::-1]
valid-palindrome-ii
Python3 Nice Solution, Faster Than 96.60%, Memory Less Than 91.12%
Hejita
3
379
valid palindrome ii
680
0.393
Easy
11,232
https://leetcode.com/problems/valid-palindrome-ii/discuss/1906900/Python3-or-Simple-Solution
class Solution: def validPalindrome(self, s: str) -> bool: i,j=0, len(s)-1 while i<j: if s[i] != s[j]: return s[:i]+s[i+1:] == (s[:i]+s[i+1:])[::-1] or s[:j]+s[j+1:] == (s[:j]+s[j+1:])[::-1] i+=1 j-=1 return True
valid-palindrome-ii
Python3 | Simple Solution
parthjindl
2
58
valid palindrome ii
680
0.393
Easy
11,233
https://leetcode.com/problems/valid-palindrome-ii/discuss/1602140/Concise-two-pointer-solution
class Solution: def validPalindrome(self, s: str) -> bool: low, high = 0, len(s) - 1 while low < high: if s[low] != s[high]: return self._validPalindrome(s[low:high]) or self._validPalindrome(s[low+1:high+1]) low += 1 high -= 1 return True def _validPalindrome(self, s: str) -> bool: if s == s[::-1]: return True
valid-palindrome-ii
Concise two pointer solution
jjalert
2
298
valid palindrome ii
680
0.393
Easy
11,234
https://leetcode.com/problems/valid-palindrome-ii/discuss/2603173/PythonnohtyP-Palindrome-Solution
class Solution: # Classic 2 pointer solution # Start travelling from start and ends # The first mismatch gives us 2 options # We can either remove the first or the end character and the remaining string must be a plindrome # Else return False def validPalindrome(self, s: str) -> bool: l, r = 0, len(s) - 1 while l < r: if s[l] == s[r]: l, r = l + 1, r - 1 else: p1 = s[l + 1: r + 1] p2 = s[l: r] if p1 == p1[:: -1] or p2 == p2[:: -1]: return True else: return False return True
valid-palindrome-ii
PythonnohtyP Palindrome Solution
shiv-codes
1
99
valid palindrome ii
680
0.393
Easy
11,235
https://leetcode.com/problems/valid-palindrome-ii/discuss/2101232/Python3-O(n)-oror-O(1)-Runtime%3A-152ms-73.35
class Solution: def validPalindrome(self, s: str) -> bool: return self.validPalindromeOptimal(s) return self.validPalindromeOptimalTwo(s) # return self.validPalindromeByDict(s) # O(n) || O(1) # runtime: 175ms: 53.30% def validPalindromeOptimal(self, string): if not string: return True left, right = 0, len(string) - 1 while left < right: if string[left] != string[right]: skipLetterLeft = string[left + 1:right+1] skipLetterRight = string[left : right] return (skipLetterLeft == skipLetterLeft[::-1] or skipLetterRight == skipLetterRight[::-1]) left += 1 right -= 1 return True # O(n) || O(1) # runtime: 152ms 73.35% def validPalindromeOptimalTwo(self, string): if not string: return True left, right = 0, len(string) - 1 while left < right: if string[left] != string[right]: return (self.reverse(string[left + 1:right+1]) or self.reverse(string[ left:right])) left += 1 right -= 1 return True def reverse(self, string): return string == string[::-1] # this code passed 375/400 cases # O(n) || O(n) def validPalindromeByDict(self, string): if not string: return True hashMap = dict() for i in string: hashMap[i] = 1 + hashMap.get(i, 0) oddCount = 0 for key in hashMap: if hashMap[key] % 2 == 1: oddCount += 1 return oddCount <= 2
valid-palindrome-ii
Python3 O(n) || O(1); Runtime: 152ms 73.35%
arshergon
1
270
valid palindrome ii
680
0.393
Easy
11,236
https://leetcode.com/problems/valid-palindrome-ii/discuss/1993960/python-easy-to-understand
class Solution: def validPalindrome(self, s: str) -> bool: def isGood(s: str, l: int, r: int): while l < r : if s[l] != s[r] : return False else : l += 1 r -= 1 return True l = 0 r = len(s) - 1 while l < r : if s[l] != s[r] : return isGood(s, l + 1, r) or isGood(s, l, r - 1) else : l += 1 r -= 1 return True
valid-palindrome-ii
python - easy to understand
ZX007java
1
290
valid palindrome ii
680
0.393
Easy
11,237
https://leetcode.com/problems/valid-palindrome-ii/discuss/1907819/python3-or-Strings-or-Simple
class Solution: def validPalindrome(self, s: str) -> bool: def ispalindrome(st : str) -> bool: return st == st[::-1] rev = s[::-1] for i in range(len(s)): if s[i] != rev[i]: s = s[:i] + s[i + 1:] rev = rev[:i] + rev[i + 1:] return ispalindrome(s) or ispalindrome(rev) return True
valid-palindrome-ii
python3 | Strings | Simple
milannzz
1
22
valid palindrome ii
680
0.393
Easy
11,238
https://leetcode.com/problems/valid-palindrome-ii/discuss/1905687/Python-or-Easy-to-Understand-Solution-or-Faster-than-91.3
class Solution: def validPalindrome(self, s: str) -> bool: # Reverse the string and create 4 new empty strings a = s[::-1] n="" m="" o="" p="" # Loop through the string s for x in range(len(s)): # if the characters in s and a at same index don't match if s[x] != a[x]: # Two possible drops can be made now # Eg if s[x] = b and a[x] = c then we can drop anyone # at a time and check if result matches # Drop the Character (Eg. c) from both strings # drops the char at x loc (Eg. c) from string a n = a[:x] + a[x+1:] # get index of same char in s b = len(s)-(x+1) # drops the char from str s m = s[:b] + s[b+1:] #Drop the chracter (Eg. b) from both string o = s[:x] + s[x+1:] b = len(s)-(x+1) p= a[:b] + a[b+1:] break # Check if any of them is True return n==m or o==p
valid-palindrome-ii
Python | Easy to Understand Solution | Faster than 91.3%
ruthlessruler
1
75
valid palindrome ii
680
0.393
Easy
11,239
https://leetcode.com/problems/valid-palindrome-ii/discuss/1872713/Python-easy-to-read-and-understand-or-two-pointers
class Solution: def validPalindrome(self, s: str) -> bool: i, j = 0, len(s)-1 while i < j: if s[i] == s[j]: i, j = i+1, j-1 else: return (s[i+1:j+1] == s[i+1:j+1][::-1]) or (s[i:j] == s[i:j][::-1]) return True
valid-palindrome-ii
Python easy to read and understand | two-pointers
sanial2001
1
169
valid palindrome ii
680
0.393
Easy
11,240
https://leetcode.com/problems/valid-palindrome-ii/discuss/1735289/Faster-than-92-less-memory-than-95
class Solution: def validPalindrome(self, s: str) -> bool: n = len(s) if s == s[::-1]: return True # return True if the string is already a palindrome i = 0 j=n-1 while(i<=j): if s[i] != s[j]: # keep checking if the characters are same if s[i+1: j+1][::-1] == s[i+1: j+1] or s[i: j] == s[i: j][::-1]: # if not same then the smaller string excluding 1 charcter from either left or right should be a palindrome return True else: return False else: i += 1 # keep moving right j -= 1 # keep moving left
valid-palindrome-ii
Faster than 92%, less memory than 95%
saurabh717
1
399
valid palindrome ii
680
0.393
Easy
11,241
https://leetcode.com/problems/valid-palindrome-ii/discuss/1530123/Python-3%3A-Valid-Palindrome-II
class Solution: def validPalindrome(self, s: str) -> bool: def ispalin(s1): return s1 == s1[::-1] left = 0 right = len(s) - 1 while(left<=right): if s[left] == s[right]: left += 1 right -= 1 else: return ispalin(s[left:right]) or ispalin(s[left+1:right+1]) return True
valid-palindrome-ii
Python 3: Valid Palindrome II
Jay1984
1
438
valid palindrome ii
680
0.393
Easy
11,242
https://leetcode.com/problems/valid-palindrome-ii/discuss/1448923/Python3Python-Simple-two-pointer-solution-w-comments
class Solution: def validPalindrome(self, s: str) -> bool: # Modified palindrome checker which return point of conflict # with results def isPalindrome(s: str) -> bool: i = 0 j = len(s)-1 while i < j: if s[i] != s[j]: return False,i,j i += 1 j -= 1 return True,0,len(s)-1 # If string is palindrom return true res, i, j = isPalindrome(s) if res: return res # remove ith character and check if string is palindrome res, _, _ = isPalindrome(s[:i] + s[i+1:]) if res: return res # remove jth character and check if string is plaindrome res, _, _ = isPalindrome(s[:j] + s[j+1:]) if res: return res return False
valid-palindrome-ii
[Python3/Python] Simple two pointer solution w/ comments
ssshukla26
1
610
valid palindrome ii
680
0.393
Easy
11,243
https://leetcode.com/problems/valid-palindrome-ii/discuss/1355706/Faster-than-99.46.
class Solution: def validPalindrome(self, s: str) -> bool: rever = s[::-1] if s == rever: return True else: for i, j in enumerate(s): if rever[i] != j: # Tag 1 rever = rever[0:i] + rever[i+1:] if rever == rever[::-1]: return True # Tag 2 s = s[0:i] + s[i+1:] return s == s[::-1]
valid-palindrome-ii
Faster than 99.46%.
AmrinderKaur1
1
534
valid palindrome ii
680
0.393
Easy
11,244
https://leetcode.com/problems/valid-palindrome-ii/discuss/1211891/Python-or-Generic-Approach-of-at-most-k-deletion
class Solution: def validPalindrome(self, s: str) -> bool: def valid_palindrome_in_k_deletion(s, k): if not s: return True if s[0] != s[-1]: if k == 0: return False else: return (valid_palindrome_in_k_deletion(s[1:],k-1) or valid_palindrome_in_k_deletion(s[:-1],k-1) ) else: return valid_palindrome_in_k_deletion(s[1:-1],k) return valid_palindrome_in_k_deletion(s,1)
valid-palindrome-ii
Python | Generic Approach of at most k deletion
Sanjaychandak95
1
221
valid palindrome ii
680
0.393
Easy
11,245
https://leetcode.com/problems/valid-palindrome-ii/discuss/350953/Solution-in-Python-3
class Solution: def validPalindrome(self, s: str) -> bool: for i in range((len(s))//2): if s[i] != s[-1-i]: t, u = s[:i]+s[i+1:], s[:-1-i]+s[len(s)-i:] return t == t[::-1] or u == u[::-1] return True - Junaid Mansuri
valid-palindrome-ii
Solution in Python 3
junaidmansuri
1
720
valid palindrome ii
680
0.393
Easy
11,246
https://leetcode.com/problems/valid-palindrome-ii/discuss/2848351/Python-oror-99.07-Faster-oror-Two-Pointers-oror-O(n)-Solution
class Solution: def validPalindrome(self, s: str) -> bool: i,j=0,len(s)-1 while i<j: if s[i]!=s[j]: left_remove=s[i+1:j+1] right_remove=s[i:j] return left_remove==left_remove[-1::-1] or right_remove==right_remove[-1::-1] else: i+=1 j-=1 return True
valid-palindrome-ii
Python \|| 99.07% Faster || Two Pointers || O(n) Solution
DareDevil_007
0
1
valid palindrome ii
680
0.393
Easy
11,247
https://leetcode.com/problems/valid-palindrome-ii/discuss/2820661/Simple-python-Two-Pointer-approach
class Solution: def validPalindrome(self, s: str) -> bool: c = 0 p1 = 0 n = len(s) p2 = n - 1 while p1 < p2 and c <= 1: if s[p1] != s[p2]: c += 1 else: p2 -= 1 p1 += 1 if c <= 1: return 1 c = 0 p1 = 0 p2 = n - 1 while p1 < p2 and c <= 1: if s[p1] != s[p2]: c += 1 else: p1 += 1 p2 -= 1 return c <= 1
valid-palindrome-ii
Simple python Two-Pointer approach
VidaSolitaria
0
1
valid palindrome ii
680
0.393
Easy
11,248
https://leetcode.com/problems/valid-palindrome-ii/discuss/2806815/Python-Solution-with-Time-and-Space-complexity-explained.
class Solution: def validPalindrome(self, s: str) -> bool: l = 0 r = len(s) - 1 while l <= r: if s[l] == s[r]: l += 1 r -= 1 else: return (self.validPalindromeHelper(s, l + 1, r) or self.validPalindromeHelper(s, l, r - 1)) return True def validPalindromeHelper(self, s:str, l: int, r: int) -> bool: while l <= r: if s[l] != s[r]: return False l += 1 r -= 1 return True
valid-palindrome-ii
Python Solution with Time and Space complexity explained.
raghupalash
0
5
valid palindrome ii
680
0.393
Easy
11,249
https://leetcode.com/problems/valid-palindrome-ii/discuss/2789449/Python-recursive-solution
class Solution: def validPalindrome(self, s: str) -> bool: def isPallin(p1, p2, k): if p1 == p2 or p1 > p2: return k < 2 if k > 1: return False if s[p1] == s[p2]: res = isPallin(p1+1, p2-1, k) else: res = isPallin(p1+1, p2, k+1) or isPallin(p1, p2-1, k+1) return res return isPallin(0, len(s)-1, 0)
valid-palindrome-ii
Python recursive solution
ankurkumarpankaj
0
4
valid palindrome ii
680
0.393
Easy
11,250
https://leetcode.com/problems/valid-palindrome-ii/discuss/2782277/Solution-using-while-loop-and-check_valid-function
class Solution: def validPalindrome(self, s: str) -> bool: # create check_valid function: def check_valid(s,i,j): # loop through index of s but make sure to stay inbounds of index: while i < j: # check if the first index character and last index character !=: if s[i]!= s[j]: # if they don't equal, return false: return False # if they do equal: elif s[i] == s[j]: # add one to i: i+=1 # subtract 1 from j: j-=1 # return True: return True # set i to 0: i = 0 # set j to last index of s: j = len(s)-1 # check while first character and last character !=: while i < j: if s[i]!=s[j]: # execute check valid function: return check_valid(s,i,j-1) or check_valid(s,i+1, j) # add one to i i+=1 # subtract 1 from j: j-=1 # return True: return True
valid-palindrome-ii
Solution using while loop and check_valid function
NavarroKU
0
3
valid palindrome ii
680
0.393
Easy
11,251
https://leetcode.com/problems/valid-palindrome-ii/discuss/2710261/Python-or-Two-Pointer
class Solution: def isPal(self,temp,ind): temp.pop(ind) return temp[::-1] == temp def validPalindrome(self, s: str) -> bool: if s == s[::-1]: return True i = 0 j = len(s)-1 temp = list(s) delCnt = 0 while i<j and delCnt<1: if s[i] == s[j]: i+=1 j-=1 elif self.isPal(temp,i): return True else: temp = list(s) if self.isPal(temp,j): return True else: return False return True
valid-palindrome-ii
Python | Two Pointer
PrasadChaskar
0
12
valid palindrome ii
680
0.393
Easy
11,252
https://leetcode.com/problems/valid-palindrome-ii/discuss/2688001/Long-solution...
class Solution: def validPalindrome(self, s: str) -> bool: l , r = 0, len(s)-1 chance = 1 while r > l: if s[l] == s[r]: l += 1 r -= 1 else: chance -= 1 if chance < 0: return False s1 = s[:l] + s[l+1:] s2 = s[:r] + s[r+1:] if s1 != s1[::-1] and s2 != s2[::-1]: return False if s1 == s1[::-1]: l += 1 else: r -= 1 return True
valid-palindrome-ii
Long solution...
zhuoya-li
0
4
valid palindrome ii
680
0.393
Easy
11,253
https://leetcode.com/problems/valid-palindrome-ii/discuss/2655327/Python-Solution-O(n)-time-complexity-and-O(n)-space-complexity-using-Two-pointers-technique
class Solution: def validPalindrome(self, s: str) -> bool: left = 0 right = len(s) - 1 while right > left: if s[right] == s[left]: right -= 1 left += 1 else: return self.validsub(s,right) or self.validsub(s,left) return True def validsub(self,s,index): s_list = list(s) s_list.pop(index) left = 0 right = len(s_list) - 1 while right > left: if s_list[right] == s_list[left]: right -= 1 left += 1 else: return False return True
valid-palindrome-ii
Python Solution O(n) time complexity and O(n) space complexity using Two pointers technique
Furat
0
64
valid palindrome ii
680
0.393
Easy
11,254
https://leetcode.com/problems/valid-palindrome-ii/discuss/2463063/Python-or-Faster-than-99.86
class Solution: def validPalindrome(self, s: str) -> bool: new_s = s[::-1] if s == new_s: return True def compare(s1, s2): return s1 == s2 for i in range(len(s)): if s[i] != new_s[i]: tmp_2 = new_s[:i] + new_s[i+1:] tmp = s[:i] + s[i+1:] if compare(tmp, tmp[::-1]) or compare(tmp_2, tmp_2[::-1]): return True else: return False
valid-palindrome-ii
Python | Faster than 99.86%
pivovar3al
0
169
valid palindrome ii
680
0.393
Easy
11,255
https://leetcode.com/problems/valid-palindrome-ii/discuss/2312754/Plain-Simple-Solution-2-Approach
class Solution(object): def validPalindrome(self, s): """ :type s: str :rtype: bool """ l = 0 r = len(s)-1 while l<=r: if s[l]!= s[r]: skipl,skipr = s[l+1:r+1],s[l:r] if skipl == s[l+1:r+1][::-1] or skipr == s[l:r][::-1]: return True else: return False else: l+=1 r-=1 return True
valid-palindrome-ii
Plain Simple Solution 2 Approach
Abhi_009
0
103
valid palindrome ii
680
0.393
Easy
11,256
https://leetcode.com/problems/valid-palindrome-ii/discuss/2312754/Plain-Simple-Solution-2-Approach
class Solution: def validPalindrome(self, s: str) -> bool: i = 0 j = len(s)-1 flag = True while i<=j: if s[i] == s[j]: i+=1 j-=1 elif s[i]!=s[j] and flag and s[j]==s[i+1]: i+=1 flag = False elif s[i]!=s[j] and flag and s[j] != s[i+1]: j-=1 flag = False elif s[i]!=s[j] and not flag: return False return True
valid-palindrome-ii
Plain Simple Solution 2 Approach
Abhi_009
0
103
valid palindrome ii
680
0.393
Easy
11,257
https://leetcode.com/problems/valid-palindrome-ii/discuss/2256744/Python-oror-Easy-Solution
class Solution: def validPalindrome(self, s: str) -> bool: if s == s[::-1]: return True left = 0 right = len(s)-1 while left < right: if s[left] != s[right]: leftstring = s[:left]+s[left+1:] rightstring = s[:right]+s[right+1:] return leftstring == leftstring[::-1] or rightstring == rightstring[::-1] left += 1 right -= 1 return True
valid-palindrome-ii
Python || Easy Solution
dyforge
0
84
valid palindrome ii
680
0.393
Easy
11,258
https://leetcode.com/problems/valid-palindrome-ii/discuss/2055293/Python3-using-single-for
class Solution: def validPalindrome(self, s: str) -> bool: s = list(s) j = len(s) - 1 for i in range(len(s)): if s[i] != s[j]: sDeleted = s[i] s.pop(i) if s == s[::-1]: return True else: s.insert(i, sDeleted) s.pop(j) return s == s[::-1] j -= 1 return True
valid-palindrome-ii
[Python3] using single for
Shiyinq
0
65
valid palindrome ii
680
0.393
Easy
11,259
https://leetcode.com/problems/valid-palindrome-ii/discuss/1906828/Python3-Solution-with-using-two-pointers
class Solution: def verify(self, s, left, right, is_deleted): while left <= right: if s[left] == s[right]: left += 1 right -= 1 else: if is_deleted: return False return self.verify(s, left, right - 1, True) or self.verify(s, left + 1, right, True) return True def validPalindrome(self, s: str) -> bool: return self.verify(s, 0, len(s) - 1, False)
valid-palindrome-ii
[Python3] Solution with using two-pointers
maosipov11
0
14
valid palindrome ii
680
0.393
Easy
11,260
https://leetcode.com/problems/valid-palindrome-ii/discuss/1906187/Pythonor-TCO(N)SCO(1)-or-Without-recursion-or-Easy-to-understand
class Solution(object): def validPalindrome(self, s): left = 0 right = len(s) - 1 while left < right: if s[left] != s[right]: one = s[left:right] two = s[left+1 : right+1] return one == one[::-1] or two == two[::-1] left+=1 right-=1 return True
valid-palindrome-ii
Python| TC=O(N)/SC=O(1) | Without recursion | Easy to understand
Patil_Pratik
0
31
valid palindrome ii
680
0.393
Easy
11,261
https://leetcode.com/problems/valid-palindrome-ii/discuss/1905984/Python-Simple-Solution
class Solution: def validPalindrome(self, s: str) -> bool: def checkPalindrome(i,j,s): while i < j: if s[i] != s[j]: return False i+=1 j-=1 return True i = 0 j = len(s) - 1 while i < j: if s[i] != s[j]: one = checkPalindrome(i,j-1,s) two = checkPalindrome(i+1,j,s) return one or two i += 1 j -= 1 return True
valid-palindrome-ii
[Python] Simple Solution
abhijeetmallick29
0
17
valid palindrome ii
680
0.393
Easy
11,262
https://leetcode.com/problems/valid-palindrome-ii/discuss/1905639/Python-Solutionor-T%3AO(n)orS%3AO(1)
class Solution: def validPalindrome(self, s: str) -> bool: def is_palindrome(left, right): while left < right: if s[left] != s[right]: return False left += 1 right -= 1 return True l, r = 0, len(s) - 1 while l < r: if s[l] != s[r]: return is_palindrome(l + 1, r) or is_palindrome(l, r - 1) l += 1 r -= 1 return True
valid-palindrome-ii
Python Solution| T:O(n)|S:O(1)
pradeep288
0
17
valid palindrome ii
680
0.393
Easy
11,263
https://leetcode.com/problems/valid-palindrome-ii/discuss/1905442/Intuitive-Python-Solution
class Solution: def validPalindrome(self, s: str) -> bool: l, r = 0, len(s)-1 while l < r: if s[l] != s[r]: temp = s[:l] + s[l+1:] # remove the char at index l if self.isPalindrome(temp): return True elif r < len(s)-1: temp = s[:r] + s[r+1:] # remove char at index r elif r == len(s)-1: temp = s[:r] # remove char at index r return self.isPalindrome(temp) l += 1 r -= 1 return True def isPalindrome(self, s): l, r = 0, len(s)-1 while l < r: if s[l] != s[r]: return False l += 1 r -= 1 return True
valid-palindrome-ii
Intuitive Python Solution
Mowei
0
31
valid palindrome ii
680
0.393
Easy
11,264
https://leetcode.com/problems/valid-palindrome-ii/discuss/1905286/Python-clean-and-easy-solution
class Solution: def validPalindrome(self, s: str) -> bool: ptr1 = 0 ptr2 = len(s) - 1 modify1 = "" modify2 = "" while ptr1 <= ptr2: if s[ptr1] != s[ptr2]: modify1 = s[:ptr1] + s[ptr1+1:] modify2 = s[:ptr2] + s[ptr2+1:] return modify1 == modify1[::-1] or modify2 == modify2[::-1] ptr1 += 1 ptr2 -= 1 return True
valid-palindrome-ii
Python clean and easy solution
alishak1999
0
66
valid palindrome ii
680
0.393
Easy
11,265
https://leetcode.com/problems/valid-palindrome-ii/discuss/1905050/Check-Plaindrome-II-Two-Pointer-approach-to-filter-the-culprit-part-of-String
class Solution: def validPalindrome(self, s: str) -> bool: def palichecker(st): k = 0 l = len(st)-1 while k <=l: if st[k] == st[l]: k+=1 l-=1 else: return False return True i = 0 j = len(s)-1 while i<=j: if s[i] == s[j]: i+=1 j-=1 else: break if i >=j: return True checkstr = s[i:j+1] for i in range(len(checkstr)): # print(checkstr[:i] + checkstr[i+1:]) result = palichecker(checkstr[:i] + checkstr[i+1:]) if result: return True return False
valid-palindrome-ii
Check Plaindrome II Two Pointer approach to filter the culprit part of String
Jatin-kaushik
0
42
valid palindrome ii
680
0.393
Easy
11,266
https://leetcode.com/problems/valid-palindrome-ii/discuss/1904990/Python3-greedy-check
class Solution: def validPalindrome(self, s: str) -> bool: for i in range(len(s)//2): if s[i] != s[~i]: ss = s[i:~i+1 or None] return ss[1:] == ss[1:][::-1] or ss[:-1] == ss[:-1][::-1] return True
valid-palindrome-ii
[Python3] greedy check
ye15
0
42
valid palindrome ii
680
0.393
Easy
11,267
https://leetcode.com/problems/valid-palindrome-ii/discuss/1848205/PYTHON-RECURSIVE-two-pointer-approach-with-explanation-(440ms)
class Solution: def validPalindrome(self, s: str) -> bool: LENGTH = len( s ); #Go into the recursive function return self.helper( s, 0 , LENGTH - 1, True ); #Pass in the left end pointer and the right end pointer #forgiveCollision is used to determine if we have removed a character def helper( self, s, leftP , rightP , forgiveCollision ): #Base case #If our pointers are touching or have passed each other #We return true if rightP - leftP <= 0: return True; #Otherwise, we look at both characters firstChar = s[ leftP ]; secondChar = s[ rightP ]; #If they match, move both pointers closer to the center if firstChar == secondChar: return self.helper( s, leftP + 1, rightP - 1, forgiveCollision ); #If they don't, and we can forgive the collision, #Keep searching but with forgiveCollision turned to False elif (firstChar != secondChar) and forgiveCollision: #Try moving the left end pointer if self.helper( s, leftP + 1, rightP, False): return True; #And then if that fails, move the right end pointer else: return self.helper( s, leftP, rightP - 1, False); #If we have a mismatch, and forgiveCollision is False, #We return False else: return False;
valid-palindrome-ii
PYTHON RECURSIVE two pointer approach with explanation (440ms)
greg_savage
0
112
valid palindrome ii
680
0.393
Easy
11,268
https://leetcode.com/problems/valid-palindrome-ii/discuss/1835800/Python-simple-and-elegant!-Recursive-with-no-additional-function
class Solution(object): def validPalindrome(self, s, k=1): l, r = 0, len(s)-1 while l < r: if s[l] != s[r]: if k == 0: return False else: return self.validPalindrome(s[l:r],k-1) or self.validPalindrome(s[l+1:r+1],k-1) l += 1 r -= 1 return True
valid-palindrome-ii
Python - simple and elegant! Recursive with no additional function
domthedeveloper
0
265
valid palindrome ii
680
0.393
Easy
11,269
https://leetcode.com/problems/valid-palindrome-ii/discuss/1776307/Python-O(n)-recursive-solution-(intuition)
class Solution: def validPalindrome(self, s): return self.is_palindrome(s, 0, len(s) - 1, 1) def is_palindrome(self, s, left, right, removals_remaining): while left < right: if s[left] != s[right]: if removals_remaining == 0: return False return self.is_palindrome(s, left + 1, right, removals_remaining - 1) or \ self.is_palindrome(s, left, right - 1, removals_remaining - 1) left += 1 right -= 1 return True
valid-palindrome-ii
Python O(n) recursive solution (intuition)
user9860u
0
290
valid palindrome ii
680
0.393
Easy
11,270
https://leetcode.com/problems/valid-palindrome-ii/discuss/1718294/Runtime%3A-167-ms-faster-than-56.81-of-Python3
class Solution: def validPalindrome(self, s: str) -> bool: if s == s[::-1]: return True left_start = 0 right_start = len(s) - 1 while left_start < right_start: if s[left_start] != s[right_start]: remove_left = list(s) remove_right = list(s) remove_left.pop(left_start) remove_right.pop(right_start) if remove_left == remove_left[::-1] or remove_right == remove_right[::-1]: return True return False left_start += 1 right_start -= 1
valid-palindrome-ii
Runtime: 167 ms, faster than 56.81% of Python3
khalidhassan3011
0
118
valid palindrome ii
680
0.393
Easy
11,271
https://leetcode.com/problems/valid-palindrome-ii/discuss/1718143/Python3-or-Two-Pointers-%2B-Brute-Force
class Solution: def validPalindrome(self, s: str) -> bool: n=len(s) left,right=0,n-1 cnt=0 while left<=right: if s[left]==s[right]: left+=1 right-=1 else: if cnt==1: return False else: if self.check(s,left+1,right): left+=1 elif self.check(s,left,right-1): right-=1 else: return False cnt+=1 return True def check(self,s,left,right): if s[left:right+1]==s[left:right+1][::-1]: return True return False
valid-palindrome-ii
[Python3] | Two Pointers + Brute Force
swapnilsingh421
0
141
valid palindrome ii
680
0.393
Easy
11,272
https://leetcode.com/problems/baseball-game/discuss/380544/Two-Solutions-in-Python-3-(beats-~99)
class Solution: def calPoints(self, s: List[str]) -> int: p = [] for i in s: if i == 'C': p.pop() elif i == 'D': p.append(2*p[-1]) elif i == '+': p.append(p[-1]+p[-2]) else: p.append(int(i)) return sum(p)
baseball-game
Two Solutions in Python 3 (beats ~99%)
junaidmansuri
7
928
baseball game
682
0.737
Easy
11,273
https://leetcode.com/problems/baseball-game/discuss/380544/Two-Solutions-in-Python-3-(beats-~99)
class Solution: def calPoints(self, s: List[str]) -> int: s, i = [int(s[i]) if s[i] not in 'CD+' else s[i] for i in range(len(s))]+[''], 1 while s[i] != '': if s[i] == 'C': del s[i-1], s[i-1] i -= 1 continue i += 1 for i in range(len(s)-1): if s[i] == 'D': s[i] = 2*s[i-1] if s[i] == '+': s[i] = s[i-2] + s[i-1] return sum(s[:len(s)-1]) - Junaid Mansuri (LeetCode ID)@hotmail.com
baseball-game
Two Solutions in Python 3 (beats ~99%)
junaidmansuri
7
928
baseball game
682
0.737
Easy
11,274
https://leetcode.com/problems/baseball-game/discuss/2102494/Python3-Runtime%3A-52ms-61.18-Memory%3A-14.1mb-73.54
class Solution: # O(n) || O(n); where n is the number of scores # 52ms 61.18%, memory: 14.1mb 73.54% def calPoints(self, ops: List[str]) -> int: array = ops if not array: return 0 stack = [] nextPrev, prev = None, None for i in array: if i[0] == '-' or i.isnumeric(): stack.append(int(i)) prev = stack[-1] nextPrev = stack[-2] if len(stack) > 1 else None elif i == 'C': if stack: stack.pop() prev = stack[-1] if stack else None nextPrev = stack[-2] if len(stack) > 1 else None elif i == 'D': if stack: stack.append(prev * 2) prev = stack[-1] nextPrev = stack[-2] if len(stack) > 1 else None elif i == '+': if stack: stack.append(nextPrev + prev) prev = stack[-1] nextPrev = stack[-2] if len(stack) > 1 else None return sum(stack)
baseball-game
Python3 Runtime: 52ms 61.18%, Memory: 14.1mb 73.54%
arshergon
1
45
baseball game
682
0.737
Easy
11,275
https://leetcode.com/problems/baseball-game/discuss/1932354/Simple-Python-Solution.-O(1)-space-complexity-and-O(n)-time-complexity
class Solution: def calPoints(self, ops: List[str]) -> int: i = j = 0 while j < len(ops): if ops[j] == "C": i -= 2 elif ops[j] == "D": ops[i] = int(ops[i-1])*2 elif ops[j] == "+": ops[i] = int(ops[i-1]) + int(ops[i-2]) else: ops[i] = int(ops[j]) i += 1 j += 1 return sum(ops[:i])
baseball-game
Simple Python Solution. O(1) space complexity and O(n) time complexity
VicV13
1
19
baseball game
682
0.737
Easy
11,276
https://leetcode.com/problems/baseball-game/discuss/1931949/93.71-faster-10-lines-of-code-in-python
class Solution: def calPoints(self, ops: List[str]) -> int: rec = [] for i in ops: if i == 'C' and rec: rec.pop() elif i == 'D' and len(rec) >= 1: a = rec[-1] rec.append(2 * a) elif i == '+' and len(rec) >= 2: a = rec[-1] b = rec[-2] rec.append(b + a) else: rec.append(int(i)) return sum(rec)
baseball-game
93.71% faster 10 lines of code in python
ankurbhambri
1
38
baseball game
682
0.737
Easy
11,277
https://leetcode.com/problems/baseball-game/discuss/1611586/Python3-Solution-Memory-Usage-less-than-98
class Solution: def calPoints(self, ops: List[str]) -> int: stack = [] for i in ops: if i == 'D': a = int(stack.pop()) stack.extend([a,2*a]) elif i == 'C': stack.pop() elif i == '+': a = int(stack.pop()) b = int(stack.pop()) stack.extend([b,a,a+b]) else: stack.append(int(i)) return sum(stack)
baseball-game
Python3 Solution Memory Usage less than 98%
risabhmishra19
1
101
baseball game
682
0.737
Easy
11,278
https://leetcode.com/problems/baseball-game/discuss/1057722/Python3-simple-solution-using-%22list%22
class Solution: def calPoints(self, ops: List[str]) -> int: l = [] for i in ops: if i == 'C': l.pop() elif i == 'D': l.append(l[-1] * 2) elif i == '+': l.append(l[-1] + l[-2]) else: l.append(int(i)) return sum(l)
baseball-game
Python3 simple solution using "list"
EklavyaJoshi
1
99
baseball game
682
0.737
Easy
11,279
https://leetcode.com/problems/baseball-game/discuss/2848355/682.-Baseball-Game-Python-Solution
class Solution: def calPoints(self, operations: List[str]) -> int: score = [] ans = 0 for i in range(int(len(operations))): if (operations[i] == "C"): if score: score.pop() continue if (operations[i] == 'D'): score.append(int(score[-1]*2)) continue if (operations[i] == '+'): ans = int(score[-2]) + int(score[-1]) score.append(ans) continue else: temp = int(operations[i]) score.append(temp) final = 0 for k in score: final = final + k return final
baseball-game
✅ 682. Baseball Game - Python Solution
Brian_Daniel_Thomas
0
2
baseball game
682
0.737
Easy
11,280
https://leetcode.com/problems/baseball-game/discuss/2830800/simple-or-stack-based-or-python
class Solution(object): def calPoints(self, operations): """ :type operations: List[str] :rtype: int """ stack = [] for op in operations: if op.lstrip('-+').isdigit(): stack.append(int(op)) elif op == 'C': stack.pop(-1) elif op == "D": stack.append(stack[-1]*2) elif op == "+": val = stack[-1] + stack[-2] stack.append(val) return sum(stack)
baseball-game
simple | stack based | python
YousDaoud
0
1
baseball game
682
0.737
Easy
11,281
https://leetcode.com/problems/baseball-game/discuss/2825246/the-faster-solution-using-python-(faster-than-98.53-of-solution-)
class Solution: def calPoints(self, operations: List[str]) -> int: stack = [] for operation in operations: if operation == '+': stack.append(stack[-1]+stack[-2]) elif operation == 'D': stack.append(stack[-1]*2) elif operation == 'C': stack.pop() else: stack.append(int(operation)) return sum(stack)
baseball-game
the faster solution using python (faster than 98.53% of solution )
Osama_Qutait
0
2
baseball game
682
0.737
Easy
11,282
https://leetcode.com/problems/baseball-game/discuss/2816533/Basic-python-sol
class Solution: def calPoints(self, operations: List[str]) -> int: res = [] for op in operations: if op not in '+DC': res.append(int(op)) elif op == 'C': res = res[:-1] elif op == 'D': res.append(int(res[-1])*2) elif op == '+': res.append((int(res[-1]) + int(res[-2]))) print(res) return sum([int(x) for x in res])
baseball-game
Basic python sol
macgeargear
0
2
baseball game
682
0.737
Easy
11,283
https://leetcode.com/problems/baseball-game/discuss/2803566/My-solution-beat-96.54-submitted
class Solution: def calPoints(self, operations: List[str]) -> int: t = [] for i in range(len(operations)): if operations[i]=="D": t.append(t[-1]*2) elif operations[i]=="C": t.pop() elif operations[i]=="+": t.append(t[-1]+t[-2]) else: t.append(int(operations[i])) return sum(t)
baseball-game
My solution beat 96.54% submitted
diamoussa2014
0
3
baseball game
682
0.737
Easy
11,284
https://leetcode.com/problems/baseball-game/discuss/2738534/Beats-98.20-conditional-structure-easy-to-understand
class Solution: def calPoints(self, operations: List[str]) -> int: stack = [] def getResult(i): if i == "C": return stack.pop() if i == "D": return stack.append(2 * stack[-1]) if i == "+": return stack.append(stack[-1] + stack[-2]) for i in operations: if i.strip('-').isdigit(): stack.append(int(i)) else: getResult(i) return sum(stack)
baseball-game
Beats 98.20%, conditional structure, easy to understand
karanvirsagar98
0
2
baseball game
682
0.737
Easy
11,285
https://leetcode.com/problems/baseball-game/discuss/2710999/Python-Easy-to-understand
class Solution: def is_number(self,s): try: float(s) return True except ValueError: return False def calPoints(self, operations: List[str]) -> int: st = [] n = len(operations) for i in operations: if self.is_number(i): j = float(i) st.append(j) if i == '+': num1 = st.pop() num2 = st.pop() summ = num1+num2 st.append(num2) st.append(num1) st.append(summ) if i == 'D': num1 = st.pop() d = num1 * 2 st.append(num1) st.append(d) if i == 'C': st.pop() return int(sum(st))
baseball-game
Python Easy to understand
piyush_54
0
2
baseball game
682
0.737
Easy
11,286
https://leetcode.com/problems/baseball-game/discuss/2687091/BASEBALL-GAME-python-solution-0(n)-complexity
class Solution: def calPoints(self,p: List[str]) -> int: l=[] for i in range(len(p)): if p[i]=='+' and len(l)>2: l.append(l[-1]+l[-2]) elif p[i]=='+' and len(l)<=2: l.append(sum(l)) elif p[i]=='C': l.pop() elif p[i]=='D': l.append(2*l[-1]) else: l.append(int(p[i])) return sum(l)
baseball-game
BASEBALL GAME python solution 0(n) complexity
shreya_singh1
0
1
baseball game
682
0.737
Easy
11,287
https://leetcode.com/problems/baseball-game/discuss/2678625/Python3-Simple-Using-Match..Case
class Solution: def calPoints(self, operations: List[str]) -> int: stack = [] for command in operations: match command: case '+': stack.append(stack[-1]+stack[-2]) case 'D': stack.append(stack[-1]*2) case 'C': stack.pop() case other: stack.append(int(command)) return reduce(lambda a, b: a+b, stack) if stack else 0
baseball-game
Python3 Simple Using Match..Case
Mbarberry
0
3
baseball game
682
0.737
Easy
11,288
https://leetcode.com/problems/baseball-game/discuss/2649844/Simple-Python-solution-with-if-else-with-explanation
class Solution: def calPoints(self, operations: List[str]) -> int: # First element of the string, always has to be numeric, hence new_list = [int(operations[0])] for i in range(1, len(operations)): # Chop the last entry if operations[i] == 'C': new_list.pop() # Double the last entry elif operations[i] == 'D': new_list.append(new_list[-1] * 2) # Add the last 2 entries elif operations[i] == '+': new_list.append(sum(new_list[-2:])) else: # Convert str -> int and append new_list.append(int(operations[i])) return sum(new_list)
baseball-game
Simple Python solution with if-else with explanation
code_snow
0
11
baseball game
682
0.737
Easy
11,289
https://leetcode.com/problems/baseball-game/discuss/2500157/Python3-Fast-easy
class Solution: def calPoints(self, ops: List[str]) -> int: ans = [] for x in ops: try: ans.append(int(x)) except: if x=="C": ans.pop() elif x=="D": ans.append(int(ans[-1])*2) else: ans.append(int(ans[-1])+ int(ans[-2])) return sum(ans)
baseball-game
Python3 Fast easy
Yodawgz0
0
20
baseball game
682
0.737
Easy
11,290
https://leetcode.com/problems/baseball-game/discuss/2490589/Python3-Solution-oror-Stacks-oror-Easy-oror-75-Faster
class Solution: def calPoints(self, ops: List[str]) -> int: new = [] for i in range(0,len(ops)): if ops[i] == 'C': pop = int(new.pop()) elif ops[i] == 'D' and len(new) != 0 : if ops[i-1] == 'C': new.append(2 * int(new [-1])) else: new.append(2 * int(new[-1])) elif ops[i] == '+': new.append(int(new[-2]) + int(new [-1])) else: new.append(ops[i]) sum = 0 for i in new: sum += int(i) return sum
baseball-game
Python3 Solution || Stacks || Easy || 75% Faster
shashank_shashi
0
16
baseball game
682
0.737
Easy
11,291
https://leetcode.com/problems/baseball-game/discuss/2474954/Python-97.60-faster-or-Simplest-solution-with-explanation-or-Beg-to-Adv-or-Stack
class Solution: def calPoints(self, ops: List[str]) -> int: stack = [] # taking an empty stack. prod = 2 # taking a variable to double a provided number. prev_sum = 0 # taking a variable to have sum of previous elems of the stack. for i in range(len(ops)): # Traversing through the provided list. if ops[i] is not "C" and ops[i] is not "D" and ops[i] is not "+": # if we are having other then a number then we`ll just add it to stack. stack.append(int(ops[i])) # pushing elements to the stack and making it as int bcz originally it is provided as char. elif ops[i] is "C": # if its other then a number we`ll check what it is. stack.pop() # removing the previous record, we as coder refer it as a last element in the stack. elif ops[i] is "D": # if its other then a number we`ll check what it is. prod*=int(stack[-1]) # Again making stack element as a integer for performing product operation. stack.append(prod) # Pushing the product to the stack. prod=2 # reseting variable. elif ops[i] is "+": # if its other then a number we`ll check what it is. prev_sum = int(stack[-2]) + int(stack[-1]) # Again as we have list elem as char, to perform adding we have to change it to int. stack.append(prev_sum) # Pushing the sum to the stack. prev_sum=0 # reseting variable. return sum(stack) # Returning the sum of all the scores on the record(sum of elements in the stack).
baseball-game
Python 97.60% faster | Simplest solution with explanation | Beg to Adv | Stack
rlakshay14
0
21
baseball game
682
0.737
Easy
11,292
https://leetcode.com/problems/baseball-game/discuss/2384418/Python-oror-easy-solutionoror-TC%3AO(n)-SC%3A-O(n)
class Solution: def calPoints(self, ops: List[str]) -> int: stack=[] for i in range(len(ops)): if ops[i]=="C": stack.pop(-1) elif ops[i]=="D": stack.append((stack[-1]*2)) elif ops[i]=="+": stack.append((stack[-1])+(stack[-2])) else: stack.append(int(ops[i])) return sum(stack)
baseball-game
Python || easy-solution|| TC:O(n) , SC: O(n)
shikhar_srivastava391
0
16
baseball game
682
0.737
Easy
11,293
https://leetcode.com/problems/baseball-game/discuss/2178856/Python-Solution-Beginner-Friendly
class Solution: def calPoints(self, ops: List[str]) -> int: l=[] for i in range(len(ops)): if ops[i]=="+": l.append(l[-2]+l[-1]) elif ops[i]=="D": l.append(l[-1]*2) elif ops[i]=="C": l.pop() else: l.append(int(ops[i])) return sum(l)
baseball-game
Python Solution- Beginner Friendly
T1n1_B0x1
0
29
baseball game
682
0.737
Easy
11,294
https://leetcode.com/problems/baseball-game/discuss/2031432/Easy
class Solution: def calPoints(self, ops: List[str]) -> int: a=[] for i in ops: if(i.isnumeric()): a.append(int(i)) elif(i.lstrip('-').isdigit()): a.append(int(i)) elif(i=="C"): a.remove(a[-1]) elif(i=="D"): a.append((a[-1])*2) elif(i=="+"): a.append((a[-1])+(a[-2])) if(len(a)>0): return sum(a) else: return 0
baseball-game
Easy
Durgavamsi
0
38
baseball game
682
0.737
Easy
11,295
https://leetcode.com/problems/baseball-game/discuss/1945296/Python-Easy-Python-Solution-Using-List
class Solution: def calPoints(self, ops: List[str]) -> int: result = [] for i in ops: if i == '+': result.append( result[-2] + result[-1] ) elif i == 'C': result.pop(-1) elif i == 'D': result.append( result[-1] * 2 ) else: result.append( int(i) ) return sum(result)
baseball-game
[ Python ] ✅✅ Easy Python Solution Using List ✌👍
ASHOK_KUMAR_MEGHVANSHI
0
42
baseball game
682
0.737
Easy
11,296
https://leetcode.com/problems/baseball-game/discuss/1934758/easy-python-code
class Solution: def calPoints(self, ops: List[str]) -> int: output = [] add = 0 for i in ops: if i == "C": output.pop() elif i == "D": output.append(output[-1]*2) elif i == "+": output.append(output[-1]+output[-2]) else: output.append(int(i)) for i in output: add += i return add
baseball-game
easy python code
dakash682
0
15
baseball game
682
0.737
Easy
11,297
https://leetcode.com/problems/baseball-game/discuss/1934090/(30-40)-Faster-and-Less-Memory-usage-than-other-Python3-submissions
class Solution: def calPoints(self, ops: List[str]) -> int: new_arr = [] for x in range(len(ops)): if ops[x].isdigit(): new_arr.append(float(ops[x])) elif ops[x] == "+": new_arr.append(new_arr[-1] + new_arr[-2]) elif ops[x] == "D": new_arr.append(new_arr[-1] * 2) elif ops[x] == "C": new_arr.pop() else: new_arr.append(float(ops[x])) return int(sum(new_arr))
baseball-game
(30-40)% Faster and Less Memory usage than other Python3 submissions
ruhiddin_uzb
0
13
baseball game
682
0.737
Easy
11,298
https://leetcode.com/problems/baseball-game/discuss/1933536/Python-or-EASY-TO-UNDERSTAND-or-Faster-than-99.56
class Solution: def calPoints(self, ops: List[str]) -> int: rec=[] temp=[] for i in ops: if i=='+': rec.append(rec[-1]+rec[-2]) elif i=='C': rec.pop() elif i=='D': rec.append(rec[-1]*2) else: rec.append(int(i)) return sum(rec)
baseball-game
Python | EASY-TO-UNDERSTAND | Faster than 99.56%
manav023
0
24
baseball game
682
0.737
Easy
11,299