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/a-number-after-a-double-reversal/discuss/1798270/1-Line-Python-Solution-oror-90-Faster-oror-Memory-less-than-90
class Solution: def isSameAfterReversals(self, num: int) -> bool: return True if str(num)[-1]!='0' or num==0 else False
a-number-after-a-double-reversal
1-Line Python Solution || 90% Faster || Memory less than 90%
Taha-C
0
31
a number after a double reversal
2,119
0.758
Easy
29,300
https://leetcode.com/problems/a-number-after-a-double-reversal/discuss/1791770/Python3-accepted-one-liner-solution
class Solution: def isSameAfterReversals(self, num: int) -> bool: return num == int(str(int(str(num)[::-1]))[::-1])
a-number-after-a-double-reversal
Python3 accepted one-liner solution
sreeleetcode19
0
29
a number after a double reversal
2,119
0.758
Easy
29,301
https://leetcode.com/problems/a-number-after-a-double-reversal/discuss/1695969/Python-3-1-line-O(1)-time-O(1)-space
class Solution: def isSameAfterReversals(self, num: int) -> bool: return num % 10 != 0 or num == 0
a-number-after-a-double-reversal
Python 3, 1 line, O(1) time, O(1) space
dereky4
0
56
a number after a double reversal
2,119
0.758
Easy
29,302
https://leetcode.com/problems/a-number-after-a-double-reversal/discuss/1690405/**-Python-code%3A-1-Linear
class Solution: def isSameAfterReversals(self, num: int) -> bool: return num==int(str(int(str(num)[::-1]))[::-1])
a-number-after-a-double-reversal
** Python code: 1-Linear
Anilchouhan181
0
19
a number after a double reversal
2,119
0.758
Easy
29,303
https://leetcode.com/problems/a-number-after-a-double-reversal/discuss/1683461/return-num-10-!-0-or-num-0-lessEOPgreater
class Solution: def isSameAfterReversals(self, num: int) -> bool: return num % 10 != 0 or num == 0
a-number-after-a-double-reversal
return num % 10 != 0 or num == 0 <EOP>
snagsbybalin
0
14
a number after a double reversal
2,119
0.758
Easy
29,304
https://leetcode.com/problems/a-number-after-a-double-reversal/discuss/1658533/Python-1-Liner-Simple
class Solution: def isSameAfterReversals(self, num: int) -> bool: return num < 10 or num % 10
a-number-after-a-double-reversal
Python 1 Liner Simple
dhnam2234
0
46
a number after a double reversal
2,119
0.758
Easy
29,305
https://leetcode.com/problems/a-number-after-a-double-reversal/discuss/1647456/Python3-1-line
class Solution: def isSameAfterReversals(self, num: int) -> bool: return num == 0 or num % 10
a-number-after-a-double-reversal
[Python3] 1-line
ye15
0
50
a number after a double reversal
2,119
0.758
Easy
29,306
https://leetcode.com/problems/execution-of-all-suffix-instructions-staying-in-a-grid/discuss/2838969/Python-Straight-forward-O(n-2)-solution-(still-fast-85)
class Solution: def executeInstructions(self, n: int, startPos: list[int], s: str) -> list[int]: def num_of_valid_instructions(s, pos, start, end): row, colon = pos k = 0 for i in range(start, end): cur = s[i] row += (cur == 'D') - (cur == 'U') colon += (cur == 'R') - (cur == 'L') if not (0 <= row < n and 0 <= colon < n): return k k += 1 return k ans = [] for i in range(len(s)): ans.append(num_of_valid_instructions(s, startPos, i, len(s))) return ans
execution-of-all-suffix-instructions-staying-in-a-grid
[Python] Straight-forward O(n ^ 2) solution (still fast - 85%)
Mark_computer
1
4
execution of all suffix instructions staying in a grid
2,120
0.836
Medium
29,307
https://leetcode.com/problems/execution-of-all-suffix-instructions-staying-in-a-grid/discuss/1696798/python-brute-force
class Solution: def executeInstructions(self, n: int, startPos: List[int], s: str) -> List[int]: d = {'U':(-1, 0),'D':(1, 0), 'R':(0, 1), 'L':(0, -1)} m = len(s) ans = [0]*m def isBounded(start, end): return (0<= start < n and 0<= end < n) for i in range(m): x, y = startPos for j in range(i, m): dx, dy = d[s[j]] x += dx; y += dy if not isBounded(x, y): break ans[i] += 1 return ans
execution-of-all-suffix-instructions-staying-in-a-grid
python brute force
abkc1221
1
82
execution of all suffix instructions staying in a grid
2,120
0.836
Medium
29,308
https://leetcode.com/problems/execution-of-all-suffix-instructions-staying-in-a-grid/discuss/1647470/Python3-brute-force
class Solution: def executeInstructions(self, n: int, startPos: List[int], s: str) -> List[int]: ans = [] for k in range(len(s)): i, j = startPos val = 0 for kk in range(k, len(s)): if s[kk] == 'L': j -= 1 elif s[kk] == 'R': j += 1 elif s[kk] == 'U': i -= 1 else: i += 1 if 0 <= i < n and 0 <= j < n: val += 1 else: break ans.append(val) return ans
execution-of-all-suffix-instructions-staying-in-a-grid
[Python3] brute-force
ye15
1
61
execution of all suffix instructions staying in a grid
2,120
0.836
Medium
29,309
https://leetcode.com/problems/execution-of-all-suffix-instructions-staying-in-a-grid/discuss/1647470/Python3-brute-force
class Solution: def executeInstructions(self, n: int, startPos: List[int], s: str) -> List[int]: @cache def fn(i, j, k): """Return valid number of instructions at (i, j) starting from kth.""" if k == len(s): return 0 if s[k] == 'L': j -= 1 elif s[k] == 'R': j += 1 elif s[k] == 'U': i -= 1 else: i += 1 if 0 <= i < n and 0 <= j < n: return 1 + fn(i, j, k+1) return 0 return [fn(*startPos, k) for k in range(len(s))]
execution-of-all-suffix-instructions-staying-in-a-grid
[Python3] brute-force
ye15
1
61
execution of all suffix instructions staying in a grid
2,120
0.836
Medium
29,310
https://leetcode.com/problems/execution-of-all-suffix-instructions-staying-in-a-grid/discuss/2792292/HOLY-COW!-Explained-trivial-python3-solution
class Solution: def executeInstructions(self, n: int, startPos: List[int], s: str) -> List[int]: ans = [] for i in range(len(s)): # create short version of instructions # for current iteration instructions = s[i:] cnt = 0 x, y = startPos[0], startPos[1] # for every instruction in this iteration for inst in instructions: # move if inst == "R": y += 1 elif inst == "L": y -= 1 elif inst == "D": x += 1 else: x -= 1 # check conditions if x < 0 or y < 0 or x >= n or y >= n: break # counting steps cnt += 1 ans.append(cnt) return ans
execution-of-all-suffix-instructions-staying-in-a-grid
HOLY COW! Explained trivial python3 solution
jestpunk
0
4
execution of all suffix instructions staying in a grid
2,120
0.836
Medium
29,311
https://leetcode.com/problems/execution-of-all-suffix-instructions-staying-in-a-grid/discuss/2778967/Easy-Python-Code
class Solution: def executeInstructions(self, n: int, startPos: List[int], s: str) -> List[int]: lenn=len(s) res=[0]*lenn def rec(i,j,steps,k): if i<0 or j<0 or i==n or j==n: return steps-1 if k==lenn: return steps if s[k]=='R': return rec(i,j+1,steps+1,k+1) if s[k]=='L': return rec(i,j-1,steps+1,k+1) if s[k]=='U': return rec(i-1,j,steps+1,k+1) if s[k]=='D': return rec(i+1,j,steps+1,k+1) for i in range(lenn): res[i]=rec(startPos[0],startPos[1],0,i) return res
execution-of-all-suffix-instructions-staying-in-a-grid
Easy Python Code
Chetan_007
0
1
execution of all suffix instructions staying in a grid
2,120
0.836
Medium
29,312
https://leetcode.com/problems/execution-of-all-suffix-instructions-staying-in-a-grid/discuss/2755985/python-easy-solutionoror-Bruteforce-approach
class Solution: def executeInstructions(self, n: int, startPos: List[int], s: str) -> List[int]: ans = [] r = startPos[0] c = startPos[1] count = 0 while s!='': for j in range(len(s)): if s[j]=="R": if c<n-1: c+=1 count+=1 else: ans.append(count) count = 0 break elif s[j]=="L": if c>0: c-=1 count+=1 else: ans.append(count) count = 0 break elif s[j]=="D": if r<n-1: r+=1 count+=1 else: ans.append(count) count = 0 break elif s[j]=="U": if r>0: r-=1 count+=1 else: ans.append(count) count = 0 break if count==len(s): ans.append(count) count = 0 r = startPos[0] c = startPos[1] s = s[1:] return ans
execution-of-all-suffix-instructions-staying-in-a-grid
✅✅python easy solution|| Bruteforce approach
chessman_1
0
3
execution of all suffix instructions staying in a grid
2,120
0.836
Medium
29,313
https://leetcode.com/problems/execution-of-all-suffix-instructions-staying-in-a-grid/discuss/2752939/Python-bruteforce
class Solution: def executeInstructions(self, n: int, startPos: List[int], s: str) -> List[int]: directions = {"R":(0,1),"L":(0,-1),"U":(-1,0),"D":(1,0)} res = [] for startingInstruction in range(len(s)): x,y = startPos successful_instructions = 0 for instruction in s[startingInstruction:]: dx,dy = directions[instruction] x,y = x+dx,y+dy if x >= 0 and x < n and y >= 0 and y < n: successful_instructions += 1 else: break res.append(successful_instructions) return res
execution-of-all-suffix-instructions-staying-in-a-grid
Python bruteforce
shriyansnaik
0
2
execution of all suffix instructions staying in a grid
2,120
0.836
Medium
29,314
https://leetcode.com/problems/execution-of-all-suffix-instructions-staying-in-a-grid/discuss/2700326/Python3-Store-FIRST-time-at-X-and-Y-positions-in-dictionary
class Solution: def executeInstructions(self, n: int, startPos: List[int], s: str) -> List[int]: fx, fy, m = {startPos[1] : 0}, {startPos[0]: 0}, {'U': (0, -1) , 'D': (0, 1), 'L': (-1, 0) , 'R': (1, 0)} ret = [] for i in reversed(range(len(s))): offx, offy = m[s[i]] fx = {k + offx: v + 1 for k, v in fx.items()} fy = {k + offy: v + 1 for k, v in fy.items()} fx.update({startPos[1] : 0}) fy.update({startPos[0] : 0}) mo = len(s) + 1 - i for d in [fx, fy]: for k, v in d.items(): if (k < 0 or k >= n) and v<mo: mo = v ret.insert(0, mo-1) return ret
execution-of-all-suffix-instructions-staying-in-a-grid
Python3 Store FIRST time at X and Y positions in dictionary
godshiva
0
6
execution of all suffix instructions staying in a grid
2,120
0.836
Medium
29,315
https://leetcode.com/problems/execution-of-all-suffix-instructions-staying-in-a-grid/discuss/2699569/Python3-Solution-nested-loops-beats-90
class Solution: def executeInstructions(self, n: int, startPos: List[int], s: str) -> List[int]: dict_ = {'R':1, 'D':1, 'L':-1, 'U':-1, } ans = [] for i in range(len(s)): m = 0 x, y = startPos for c in s[i:]: if c in ('R', 'L'): y += dict_[c] if y == n or y < 0: break else: m += 1 else: x += dict_[c] if x == n or x < 0: print('break') break else: m += 1 ans.append(m) return ans
execution-of-all-suffix-instructions-staying-in-a-grid
Python3 Solution - nested loops, beats 90%
sipi09
0
4
execution of all suffix instructions staying in a grid
2,120
0.836
Medium
29,316
https://leetcode.com/problems/execution-of-all-suffix-instructions-staying-in-a-grid/discuss/2698507/Python3-Simple-Solution
class Solution: def executeInstructions(self, n: int, startPos: List[int], s: str) -> List[int]: res = [] for i in range(len(s)): row, col = startPos tmp = 0 for inst in s[i:]: if inst == 'R' and col + 1 < n: tmp, col = tmp + 1, col + 1 elif inst == 'L' and col - 1 >= 0: tmp, col = tmp + 1, col - 1 elif inst == 'U' and row - 1 >= 0: tmp, row = tmp + 1, row - 1 elif inst == 'D' and row + 1 < n: tmp, row = tmp + 1, row + 1 else: break res.append(tmp) return res
execution-of-all-suffix-instructions-staying-in-a-grid
Python3 Simple Solution
mediocre-coder
0
3
execution of all suffix instructions staying in a grid
2,120
0.836
Medium
29,317
https://leetcode.com/problems/execution-of-all-suffix-instructions-staying-in-a-grid/discuss/2688270/Python
class Solution: def executeInstructions(self, n: int, startPos: List[int], s: str) -> List[int]: move = {'L': [0,-1], 'D': [1,0], 'U': [-1,0], 'R': [0,1]} res = [] for i in range(len(s)): counter = 0 x = startPos[0] y = startPos[1] for j in range(i, len(s)): if 0 <= x+ move[s[j]][0] < n and 0 <= y+move[s[j]][1] < n : x = x+ move[s[j]][0] y = y+ move[s[j]][1] counter +=1 else: break res.append(counter) return res
execution-of-all-suffix-instructions-staying-in-a-grid
Python
naveenraiit
0
3
execution of all suffix instructions staying in a grid
2,120
0.836
Medium
29,318
https://leetcode.com/problems/execution-of-all-suffix-instructions-staying-in-a-grid/discuss/2206750/C%2B%2B-Python-Kotlin-oror-Easy-Explained-Solution-oror-O(n2)
class Solution(object): def executeInstructions(self, n, startPos, s): li = [] count = 0; ini = startPos[0] inj = startPos[1] for i in range(len(s)): for j in range(i, len(s)): if s[j] == 'R' : startPos[1] += 1 elif s[j] == 'L' : startPos[1] -= 1 elif s[j] == 'U' : startPos[0] -= 1 elif s[j] == 'D' : startPos[0] += 1 if (startPos[1] > -1 and startPos[1] < n and startPos[0] > -1 and startPos[0] < n) : count += 1 else : startPos = [-1,-1] startPos = [ini, inj] li.append(count) count = 0 return li
execution-of-all-suffix-instructions-staying-in-a-grid
C++, Python, Kotlin || Easy Explained Solution || O(n^2)
r_o_xx_
0
24
execution of all suffix instructions staying in a grid
2,120
0.836
Medium
29,319
https://leetcode.com/problems/execution-of-all-suffix-instructions-staying-in-a-grid/discuss/2044450/Python-Easy-Solution
class Solution: def executeInstructions(self, n: int, startPos: List[int], s: str) -> List[int]: result = [] for i in range(len(s)): moves = s[i:] number_of_moves = 0 position = list(startPos) for move in moves: if move == "L": position[1] -= 1 if move == "R": position[1] += 1 if move == "U": position[0] -= 1 if move == "D": position[0] += 1 if position[0] >= n or position[1] >= n or position[0] < 0 or position[1] < 0: break number_of_moves += 1 result.append(number_of_moves) return result
execution-of-all-suffix-instructions-staying-in-a-grid
Python - Easy Solution
TrueJacobG
0
49
execution of all suffix instructions staying in a grid
2,120
0.836
Medium
29,320
https://leetcode.com/problems/execution-of-all-suffix-instructions-staying-in-a-grid/discuss/1939495/Python3-Brute-Force-Solution
class Solution: def executeInstructions(self, n: int, startPos: List[int], s: str) -> List[int]: output = [] ns = len(s) for i in range(ns): count = 0 Pos = [startPos[0], startPos[1]] for j in range(i, ns): if s[j] == 'L': Pos[1] -= 1 elif s[j] == 'R': Pos[1] += 1 elif s[j] == 'U': Pos[0] -= 1 elif s[j] == 'D': Pos[0] += 1 if Pos[0] < 0 or Pos[0] >= n: break if Pos[1] < 0 or Pos[1] >= n: break count += 1 output.append(count) return output
execution-of-all-suffix-instructions-staying-in-a-grid
[Python3] Brute Force Solution
terrencetang
0
22
execution of all suffix instructions staying in a grid
2,120
0.836
Medium
29,321
https://leetcode.com/problems/execution-of-all-suffix-instructions-staying-in-a-grid/discuss/1794625/Python-Simple-Brute-Force-Solution
class Solution: def executeInstructions(self, n: int, sp: List[int], s: str) -> List[int]: def move_up(pos): pos[0] -= 1 return pos def move_down(pos): pos[0] += 1 return pos def move_right(pos): pos[1] += 1 return pos def move_left(pos): pos[1] -= 1 return pos ans = [] funcs = { 'R': move_right, 'L': move_left, 'U': move_up, 'D': move_down } for i in range(len(s)): count = 0 temp = sp.copy() for j in range(i, len(s)): temp = funcs[s[j]](temp) if temp[0] >= 0 and temp[1] >= 0 and temp[0] < n and temp[1] < n: count += 1 else: break ans.append(count) return ans
execution-of-all-suffix-instructions-staying-in-a-grid
Python Simple Brute-Force Solution
dos_77
0
46
execution of all suffix instructions staying in a grid
2,120
0.836
Medium
29,322
https://leetcode.com/problems/execution-of-all-suffix-instructions-staying-in-a-grid/discuss/1695189/Python-O(m2)-using-imaginary-numbers
class Solution: def executeInstructions(self, n: int, startPos: List[int], s: str) -> List[int]: d = dict(U=-1, D=1, L=-1j, R=1j) start = startPos[0] + 1j*startPos[1] m = len(s) l = [0]*m for i in range(m): pos = start for j in range(i, m): pos += d[s[j]] if not (0 <= pos.real < n and 0 <= pos.imag < n): break l[i] += 1 return l
execution-of-all-suffix-instructions-staying-in-a-grid
Python O(m^2), using imaginary numbers
emwalker
0
49
execution of all suffix instructions staying in a grid
2,120
0.836
Medium
29,323
https://leetcode.com/problems/execution-of-all-suffix-instructions-staying-in-a-grid/discuss/1659660/Python-Super-Easy-but-Slow-.
class Solution: def executeInstructions(self, n: int, startPos: List[int], s: str) -> List[int]: arr=[] if(n==1): for i in range(len(s)): arr.append(0) return arr else: for a in range(len(s)): count=0 i=startPos[0] j=startPos[1] for k in range(a,len(s)): if s[k]=='R': j+=1 elif s[k]=='L': j-=1 elif s[k]=='D': i+=1 elif s[k]=='U': i-=1 if(j>=0) and (j<=n-1): if(i>=0) and (i<=n-1): count+=1 else: break else: break arr.append(count) return arr
execution-of-all-suffix-instructions-staying-in-a-grid
Python Super Easy but Slow .
alimlalani
0
54
execution of all suffix instructions staying in a grid
2,120
0.836
Medium
29,324
https://leetcode.com/problems/execution-of-all-suffix-instructions-staying-in-a-grid/discuss/1647557/Python3-Brute-Force
class Solution: def executeInstructions(self, n: int, startPos: List[int], s: str) -> List[int]: grid = [[0]*n for _ in range(n)] directions = {'R':(0,1),'L':(0,-1),'U':(-1,0),'D':(1,0)} l = len(s) ans = [0]*l temp = startPos.copy() for i in range(l): step = 0 startPos = temp.copy() for j in range(i,l): d = directions[s[j]] new_start = [startPos[0]+d[0],startPos[1]+d[1]] if 0<=new_start[0]<n and 0<=new_start[1]<n : step += 1 startPos = new_start else: break ans[i] = step return ans
execution-of-all-suffix-instructions-staying-in-a-grid
Python3 Brute-Force
AndrewHou
0
34
execution of all suffix instructions staying in a grid
2,120
0.836
Medium
29,325
https://leetcode.com/problems/intervals-between-identical-elements/discuss/1647480/Python3-prefix-sum
class Solution: def getDistances(self, arr: List[int]) -> List[int]: loc = defaultdict(list) for i, x in enumerate(arr): loc[x].append(i) for k, idx in loc.items(): prefix = list(accumulate(idx, initial=0)) vals = [] for i, x in enumerate(idx): vals.append(prefix[-1] - prefix[i] - prefix[i+1] - (len(idx)-2*i-1)*x) loc[k] = deque(vals) return [loc[x].popleft() for x in arr]
intervals-between-identical-elements
[Python3] prefix sum
ye15
9
1,100
intervals between identical elements
2,121
0.433
Medium
29,326
https://leetcode.com/problems/intervals-between-identical-elements/discuss/1706167/Python3-concise-code-with-visual-notes.
class Solution: def getDistances(self, arr: List[int]) -> List[int]: n = len(arr) d = defaultdict(list) for i, v in enumerate(arr): d[v].append(i) res = defaultdict(list) for v, idx in d.items(): ps = list(accumulate(idx, initial=0)) vals = [] idn = len(idx) for i, x in enumerate(idx): vals.append(i*x-ps[i] + ps[-1]-ps[i+1]-(idn-i-1)*x) res[v] = deque(vals) return [res[v].popleft() for v in arr]
intervals-between-identical-elements
Python3 concise code with visual notes.
danielxuforever
1
191
intervals between identical elements
2,121
0.433
Medium
29,327
https://leetcode.com/problems/intervals-between-identical-elements/discuss/1647662/Clear-Prefix-Sum-O(n)
class Solution: def getDistances(self, arr: List[int]) -> List[int]: """ The key fact is that result[i] = sum(i - indices below i) + sum(indices above i - i) This implies results[i] = sum(indices above i) - sum(indices below i) + i * (number of indices above i - number of indices below i) Fortunately, you can update the sums in constant time. """ indicesAbove = {} indicesBelow = {} runningSumAbove = {} runningSumBelow = {} result = [0] * len(arr) for i, n in enumerate(arr): if n not in indicesAbove: indicesAbove[n] = 1 indicesBelow[n] = 0 runningSumAbove[n] = i runningSumBelow[n] = 0 else: indicesAbove[n] += 1 runningSumAbove[n] += i # result = sum of numbers above - sum of #s below + pivot * (Nb - Na) for i, n in enumerate(arr): runningSumAbove[n] -= i indicesAbove[n] -= 1 result[i] = runningSumAbove[n] - runningSumBelow[n] + i * (indicesBelow[n] - indicesAbove[n]) indicesBelow[n] += 1 runningSumBelow[n] += i return result ```
intervals-between-identical-elements
Clear Prefix Sum O(n)
ealster2004
1
63
intervals between identical elements
2,121
0.433
Medium
29,328
https://leetcode.com/problems/intervals-between-identical-elements/discuss/2596930/Python-Explained-Preifx-Sum
class Solution: def getDistances(self, arr: List[int]) -> List[int]: # make a dict to save indices idces = collections.defaultdict(list) # search for all common numbers and make the computations for idx, num in enumerate(arr): # check whether we already found one idces[num].append(idx) # reset the array arr = [0 for _ in arr] # go through all of the numbers and calculate the sums for ls in idces.values(): # go through all other elements for idx, num in enumerate(ls): for idx2, num2 in enumerate(ls): if idx != idx2: arr[num] += abs(num-num2) return arr
intervals-between-identical-elements
[Python] - Explained Preifx-Sum
Lucew
0
35
intervals between identical elements
2,121
0.433
Medium
29,329
https://leetcode.com/problems/intervals-between-identical-elements/discuss/2596930/Python-Explained-Preifx-Sum
class Solution: def getDistances(self, arr: List[int]) -> List[int]: # make a dict to save indices idces = collections.defaultdict(list) # search for all common numbers and make the computations for idx, num in enumerate(arr): # check whether we already found one idces[num].append(idx) # go through all of the numbers and calculate the sums for ls in idces.values(): # make the prefix sum prefix = [ls[0] for _ in ls] n = len(ls) for idx, num in enumerate(ls[1:], 1): prefix[idx] = prefix[idx-1] + num # calculate the result for idx, num in enumerate(ls): # get the left part (current index - sum before the index) left = 0 if idx > 0: left = idx*num - prefix[idx-1] # get the right part (sum after the index, minus current index) right = 0 if idx < n-1: right = prefix[-1] - prefix[idx] - (n-1-idx)*num arr[num] = left + right return arr
intervals-between-identical-elements
[Python] - Explained Preifx-Sum
Lucew
0
35
intervals between identical elements
2,121
0.433
Medium
29,330
https://leetcode.com/problems/intervals-between-identical-elements/discuss/2404854/Why-my-solution-doesn't-work
class Solution: def getDistances(self, arr: List[int]) -> List[int]: idx = {} for i,n in enumerate(arr): idx[n] = idx.get(n, [])+[i] ans = [0]*len(arr) for l in idx.values(): tot = sum(l) length = len(l) for i in range(len(l)): ans[l[i]] = tot+l[i]*i-l[i]*(length-i) tot-=l[i]*2 return ans
intervals-between-identical-elements
Why my solution doesn't work?
li87o
0
27
intervals between identical elements
2,121
0.433
Medium
29,331
https://leetcode.com/problems/intervals-between-identical-elements/discuss/1651838/Python-Simple-Prefix-Sum-Solution
class Solution: def getDistances(self, arr: List[int]) -> List[int]: pre, hmap = [(0,0)]*len(arr), {} for i, val in enumerate(arr): if val not in hmap: hmap[val] = (0,0) //hmap[num] stores : [sum of indexes where num is present, frequency of occurence of num] hmap[val] = [hmap.get(val, 0)[0] + i, hmap.get(val, 0)[1] + 1] pre[i] = hmap[val] res = [0] * len(arr) for i, val in enumerate(arr): //right = (sum of indexes where arr[i] is present towards right of i) - ( (current index i) * (frequency of arr[i] from i+1 to n //left = (frequency of arr[i] before i ( excluding i, so -1)) * (current index i)- (sum of indexes where arr[i] is present from 0 to i, excluding i) right = (hmap[val][0] - pre[i][0]) - (hmap[val][1] - pre[i][1]) * i left = (pre[i][1]-1) * i - (pre[i][0] - i) res[i] = right + left return res
intervals-between-identical-elements
[Python] Simple Prefix Sum Solution
Saksham003
0
136
intervals between identical elements
2,121
0.433
Medium
29,332
https://leetcode.com/problems/intervals-between-identical-elements/discuss/1650782/Linear-solution-100-speed
class Solution: def getDistances(self, arr: List[int]) -> List[int]: val_idx = defaultdict(list) for i, n in enumerate(arr): val_idx[n].append(i) ans = [0] * len(arr) for lst_idx in val_idx.values(): len_lst_idx = len(lst_idx) if len_lst_idx == 1: continue sum_l, sum_r = 0, sum(lst_idx) len_lst_idx1 = len_lst_idx - 1 for i, n in enumerate(lst_idx): sum_r -= n ans[lst_idx[i]] = sum_r + n * (i * 2 - len_lst_idx1) - sum_l sum_l += n return ans
intervals-between-identical-elements
Linear solution, 100% speed
EvgenySH
0
97
intervals between identical elements
2,121
0.433
Medium
29,333
https://leetcode.com/problems/intervals-between-identical-elements/discuss/1648226/Simple-approach%3A-code-%2B-comments
class Solution: # computes for each element of the list the sum of intervals with other elements when their values are equal; returns computed sums in a list def getDistances(self, arr: List[int]) -> List[int]: # e1 e2 e3 -> e4 e5 e6 e7 # |--L---|-di-|----R----| # soi += di*(L-R) n=len(arr) ans=[None]*n D={} # [soi,ei,L,R] # inits the first soi for each value for i,v in enumerate(arr): if v not in D: D[v]=[0,i,0,1] else: soi,first_i,_,k=D[v] D[v]=soi+(i-first_i),first_i,0,k+1 # fills the list ans for i,v in enumerate(arr): soi,prev_i,L,R=D[v] soi+=(i-prev_i)*(L-R) D[v]=soi,i,L+1,R-1 ans[i]=soi return ans
intervals-between-identical-elements
Simple approach: code + comments
volokh0x
0
45
intervals between identical elements
2,121
0.433
Medium
29,334
https://leetcode.com/problems/intervals-between-identical-elements/discuss/1647619/Python3-Index-hashmap-%2B-prefix-sum-%2B-binary-search
class Solution: def getDistances(self, arr: List[int]) -> List[int]: indices = defaultdict(list) prefsum = {} for i, a in enumerate(arr): indices[a].append(i) if a not in prefsum: prefsum[a] = [i] else: prefsum[a].append(i + prefsum[a][-1]) res = [] for i, a in enumerate(arr): idx = bisect_right(indices[a], i) - 1 # count of smaller, count of larger sc, lc = idx, len(indices[a]) - idx - 1 ss = prefsum[a][idx - 1] if idx > 0 else 0 # sum of smaller ls = prefsum[a][-1] - prefsum[a][idx] # sum of larger res.append(i * sc - ss + ls - i * lc) return res
intervals-between-identical-elements
[Python3] Index hashmap + prefix sum + binary search
FanchenBao
0
49
intervals between identical elements
2,121
0.433
Medium
29,335
https://leetcode.com/problems/recover-the-original-array/discuss/1647488/Python3-brute-force
class Solution: def recoverArray(self, nums: List[int]) -> List[int]: nums.sort() cnt = Counter(nums) for i in range(1, len(nums)): diff = nums[i] - nums[0] if diff and diff&amp;1 == 0: ans = [] freq = cnt.copy() for k, v in freq.items(): if v: if freq[k+diff] < v: break ans.extend([k+diff//2]*v) freq[k+diff] -= v else: return ans
recover-the-original-array
[Python3] brute-force
ye15
11
503
recover the original array
2,122
0.381
Hard
29,336
https://leetcode.com/problems/recover-the-original-array/discuss/1647692/Python3-Try-All-Valid-K-Values
class Solution: def recoverArray(self, nums): self.n, self.nums = len(nums) // 2, sorted(nums) small = self.nums[0] for x in self.nums[1:]: k = x - small # this represents 2 * k from the problem statement if k % 2 or not k: continue temp = self.valid(k) if temp: return temp return [] def valid(self, k): counts = defaultdict(list) for i in range(len(self.nums) - 1, -1, -1): counts[self.nums[i]].append(i) # go through each value from smallest to largest # at each value check for corresponding (val + k) # keep track of which values are used when checking # ahead for the (val + k) # finally add (val + k / 2) if we find the corresponding # (val + k) as it is the value from the original array ans, used = [], [False] * len(self.nums) for i, v in enumerate(self.nums): if used[i]: continue if not counts[v + k]: return [] used[counts[v + k].pop()] = True ans.append(v + k // 2) return ans
recover-the-original-array
[Python3] Try All Valid K Values
simonesestili
1
63
recover the original array
2,122
0.381
Hard
29,337
https://leetcode.com/problems/recover-the-original-array/discuss/2491703/Clean-and-well-structured-Python3-implementation-(Top-93.2)-oror-Very-simple
class Solution(object): def recoverArray(self, nums): nums.sort() mid = len(nums) // 2 # All possible k are (nums[j] - nums[0]) // 2, otherwise there is no num that satisfies nums[0] + k = num - k. # For nums is sorted, so that any 2 elements (x, y) in nums[1:j] cannot satisfy x + k = y - k. # In other words, for any x in nums[1:j], it needs to find y from nums[j + 1:] to satisfy x + k = y - k, but # unfortunately if j > mid, then len(nums[j + 1:]) < mid <= len(nums[1:j]), nums[j + 1:] are not enough. # The conclusion is j <= mid. # If you think it’s not easy to understand why mid is enough, len(nums) can also work well # for j in range(1, len(nums)): for j in range(1, mid + 1): # O(N) if nums[j] - nums[0] > 0 and (nums[j] - nums[0]) % 2 == 0: # Note the problem described k is positive. k, counter, ans = (nums[j] - nums[0]) // 2, collections.Counter(nums), [] # For each number in lower, we try to find the corresponding number from higher list. # Because nums is sorted, current n is always the current lowest num which can only come from lower # list, so we search the corresponding number of n which equals to n + 2 * k in the left # if it can not be found, change another k and continue to try. for n in nums: # check if n + 2 * k available as corresponding number in higher list of n if counter[n] == 0: # removed by previous num as its corresponding number in higher list continue if counter[n + 2 * k] == 0: # not found corresponding number in higher list break ans.append(n + k) counter[n] -= 1 # remove n counter[n + 2 * k] -= 1 # remove the corresponding number in higher list if len(ans) == mid: return ans
recover-the-original-array
✔️ Clean and well structured Python3 implementation (Top 93.2%) || Very simple
Kagoot
0
35
recover the original array
2,122
0.381
Hard
29,338
https://leetcode.com/problems/recover-the-original-array/discuss/1713646/Using-Counter-and-sorted-keys-82-speed
class Solution: def recoverArray(self, nums: List[int]) -> List[int]: half_len_nums = len(nums) // 2 cnt = Counter(nums) keys = sorted(cnt.keys()) min_key = keys[0] diffs = [diff for i in range(1, len(keys)) if not (diff := keys[i] - min_key) % 2] for d in diffs: ans = [] cnt_copy = cnt.copy() for k in keys: if cnt_copy[k]: if k + d in cnt_copy and cnt_copy[k] <= cnt_copy[k + d]: ans.extend([k + d // 2] * cnt_copy[k]) cnt_copy[k + d] -= cnt_copy[k] else: break if len(ans) == half_len_nums: return ans return []
recover-the-original-array
Using Counter and sorted keys, 82% speed
EvgenySH
0
83
recover the original array
2,122
0.381
Hard
29,339
https://leetcode.com/problems/recover-the-original-array/discuss/1648740/Python-3-Hint-solution
class Solution: def recoverArray(self, nums: List[int]) -> List[int]: nums.sort() n = len(nums) def check(k): cnt = defaultdict(int) ans = [] for x in nums: if cnt[x - 2*k] > 0: cnt[x - 2*k] -= 1 ans.append(x - k) else: cnt[x] += 1 if len(ans) == n // 2: return ans return [] # maximum k should not exceed half of the array cand_k = sorted(set((nums[i] - nums[0]) // 2 for i in range(1, n // 2 + 1) if (nums[i] - nums[0]) % 2 == 0)) for k in cand_k: if k == 0: continue ans = check(k) if ans: return ans
recover-the-original-array
[Python 3] Hint solution
chestnut890123
0
51
recover the original array
2,122
0.381
Hard
29,340
https://leetcode.com/problems/check-if-all-as-appears-before-all-bs/discuss/1662586/Python-O(NlogN)-sort-solution-and-O(N)-linear-scan-solution
class Solution: def checkString(self, s: str) -> bool: return ''.join(sorted(s)) == s
check-if-all-as-appears-before-all-bs
[Python] O(NlogN) sort solution and O(N) linear scan solution
kryuki
4
193
check if all as appears before all bs
2,124
0.716
Easy
29,341
https://leetcode.com/problems/check-if-all-as-appears-before-all-bs/discuss/1662586/Python-O(NlogN)-sort-solution-and-O(N)-linear-scan-solution
class Solution: def checkString(self, s: str) -> bool: appeared_b = False for char in s: if char == 'b': appeared_b = True else: if appeared_b: return False return True
check-if-all-as-appears-before-all-bs
[Python] O(NlogN) sort solution and O(N) linear scan solution
kryuki
4
193
check if all as appears before all bs
2,124
0.716
Easy
29,342
https://leetcode.com/problems/check-if-all-as-appears-before-all-bs/discuss/1661317/Python
class Solution: def checkString(self, s: str) -> bool: found = False for c in s: if c == 'b': found = True elif found: return False return True
check-if-all-as-appears-before-all-bs
Python
blue_sky5
2
108
check if all as appears before all bs
2,124
0.716
Easy
29,343
https://leetcode.com/problems/check-if-all-as-appears-before-all-bs/discuss/2725389/Python3ororO(n)oror-easy
class Solution: def checkString(self, s: str) -> bool: c=s[0] if s[0]=='b' and 'a' in s: return False n=len(s) for i in range(n): if c==s[i]: continue elif c in s[i+1:]: return False return True
check-if-all-as-appears-before-all-bs
Python3||O(n)|| easy
Sneh713
1
153
check if all as appears before all bs
2,124
0.716
Easy
29,344
https://leetcode.com/problems/check-if-all-as-appears-before-all-bs/discuss/1816145/Python-solution-in-one-line
class Solution: def checkString(self, s: str) -> bool: return not 'ba' in s
check-if-all-as-appears-before-all-bs
Python solution in one line
iamamirhossein
1
62
check if all as appears before all bs
2,124
0.716
Easy
29,345
https://leetcode.com/problems/check-if-all-as-appears-before-all-bs/discuss/1666354/Easy-To-Understand-Python-Simple-Solution
class Solution: def checkString(self, s: str) -> bool: if "ba" in s: return False return True ```
check-if-all-as-appears-before-all-bs
Easy To Understand Python Simple Solution
prasadghadage
1
32
check if all as appears before all bs
2,124
0.716
Easy
29,346
https://leetcode.com/problems/check-if-all-as-appears-before-all-bs/discuss/2825276/Simple-and-Fast-Python-Solution
class Solution: def checkString(self, s: str) -> bool: if "b" in s: b_index = s.index("b") new_s = s[b_index: len(s)] return not "a" in new_s else: return True
check-if-all-as-appears-before-all-bs
Simple and Fast Python Solution
PranavBhatt
0
2
check if all as appears before all bs
2,124
0.716
Easy
29,347
https://leetcode.com/problems/check-if-all-as-appears-before-all-bs/discuss/2810706/Very-very-easy-solution-using-Python
class Solution: def checkString(self, s: str) -> bool: c = s.count('a') if c == 0: return True if c > 0 and s[:c] == "a" * c: return True return False
check-if-all-as-appears-before-all-bs
Very very easy solution using Python
ankurbhambri
0
7
check if all as appears before all bs
2,124
0.716
Easy
29,348
https://leetcode.com/problems/check-if-all-as-appears-before-all-bs/discuss/2803509/Simple-Python-Solution
class Solution: def checkString(self, s: str) -> bool: seen = set() for c in s: if c == 'a' and 'b' in seen: return False seen.add(c) return True
check-if-all-as-appears-before-all-bs
Simple Python Solution
mansoorafzal
0
2
check if all as appears before all bs
2,124
0.716
Easy
29,349
https://leetcode.com/problems/check-if-all-as-appears-before-all-bs/discuss/2788366/python-solution
class Solution: def checkString(self, s: str) -> bool: a = 0 b = 0 for i in s: if i == 'a' and b == 0: a += 1 elif i == 'b': b += 1 else: return False return True
check-if-all-as-appears-before-all-bs
python solution
shingnapure_shilpa17
0
3
check if all as appears before all bs
2,124
0.716
Easy
29,350
https://leetcode.com/problems/check-if-all-as-appears-before-all-bs/discuss/2786357/Simplest-solution.
class Solution: def checkString(self, s: str) -> bool: start, end = 0, len(s) while start < end and s[start] == 'a': start += 1 while start < end and s[start] == 'b': start += 1 return start == end
check-if-all-as-appears-before-all-bs
Simplest solution.
ahmedsamara
0
2
check if all as appears before all bs
2,124
0.716
Easy
29,351
https://leetcode.com/problems/check-if-all-as-appears-before-all-bs/discuss/2781351/python-solution-very-easy
class Solution: def checkString(self, s: str) -> bool: if (sorted(s)) == list(s): return True; else: return False;
check-if-all-as-appears-before-all-bs
python solution very easy
seifsoliman
0
1
check if all as appears before all bs
2,124
0.716
Easy
29,352
https://leetcode.com/problems/check-if-all-as-appears-before-all-bs/discuss/2758719/python-code
class Solution: def checkString(self, s: str) -> bool: return ''.join(sorted(s)) == s
check-if-all-as-appears-before-all-bs
python code
ayushigupta2409
0
6
check if all as appears before all bs
2,124
0.716
Easy
29,353
https://leetcode.com/problems/check-if-all-as-appears-before-all-bs/discuss/2758719/python-code
class Solution: def checkString(self, s: str) -> bool: s=list(s) while 'a' in s and 'b' in s: if s.index('a')<s.index('b'): s.remove('a') else: return False return True
check-if-all-as-appears-before-all-bs
python code
ayushigupta2409
0
6
check if all as appears before all bs
2,124
0.716
Easy
29,354
https://leetcode.com/problems/check-if-all-as-appears-before-all-bs/discuss/2662250/Python-One-liner-Solution
class Solution: def checkString(self, s: str) -> bool: return "ba" not in s
check-if-all-as-appears-before-all-bs
Python One-liner Solution
kcstar
0
5
check if all as appears before all bs
2,124
0.716
Easy
29,355
https://leetcode.com/problems/check-if-all-as-appears-before-all-bs/discuss/2629475/Python3-Simple-One-Liner-with-not-any()
class Solution: def checkString(self, s: str) -> bool: return not any('a' in s[i:] for i, char in enumerate(s) if char == 'b')
check-if-all-as-appears-before-all-bs
[Python3] Simple One-Liner with not any()
ivnvalex
0
7
check if all as appears before all bs
2,124
0.716
Easy
29,356
https://leetcode.com/problems/check-if-all-as-appears-before-all-bs/discuss/2576200/Python-Simple-Python-Solution
class Solution: def checkString(self, s: str) -> bool: last_index_a = -1 last_index_b = -1 for i in range(len(s)): if s[i] == 'a': last_index_a = i if s[i] == 'b' and last_index_b == -1: last_index_b = i if last_index_a == -1 or last_index_b == -1: return True else: if last_index_a < last_index_b: return True else: return False
check-if-all-as-appears-before-all-bs
[ Python ] ✅✅ Simple Python Solution 🥳✌👍
ASHOK_KUMAR_MEGHVANSHI
0
36
check if all as appears before all bs
2,124
0.716
Easy
29,357
https://leetcode.com/problems/check-if-all-as-appears-before-all-bs/discuss/2564972/Solution
class Solution: def checkString(self, s: str) -> bool: for i in range(len(s)-1): if s[i] == "b" and s[i+1] == "a": return False return True
check-if-all-as-appears-before-all-bs
Solution
fiqbal997
0
10
check if all as appears before all bs
2,124
0.716
Easy
29,358
https://leetcode.com/problems/check-if-all-as-appears-before-all-bs/discuss/2535891/Simple-Python-solution
class Solution: def checkString(self, s: str) -> bool: for i in range(len(s)): if s[i] == "a": continue else: break if i == len(s)-1: return True while i < len(s): if s[i] == "a": return False i += 1 return True
check-if-all-as-appears-before-all-bs
Simple Python solution
aruj900
0
21
check if all as appears before all bs
2,124
0.716
Easy
29,359
https://leetcode.com/problems/check-if-all-as-appears-before-all-bs/discuss/2466249/Iterative-Solution-with-slicing
class Solution: def checkString(self, s: str) -> bool: # iterate the string s # if when you locate a b, verify that no a's suceed it. # use a flag to verify when you see an a # if it does return False, otherwise return True after iteration # Time O(N) Space: O(1) for i in range(1, len(s)): if s[i] == "a" and "b" in s[:i]: return False return True
check-if-all-as-appears-before-all-bs
Iterative Solution with slicing
andrewnerdimo
0
18
check if all as appears before all bs
2,124
0.716
Easy
29,360
https://leetcode.com/problems/check-if-all-as-appears-before-all-bs/discuss/2385082/Super-easy-python
class Solution: def checkString(self, s: str) -> bool: l=len(s) for i in range(l-1): if s[i]=='b' and s[i+1]=='a': return False return True
check-if-all-as-appears-before-all-bs
Super easy python
sunakshi132
0
34
check if all as appears before all bs
2,124
0.716
Easy
29,361
https://leetcode.com/problems/check-if-all-as-appears-before-all-bs/discuss/2183214/faster-than-93.65-of-Python3
class Solution: def checkString(self, s: str) -> bool: return (''.join(sorted(list(s)))) == s
check-if-all-as-appears-before-all-bs
faster than 93.65% of Python3
writemeom
0
41
check if all as appears before all bs
2,124
0.716
Easy
29,362
https://leetcode.com/problems/check-if-all-as-appears-before-all-bs/discuss/2166818/Super-simple-python-one-liner
class Solution: def checkString(self, s: str) -> bool: return list(s) == sorted(list(s))
check-if-all-as-appears-before-all-bs
Super simple python one-liner
pro6igy
0
31
check if all as appears before all bs
2,124
0.716
Easy
29,363
https://leetcode.com/problems/check-if-all-as-appears-before-all-bs/discuss/2069192/Python3-Easy-Understanding-(Faster-than-98.47)
class Solution: def checkString(self, s: str) -> bool: a_count = s.count("a") ## Count the occurances of a # b_count = s.count("b") for i in range(a_count): ## Check if the first of a_count in the string are "a" if s[i] != 'a': return False return True
check-if-all-as-appears-before-all-bs
Python3- Easy Understanding (Faster than 98.47%)
prithuls
0
50
check if all as appears before all bs
2,124
0.716
Easy
29,364
https://leetcode.com/problems/check-if-all-as-appears-before-all-bs/discuss/1988717/Python3-100-faster-with-explanation
class Solution: def checkString(self, s: str) -> bool: mapper = {} for x in s: if 'b' in mapper and x == 'a': return False else: mapper[x] = 1 return True
check-if-all-as-appears-before-all-bs
Python3, 100% faster with explanation
cvelazquez322
0
76
check if all as appears before all bs
2,124
0.716
Easy
29,365
https://leetcode.com/problems/check-if-all-as-appears-before-all-bs/discuss/1940863/Python-dollarolution
class Solution: def checkString(self, s: str) -> bool: flag = 0 for i in s: if i == 'a' and flag == 1: return False elif i == 'b': flag = 1 return True
check-if-all-as-appears-before-all-bs
Python $olution
AakRay
0
41
check if all as appears before all bs
2,124
0.716
Easy
29,366
https://leetcode.com/problems/check-if-all-as-appears-before-all-bs/discuss/1926995/Python3-simple-solution
class Solution: def checkString(self, s: str) -> bool: flag = True for i in s: if i == 'b' and flag: flag = False if i == 'a' and not flag: return False return True
check-if-all-as-appears-before-all-bs
Python3 simple solution
EklavyaJoshi
0
30
check if all as appears before all bs
2,124
0.716
Easy
29,367
https://leetcode.com/problems/check-if-all-as-appears-before-all-bs/discuss/1911761/python-3-oror-very-simple-solution
class Solution: def checkString(self, s: str) -> bool: flag = False for c in s: if c == 'b': flag = True elif flag: return False return True
check-if-all-as-appears-before-all-bs
python 3 || very simple solution
dereky4
0
34
check if all as appears before all bs
2,124
0.716
Easy
29,368
https://leetcode.com/problems/check-if-all-as-appears-before-all-bs/discuss/1899274/Python-clean-and-simple!-%2B-One-Liner
class Solution: def checkString(self, s): sawB = False for c in s: if c=='a' and sawB: return False elif c=='b': sawB = True return True
check-if-all-as-appears-before-all-bs
Python - clean and simple! + One Liner
domthedeveloper
0
28
check if all as appears before all bs
2,124
0.716
Easy
29,369
https://leetcode.com/problems/check-if-all-as-appears-before-all-bs/discuss/1899274/Python-clean-and-simple!-%2B-One-Liner
class Solution: def checkString(self, s): sawB = False for c in s: match c: case 'a': if sawB: return False case 'b': sawB = True return True
check-if-all-as-appears-before-all-bs
Python - clean and simple! + One Liner
domthedeveloper
0
28
check if all as appears before all bs
2,124
0.716
Easy
29,370
https://leetcode.com/problems/check-if-all-as-appears-before-all-bs/discuss/1899274/Python-clean-and-simple!-%2B-One-Liner
class Solution: def checkString(self, s): return "ba" not in s
check-if-all-as-appears-before-all-bs
Python - clean and simple! + One Liner
domthedeveloper
0
28
check if all as appears before all bs
2,124
0.716
Easy
29,371
https://leetcode.com/problems/check-if-all-as-appears-before-all-bs/discuss/1846953/4-Line-Python3-Easy-Solution-oror-100-Faster-oror-Easy-to-understand-Python-code
class Solution: def checkString(self, s: str) -> bool: ct=1 cm=1 for i in range(0,len(s)-1): if s[i]=='b': if s[i+1]=='a': ct=-3 return ct==cm
check-if-all-as-appears-before-all-bs
4-Line Python3 Easy Solution || 100% Faster || Easy to understand Python code
RatnaPriya
0
53
check if all as appears before all bs
2,124
0.716
Easy
29,372
https://leetcode.com/problems/check-if-all-as-appears-before-all-bs/discuss/1823504/easy-python-solution
class Solution: def checkString(self, s: str) -> bool: flag = 0 if "a" not in s: return True elif "b" not in s: return True else: for i in s: if i == "b": flag = 1 elif i == "a" and flag == 1: return False return True
check-if-all-as-appears-before-all-bs
easy python solution
dakash682
0
40
check if all as appears before all bs
2,124
0.716
Easy
29,373
https://leetcode.com/problems/check-if-all-as-appears-before-all-bs/discuss/1791880/Python-easy-solution
class Solution: def checkString(self, s: str) -> bool: n = len(s) # initial values take care if s has only a's or only b's lastA = -1 firstB = n for i in range(n): if s[i] == 'a': lastA = max(lastA, i) else: firstB = min(firstB, i) return lastA < firstB # check if last occurrence of 'a' is before first occurrence of 'b'
check-if-all-as-appears-before-all-bs
Python easy solution
abkc1221
0
50
check if all as appears before all bs
2,124
0.716
Easy
29,374
https://leetcode.com/problems/check-if-all-as-appears-before-all-bs/discuss/1673948/Python3Java-Simple-clean-and-concise-O(n)-time-O(1)-space-100-Java
class Solution: def checkString(self, s: str) -> bool: max_a_index = float("-inf") min_b_index = float("inf") for i, c in enumerate(s): if c == "a": max_a_index = max(max_a_index, i) elif c == "b": min_b_index = min(min_b_index, i) return max_a_index < min_b_index
check-if-all-as-appears-before-all-bs
[Python3/Java] Simple, clean and concise - O(n) time, O(1) space - 100% Java
hanelios
0
42
check if all as appears before all bs
2,124
0.716
Easy
29,375
https://leetcode.com/problems/check-if-all-as-appears-before-all-bs/discuss/1670879/python-easy-O(n)-time-O(1)-space-solution
class Solution: def checkString(self, s: str) -> bool: n = len(s) if n == 1: return True if s.count('a') == 0 or s.count('a') == n: return True i, j = 0, n-1 while i <= n-1 and s[i] == 'a': i += 1 while j >=0 and s[j] =='b': j -= 1 return i == j+1
check-if-all-as-appears-before-all-bs
python easy O(n) time, O(1) space solution
byuns9334
0
39
check if all as appears before all bs
2,124
0.716
Easy
29,376
https://leetcode.com/problems/check-if-all-as-appears-before-all-bs/discuss/1661534/Python3-Easy-Solution-(Accepted)-(Commented)-(Clean)
class Solution: def checkString(self, s: str) -> bool: if 'a' not in s: //Base case is if there are no a's in the string return True for i in range(1, len(s)): //Iterate from the 2nd element of string to last if s[i] == 'a' and s[i-1] == 'b': //If there is a 'b' before 'a' then return False return False return True //There was no 'b' before 'a'
check-if-all-as-appears-before-all-bs
Python3 Easy Solution (Accepted) (Commented) (Clean)
sdasstriver9
0
36
check if all as appears before all bs
2,124
0.716
Easy
29,377
https://leetcode.com/problems/check-if-all-as-appears-before-all-bs/discuss/1660977/Python3-1-line
class Solution: def checkString(self, s: str) -> bool: return "ba" not in s
check-if-all-as-appears-before-all-bs
[Python3] 1-line
ye15
0
47
check if all as appears before all bs
2,124
0.716
Easy
29,378
https://leetcode.com/problems/number-of-laser-beams-in-a-bank/discuss/2272999/PYTHON-3-99.13-LESS-MEMORY-or-94.93-FASTER-or-EXPLANATION
class Solution: def numberOfBeams(self, bank: List[str]) -> int: a, s = [x.count("1") for x in bank if x.count("1")], 0 # ex: bank is [[00101], [01001], [00000], [11011]] # a would return [2, 2, 4] for c in range(len(a)-1): s += (a[c]*a[c+1]) # basic math to find the total amount of lasers # for the first iteration: s += 2*2 # for the second iteration: s += 2*4 # returns s = 12 return s
number-of-laser-beams-in-a-bank
[PYTHON 3] 99.13% LESS MEMORY | 94.93% FASTER | EXPLANATION
omkarxpatel
7
130
number of laser beams in a bank
2,125
0.826
Medium
29,379
https://leetcode.com/problems/number-of-laser-beams-in-a-bank/discuss/1660994/Python3-simulation
class Solution: def numberOfBeams(self, bank: List[str]) -> int: ans = prev = 0 for row in bank: curr = row.count('1') if curr: ans += prev * curr prev = curr return ans
number-of-laser-beams-in-a-bank
[Python3] simulation
ye15
7
417
number of laser beams in a bank
2,125
0.826
Medium
29,380
https://leetcode.com/problems/number-of-laser-beams-in-a-bank/discuss/2677735/Simple-Python-Solution
class Solution: def numberOfBeams(self, bank: List[str]) -> int: ans = prev = 0 for s in bank: c = s.count('1') if c: ans += prev * c prev = c return ans
number-of-laser-beams-in-a-bank
Simple Python Solution
Sneh713
1
70
number of laser beams in a bank
2,125
0.826
Medium
29,381
https://leetcode.com/problems/number-of-laser-beams-in-a-bank/discuss/2633920/Python3-Simple-Solution
class Solution: def numberOfBeams(self, bank: List[str]) -> int: pre = 0 nn = 0 ans = 0 for i in bank: nn= 0 for j in i: if j == '1': nn+=1 if nn: ans+=nn*pre pre= nn return ans ## PLease upvote if you like the Solution
number-of-laser-beams-in-a-bank
Python3 Simple Solution
hoo__mann
1
11
number of laser beams in a bank
2,125
0.826
Medium
29,382
https://leetcode.com/problems/number-of-laser-beams-in-a-bank/discuss/1938928/Python3-Simple-Solution
class Solution: def numberOfBeams(self, bank: List[str]) -> int: beams = 0 prev = 0 for b in bank: last = b.count('1') if last: beams += prev * last prev = last return beams
number-of-laser-beams-in-a-bank
[Python3] Simple Solution
terrencetang
1
70
number of laser beams in a bank
2,125
0.826
Medium
29,383
https://leetcode.com/problems/number-of-laser-beams-in-a-bank/discuss/1832792/Python-Solution-or-95-lesser-memory-or-5-Lines-of-code
class Solution: def numberOfBeams(self, bank: List[str]) -> int: laser, n = [], len(bank[0]) bank = list(filter(("0"*n).__ne__, bank)) for i in range(len(bank)-1): laser.append(bank[i].count("1")*bank[i+1].count("1")) return sum(laser)
number-of-laser-beams-in-a-bank
✔Python Solution | 95% lesser memory | 5 Lines of code
Coding_Tan3
1
59
number of laser beams in a bank
2,125
0.826
Medium
29,384
https://leetcode.com/problems/number-of-laser-beams-in-a-bank/discuss/2840449/Join-method
class Solution: def numberOfBeams(self, bank: List[str]) -> int: if len(bank) > 1: last_value = len(''.join(bank[0].split('0'))) v_sum = 0 for floor in bank[1:]: value = len(''.join(floor.split('0'))) if value != 0: v_sum += (last_value*value) last_value = value return v_sum else: return 0
number-of-laser-beams-in-a-bank
Join method
Robert1914
0
1
number of laser beams in a bank
2,125
0.826
Medium
29,385
https://leetcode.com/problems/number-of-laser-beams-in-a-bank/discuss/2785334/Python-Recursion-solution
class Solution: def numberOfBeams(self, bank: List[str]) -> int: def recu(bank,i,prev,res): if i == len(bank): return res count = bank[i].count("1") if count: res += count*prev prev = count return recu(bank,i+1,prev,res) return recu(bank,0,0,0)
number-of-laser-beams-in-a-bank
Python Recursion solution
anshsharma17
0
3
number of laser beams in a bank
2,125
0.826
Medium
29,386
https://leetcode.com/problems/number-of-laser-beams-in-a-bank/discuss/2785334/Python-Recursion-solution
class Solution: def numberOfBeams(self, bank: List[str]) -> int: res = [] for b1 in range(len(bank)): count = 0 for b2 in range(len(bank[b1])): if bank[b1][b2] == "1": count+=1 if count > 0: res.append(count) if len(res) == 0 or len(res) ==1: return 0 return (sum([res[i]*res[i+1] for i in range(len(res)-1)]))
number-of-laser-beams-in-a-bank
Python Recursion solution
anshsharma17
0
3
number of laser beams in a bank
2,125
0.826
Medium
29,387
https://leetcode.com/problems/number-of-laser-beams-in-a-bank/discuss/2784963/Golang-Rust-Python-solution
class Solution: def numberOfBeams(self, bank: List[str]) -> int: def recu(bank,i,prev,res): if i == len(bank): return res count = bank[i].count("1") if count: res += count*prev prev = count return recu(bank,i+1,prev,res) return recu(bank,0,0,0)
number-of-laser-beams-in-a-bank
Golang-Rust-Python solution
anshsharma17
0
1
number of laser beams in a bank
2,125
0.826
Medium
29,388
https://leetcode.com/problems/number-of-laser-beams-in-a-bank/discuss/2784963/Golang-Rust-Python-solution
class Solution: def numberOfBeams(self, bank: List[str]) -> int: res = [] for b1 in range(len(bank)): count = 0 for b2 in range(len(bank[b1])): if bank[b1][b2] == "1": count+=1 if count > 0: res.append(count) if len(res) == 0 or len(res) ==1: return 0 return (sum([res[i]*res[i+1] for i in range(len(res)-1)]))
number-of-laser-beams-in-a-bank
Golang-Rust-Python solution
anshsharma17
0
1
number of laser beams in a bank
2,125
0.826
Medium
29,389
https://leetcode.com/problems/number-of-laser-beams-in-a-bank/discuss/2759791/easy-python-solutionorortime-complexity-O(n)
class Solution: def numberOfBeams(self, bank: List[str]) -> int: ans= 0 i = 0 j = 1 while i<len(bank) and j<len(bank): a = bank[i].count("1") b = bank[j].count("1") if a!=0 and b!=0: ans+=a*b i = j if j<len(bank): j +=1 elif a==0 and b==0: i+=1 j+=1 elif a==0 and b!=0: i+=1 j+=1 elif b==0 and a!=0: j+=1 return ans
number-of-laser-beams-in-a-bank
✅✅easy python solution||time complexity O(n)
chessman_1
0
5
number of laser beams in a bank
2,125
0.826
Medium
29,390
https://leetcode.com/problems/number-of-laser-beams-in-a-bank/discuss/2710420/Python3
class Solution: def numberOfBeams(self, bank: List[str]) -> int: count_l = [i.count('1') for i in bank if i.count('1')>0] ans = 0 i = 0 while i < len(count_l) - 1: ans = ans + count_l[i] * count_l[i + 1] i += 1 return ans
number-of-laser-beams-in-a-bank
Python3
sipi09
0
3
number of laser beams in a bank
2,125
0.826
Medium
29,391
https://leetcode.com/problems/number-of-laser-beams-in-a-bank/discuss/2709062/Python3-One-Liner-Using-List-Comprehension
class Solution: def numberOfBeams(self, bank: List[str]) -> int: return [sum(map(lambda a: a[0]*a[1], zip(x, x[1:]))) for x in [[g for g in [sum([int(c) for c in b]) for b in bank] if g!=0]]][0]
number-of-laser-beams-in-a-bank
Python3 One Liner Using List Comprehension
godshiva
0
2
number of laser beams in a bank
2,125
0.826
Medium
29,392
https://leetcode.com/problems/number-of-laser-beams-in-a-bank/discuss/2698714/Python3-Simple-Solution
class Solution: def numberOfBeams(self, bank: List[str]) -> int: res = 0 for i, row1 in enumerate(bank): c1 = row1.count('1') if c1 == 0: continue for row2 in bank[i + 1:]: c2 = row2.count('1') if c2 > 0: res += c1 * c2 break return res
number-of-laser-beams-in-a-bank
Python3 Simple Solution
mediocre-coder
0
3
number of laser beams in a bank
2,125
0.826
Medium
29,393
https://leetcode.com/problems/number-of-laser-beams-in-a-bank/discuss/2688168/Python-or-93
class Solution: def numberOfBeams(self, bank: List[str]) -> int: res=0 last = 0 for i in range(len(bank)): new = bank[i].count('1') if new >0: res = res + last*new last = new return res
number-of-laser-beams-in-a-bank
Python | 93%
naveenraiit
0
7
number of laser beams in a bank
2,125
0.826
Medium
29,394
https://leetcode.com/problems/number-of-laser-beams-in-a-bank/discuss/2665920/python3-Faster-than-95
class Solution: def numberOfBeams(self, bank: List[str]) -> int: upper = 0 lower = 0 total = 0 for i in bank: beam = i.count('1') if upper == 0: upper = beam continue else: if beam != 0: lower = beam total = total + lower * upper upper = lower else: continue return total
number-of-laser-beams-in-a-bank
python3 Faster than 95%
Noisy47
0
3
number of laser beams in a bank
2,125
0.826
Medium
29,395
https://leetcode.com/problems/number-of-laser-beams-in-a-bank/discuss/2629077/Python-solution
class Solution: def numberOfBeams(self, bank: List[str]) -> int: ans = 0 arr = [] length = 0 for row in bank: if set(row) == {'0'}: continue arr.append(row.count('1')) length += 1 for i in range(length -1): ans += (arr[i] * arr[i + 1]) return ans
number-of-laser-beams-in-a-bank
Python solution
Guild_Arts
0
2
number of laser beams in a bank
2,125
0.826
Medium
29,396
https://leetcode.com/problems/number-of-laser-beams-in-a-bank/discuss/2539313/Python-or-looping-or-O(n)-Time-or-O(1)-Space
class Solution: def numberOfBeams(self, bank: List[str]) -> int: ans = 0 prev = 0 for floor in bank: count = floor.count("1") ans += count*prev if count>0: prev = count return ans
number-of-laser-beams-in-a-bank
Python | looping | O(n) Time | O(1) Space
coolakash10
0
5
number of laser beams in a bank
2,125
0.826
Medium
29,397
https://leetcode.com/problems/number-of-laser-beams-in-a-bank/discuss/2499957/Python-or-Basic-Combinatorics
class Solution: def numberOfBeams(self, bank: List[str]) -> int: laserCount = 0; prevDeviceCount = 0 for row in bank: currentDeviceCount = row.count("1") if currentDeviceCount != 0: # this skips lines that have no devices laserCount += prevDeviceCount * currentDeviceCount prevDeviceCount = currentDeviceCount return laserCount
number-of-laser-beams-in-a-bank
Python | Basic Combinatorics
sr_vrd
0
8
number of laser beams in a bank
2,125
0.826
Medium
29,398
https://leetcode.com/problems/number-of-laser-beams-in-a-bank/discuss/2272241/Simple-Python-Solution-96-faster-than-other
class Solution: def numberOfBeams(self, bank: List[str]) -> int: output = 0 curr = 0 currPlus = 1 if len(bank)<2: return 0 while currPlus < len(bank): curr1count = bank[curr].count("1") currPlus1count = bank[currPlus].count("1") if curr1count > 0: if currPlus1count > 0: output += curr1count*currPlus1count curr = currPlus currPlus+=1 else: currPlus+=1 else: curr+=1 currPlus+=1 return output
number-of-laser-beams-in-a-bank
Simple Python Solution 96% faster than other
sunnysharma03
0
21
number of laser beams in a bank
2,125
0.826
Medium
29,399