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/number-of-lines-to-write-string/discuss/1170893/Python3-97-Faster-Solution
class Solution: def numberOfLines(self, widths: List[int], s: str) -> List[int]: count = ans = wi = 0 s = list(s) while s: val = ord(s[0]) - 97 if(widths[val] + wi > 100): wi = 0 count += 1 wi += widths[val] s.pop(0) return([count + 1 , wi])
number-of-lines-to-write-string
[Python3] 97% Faster Solution
VoidCupboard
2
80
number of lines to write string
806
0.662
Easy
13,100
https://leetcode.com/problems/number-of-lines-to-write-string/discuss/2208621/Python3-Runtime%3A-42ms-67.78-Memory%3A-13.9mb-19.81
class Solution: # Runtime: 42ms 67.78% Memory: 13.9mb 19.81% # O(n) || O(1) def numberOfLines(self, widths, s): newLine = 1 width = 0 for char in s: charWidth = widths[ord(char) - ord('a')] if charWidth + width > 100: newLine += 1 width = 0 width += charWidth return [newLine, width]
number-of-lines-to-write-string
Python3 Runtime: 42ms 67.78% Memory: 13.9mb 19.81%
arshergon
1
53
number of lines to write string
806
0.662
Easy
13,101
https://leetcode.com/problems/number-of-lines-to-write-string/discuss/1893289/Python-easy-solution-beginner-friendly
class Solution: def numberOfLines(self, widths: List[int], s: str) -> List[int]: lines = 1 pix_per_line = 0 for i in s: if widths[ord(i) - 97] + pix_per_line <= 100: pix_per_line += widths[ord(i) - 97] else: lines += 1 pix_per_line = widths[ord(i) - 97] return [lines, pix_per_line]
number-of-lines-to-write-string
Python easy solution, beginner friendly
alishak1999
1
83
number of lines to write string
806
0.662
Easy
13,102
https://leetcode.com/problems/number-of-lines-to-write-string/discuss/1328427/Python3-dollarolution
class Solution: def numberOfLines(self, widths: List[int], s: str) -> List[int]: su, c = 0, 1 for i in s: x = widths[ord(i)-97] su += x if su > 100: su = x c += 1 return [c,su]
number-of-lines-to-write-string
Python3 $olution
AakRay
1
88
number of lines to write string
806
0.662
Easy
13,103
https://leetcode.com/problems/number-of-lines-to-write-string/discuss/1066236/Python3-simple-solution
class Solution: def numberOfLines(self, widths: List[int], s: str) -> List[int]: count, sum = 1, 0 for i in s: a = widths[ord(i) - 97] sum += a if sum > 100: count += 1 sum = a return [count, sum]
number-of-lines-to-write-string
Python3 simple solution
EklavyaJoshi
1
40
number of lines to write string
806
0.662
Easy
13,104
https://leetcode.com/problems/number-of-lines-to-write-string/discuss/2834050/Simple-Python-solution-beats-80
class Solution: def numberOfLines(self, widths: List[int], s: str) -> List[int]: a_dict = {l:w for l,w in zip("abcdefghijklmnopqrstuvwxyz",widths)} lines = 0 pix = 0 for i in s: if pix + a_dict[i] > 100: pix = a_dict[i] lines += 1 else: pix += a_dict[i] return [lines+1,pix]
number-of-lines-to-write-string
Simple Python solution beats 80%
aruj900
0
1
number of lines to write string
806
0.662
Easy
13,105
https://leetcode.com/problems/number-of-lines-to-write-string/discuss/1788884/Simple-Python-Solution-oror-Faster-than-60-oror-Memory-less-than-90
class Solution: def numberOfLines(self, widths: List[int], s: str) -> List[int]: ref = dict(zip(list(string. ascii_lowercase), widths)) pixels, lines = 0, 1 for char in s: if pixels + ref[char] <= 100: pixels += ref[char] else: lines += 1 pixels = ref[char] return [lines, pixels]
number-of-lines-to-write-string
Simple Python Solution || Faster than 60% || Memory less than 90%
Taha-C
0
60
number of lines to write string
806
0.662
Easy
13,106
https://leetcode.com/problems/number-of-lines-to-write-string/discuss/1640567/Python-3-easy-solution
class Solution: def numberOfLines(self, widths: List[int], s: str) -> List[int]: lines = 1 pixels = 0 for c in s: width = widths[ord(c) - 97] if pixels + width > 100: lines += 1 pixels = 0 pixels += width return [lines, pixels]
number-of-lines-to-write-string
Python 3 easy solution
dereky4
0
120
number of lines to write string
806
0.662
Easy
13,107
https://leetcode.com/problems/number-of-lines-to-write-string/discuss/1588444/Python3-Easy-Simple-Solution(99.54-Faster-Easy-Beginner)
class Solution: def numberOfLines(self, widths: List[int], s: str) -> List[int]: number_lines = 1 sums = 0 for num in s: value = widths[ord(num)-97] if ((sums+value)>100): sums=value number_lines+=1 else: sums+=value output = [number_lines,sums] return output
number-of-lines-to-write-string
Python3 Easy Simple Solution(99.54% Faster, Easy, Beginner)
DependerMohit
0
59
number of lines to write string
806
0.662
Easy
13,108
https://leetcode.com/problems/number-of-lines-to-write-string/discuss/1511830/Very-Easy-and-Simple-Python-Solution
class Solution: def numberOfLines(self, widths: List[int], s: str) -> List[int]: sum=0 line_count=1 for i in range(len(s)): char = ord(s[i]) - 97 if sum +widths[char] >100: sum=widths[char] line_count+=1 else: sum+=widths[char] return [line_count,sum]
number-of-lines-to-write-string
Very Easy and Simple Python Solution
sangam92
0
53
number of lines to write string
806
0.662
Easy
13,109
https://leetcode.com/problems/number-of-lines-to-write-string/discuss/1434565/One-pass
class Solution: def numberOfLines(self, widths: List[int], s: str) -> List[int]: letter_w = {chr(97 + i): widths[i] for i in range(26)} n_lines = line_len = 0 for c in s: line_len += letter_w[c] if line_len > 100: n_lines += 1 line_len = letter_w[c] return [n_lines + (line_len > 0), line_len]
number-of-lines-to-write-string
One pass
EvgenySH
0
71
number of lines to write string
806
0.662
Easy
13,110
https://leetcode.com/problems/max-increase-to-keep-city-skyline/discuss/445773/Python-3-(two-lines)-(beats-~100)
class Solution: def maxIncreaseKeepingSkyline(self, G: List[List[int]]) -> int: M, N, R, C = len(G), len(G[0]), [max(r) for r in G], [max(c) for c in zip(*G)] return sum(min(R[i],C[j]) - G[i][j] for i,j in itertools.product(range(M),range(N))) - Junaid Mansuri - Chicago, IL
max-increase-to-keep-city-skyline
Python 3 (two lines) (beats ~100%)
junaidmansuri
5
1,200
max increase to keep city skyline
807
0.86
Medium
13,111
https://leetcode.com/problems/max-increase-to-keep-city-skyline/discuss/2270359/PYTHON-3-EASY-or-SIMPLE-SOLUTION-or-STRAIGHT-FORWARD
class Solution: def maxIncreaseKeepingSkyline(self, grid: List[List[int]]) -> int: rows_max = [0] * len(grid) cols_max = [0] * len(grid[0]) for i in range(len(grid)): for j in range(len(grid[0])): rows_max[i] = max(rows_max[i], grid[i][j]) cols_max[j] = max(cols_max[j], grid[i][j]) res = 0 for i in range(len(grid)): for j in range(len(grid[0])): res += min(rows_max[i], cols_max[j]) - grid[i][j] return res
max-increase-to-keep-city-skyline
[PYTHON 3] EASY | SIMPLE SOLUTION | STRAIGHT FORWARD
omkarxpatel
2
165
max increase to keep city skyline
807
0.86
Medium
13,112
https://leetcode.com/problems/max-increase-to-keep-city-skyline/discuss/932618/Python3-max-per-row-and-column
class Solution: def maxIncreaseKeepingSkyline(self, grid: List[List[int]]) -> int: m, n = len(grid), len(grid[0]) row = [max(x) for x in grid] col = [max(x) for x in zip(*grid)] ans = 0 for i in range(m): for j in range(n): ans += min(row[i], col[j]) - grid[i][j] return ans
max-increase-to-keep-city-skyline
[Python3] max per row & column
ye15
2
140
max increase to keep city skyline
807
0.86
Medium
13,113
https://leetcode.com/problems/max-increase-to-keep-city-skyline/discuss/2181467/Python3-Runtime%3A-90ms-76.16-memory%3A-13.9mb-53.23
class Solution: # O(r, c) || O(r,c) # Runtime: 90ms 76.16% memory: 13.9mb 53.23% def maxIncreaseKeepingSkyline(self, grid: List[List[int]]) -> int: maxRowVal = [0] * len(grid[0]) maxColVal = [0] * len(grid[0]) for row in range(len(grid)): for col in range(len(grid[row])): maxRowVal[row] = max(maxRowVal[row], grid[row][col]) maxColVal[col] = max(maxColVal[col], grid[row][col]) result = 0 for row in range(len(grid)): for col in range(len(grid[row])): result += min(maxRowVal[row], maxColVal[col]) - grid[row][col] return result
max-increase-to-keep-city-skyline
Python3 Runtime: 90ms 76.16% memory: 13.9mb 53.23%
arshergon
1
56
max increase to keep city skyline
807
0.86
Medium
13,114
https://leetcode.com/problems/max-increase-to-keep-city-skyline/discuss/2153763/Python-3-solution-Easy-understanding
class Solution: def maxIncreaseKeepingSkyline(self, grid: List[List[int]]) -> int: tp=list(zip(*grid)) s=0 for i in range(len(grid)): for j in range(len(grid[0])): s+=min(max(grid[i]),max(tp[j]))-grid[i][j] return s
max-increase-to-keep-city-skyline
Python 3 solution -Easy understanding
Kunalbmd
1
44
max increase to keep city skyline
807
0.86
Medium
13,115
https://leetcode.com/problems/max-increase-to-keep-city-skyline/discuss/2789994/HOLY-COW!-python-trivial-solution
class Solution: def maxIncreaseKeepingSkyline(self, grid: List[List[int]]) -> int: n = len(grid) west = [0 for _ in range(n)] north = [0 for _ in range(n)] for i in range(n): west[i] = max(grid[i]) north[i] = max([x[i] for x in grid]) print(west, north) ans = 0 for i in range(n): for j in range(n): ans += min(north[j], west[i]) - grid[i][j] return ans
max-increase-to-keep-city-skyline
HOLY COW! python trivial solution
jestpunk
0
6
max increase to keep city skyline
807
0.86
Medium
13,116
https://leetcode.com/problems/max-increase-to-keep-city-skyline/discuss/2694638/Python3-Simple-Solution
class Solution: def maxIncreaseKeepingSkyline(self, grid: List[List[int]]) -> int: n = len(grid) maxInRow = [] for r in range(n): maxInRow.append(max(grid[r])) maxInCol = [] for col in range(n): tmp = 0 for row in range(n): tmp = max(tmp, grid[row][col]) maxInCol.append(tmp) res = 0 for i in range(n): for j in range(n): diff = min(maxInRow[i], maxInCol[j]) - grid[i][j] if diff > 0: res += diff return res
max-increase-to-keep-city-skyline
Python3 Simple Solution
mediocre-coder
0
1
max increase to keep city skyline
807
0.86
Medium
13,117
https://leetcode.com/problems/max-increase-to-keep-city-skyline/discuss/2666184/python3-Low-Runtime-Low-Memory
class Solution: def maxIncreaseKeepingSkyline(self, grid: List[List[int]]) -> int: height = [0]*len(grid) width = [0]*len(grid) col = list(zip(*grid)) for i in range(len(grid)): height[i] = max(grid[i]) width [i] = max(col[i]) total = 0 for i in range(len(grid)): for j in range(len(grid)): total += abs(grid[i][j] - min(height[i],width[j])) return total
max-increase-to-keep-city-skyline
python3 Low Runtime Low Memory
Noisy47
0
5
max increase to keep city skyline
807
0.86
Medium
13,118
https://leetcode.com/problems/max-increase-to-keep-city-skyline/discuss/2653240/Python-oror-Easily-Understood-oror-Faster-than-96-oror-6-LINES-CODE
class Solution: def maxIncreaseKeepingSkyline(self, grid: List[List[int]]) -> int: ans = 0 for i in range(len(grid)): for j in range(len(grid[i])): column = max([grid[k][j]] for k in range(len(grid))) ans += (min(column[0], max(grid[i])) - grid[i][j]) return ans
max-increase-to-keep-city-skyline
🔥 Python || Easily Understood ✅ || Faster than 96% || 6 LINES CODE
rajukommula
0
8
max increase to keep city skyline
807
0.86
Medium
13,119
https://leetcode.com/problems/max-increase-to-keep-city-skyline/discuss/2562550/Python-every-step-explained-or-easy-and-simple-or-faster-than-80-or
class Solution: def maxIncreaseKeepingSkyline(self, grid: List[List[int]]) -> int: n = len(grid) verticals = [0]*n for i in range(n): for j in range(n): if grid[i][j] > verticals[j]: verticals[j] = grid[i][j] ans = 0 for i in range(n): for j in range(n): ans += min( max(grid[i]), verticals[j] ) - grid[i][j] return ans
max-increase-to-keep-city-skyline
✔️ Python every step explained | easy and simple | faster than 80% |
dc_devesh7
0
44
max increase to keep city skyline
807
0.86
Medium
13,120
https://leetcode.com/problems/max-increase-to-keep-city-skyline/discuss/2441289/python3-using-the-transpose-feature-of-a-matrix-95-faster
class Solution: def maxIncreaseKeepingSkyline(self, grid: List[List[int]]) -> int: #determine the max in each row and column maxrow = [max(i) for i in grid] maxcolumn = [max(i) for i in zip(*grid)] #transpose the matrix counts=0 for i in range(len(grid)): for j in range(len(grid[0])): counts+= min(maxrow[i],maxcolumn[j])-grid[i][j] return counts
max-increase-to-keep-city-skyline
[python3] using the transpose feature of a matrix, 95% faster
hhlinwork
0
18
max increase to keep city skyline
807
0.86
Medium
13,121
https://leetcode.com/problems/max-increase-to-keep-city-skyline/discuss/2412745/Python-3-intuirive-solution-or-faster-90-for-some-reason
class Solution: def maxIncreaseKeepingSkyline(self, grid: List[List[int]]) -> int: hor = [] ver = [0] * len(grid) for x in grid: hor.append(max(x)) for i in range(len(x)): ver[i] = max(ver[i], x[i]) total_sum = 0 for a in range(len(grid)): for b in range(len(grid)): if (grid[a][b] != ver[b]) and (grid[a][b] != hor[a]): total_sum += min(hor[a], ver[b]) - grid[a][b] return total_sum
max-increase-to-keep-city-skyline
Python 3 intuirive solution | faster 90% for some reason
BorisDvorkin
0
37
max increase to keep city skyline
807
0.86
Medium
13,122
https://leetcode.com/problems/max-increase-to-keep-city-skyline/discuss/2247060/Unique-approach
class Solution: def maxIncreaseKeepingSkyline(self, grid: List[List[int]]) -> int: L = R = len(grid) S = [0] * R for row in grid: for i in range(R): S[i] = max(S[i], row[i]) W = [0] * L i = 0 for row in grid: W[i] = max(row) i += 1 score = 0 for i in range(L * R): score += min(S[i % L], W[i // L]) - grid[i // L][i % L] return score
max-increase-to-keep-city-skyline
Unique approach
hubzado
0
12
max increase to keep city skyline
807
0.86
Medium
13,123
https://leetcode.com/problems/max-increase-to-keep-city-skyline/discuss/2074646/Easy-2-pass-solution-using-two-1D-arrays
class Solution: def maxIncreaseKeepingSkyline(self, grid: List[List[int]]) -> int: result = 0 n = len(grid) maxCol = [0 for _ in range(n)] maxRow = [0 for _ in range(n)] for i in range(n): for j in range(n): maxRow[i] = max(maxRow[i],grid[i][j]) maxCol[j] = max(maxCol[j],grid[i][j]) for i in range(n): for j in range(n): minDiff = min(maxRow[i],maxCol[j])-grid[i][j] result +=minDiff return result
max-increase-to-keep-city-skyline
Easy 2 pass solution using two 1D arrays
pratiksha0812
0
14
max increase to keep city skyline
807
0.86
Medium
13,124
https://leetcode.com/problems/max-increase-to-keep-city-skyline/discuss/1809059/807.-Max-Increase-to-Keep-City-Skyline-python-solution
class Solution: def maxIncreaseKeepingSkyline(self, grid: List[List[int]]) -> int: count = 0 for i in range(len(grid)): for j in range(len(grid)): curr = int(grid[i][j]) lC = [] lR = [] for x in range(len(grid)): lC.append(grid[x][j]) mC = max(lC) for y in range(len(grid)): lR.append(grid[i][y]) mR = max(lR) s = int(min(mC,mR)) diff = abs(s-curr) count += diff return count
max-increase-to-keep-city-skyline
807. Max Increase to Keep City Skyline python solution
seabreeze
0
48
max increase to keep city skyline
807
0.86
Medium
13,125
https://leetcode.com/problems/max-increase-to-keep-city-skyline/discuss/1753228/Faster-than-97.7
class Solution: def maxIncreaseKeepingSkyline(self, grid: List[List[int]]) -> int: row_max = [max(row) for row in grid] col_max = [max(col) for col in zip(*grid)] result=0 for i in range(len(grid)): for j in range(len(grid)): result+=min(row_max[i], col_max[j])-grid[i][j] return result
max-increase-to-keep-city-skyline
Faster than 97.7%
blackmishra
0
29
max increase to keep city skyline
807
0.86
Medium
13,126
https://leetcode.com/problems/max-increase-to-keep-city-skyline/discuss/1379694/Python3-easy-to-understand
class Solution: def maxIncreaseKeepingSkyline(self, grid: List[List[int]]) -> int: n=len(grid); m = len(grid[0]) result = [row[:] for row in grid]; gridInColumns = list(zip(*grid)) for i in range(n): for j in range(m): result[i][j] -= min(max(grid[i]), max(gridInColumns[j])) return sum([sum(row) for row in result])*(-1)
max-increase-to-keep-city-skyline
Python3 easy to understand
mikekaufman4
0
76
max increase to keep city skyline
807
0.86
Medium
13,127
https://leetcode.com/problems/max-increase-to-keep-city-skyline/discuss/1297599/easy-solution-beats-90
class Solution: def maxIncreaseKeepingSkyline(self, grid: List[List[int]]) -> int: s=0 colMax=[] for c in range(len(grid[0])): m=0 for r in range(len(grid)): if grid[r][c]>m: m=grid[r][c] colMax.append(m) rowMax=[] for i in grid: rowMax.append(max(i)) for i in range(len(grid)): for j in range(len(grid[i])): s+=abs(grid[i][j]-min(rowMax[i],colMax[j])) return(s)
max-increase-to-keep-city-skyline
easy solution beats 90%
prakharjagnani
0
54
max increase to keep city skyline
807
0.86
Medium
13,128
https://leetcode.com/problems/max-increase-to-keep-city-skyline/discuss/1041042/Python-or-Six-line-solution-or-Intuitive-or-Matrix-Transpose
class Solution: def maxIncreaseKeepingSkyline(self, grid: List[List[int]]) -> int: grid_t, result = list(zip(*grid)), 0 # We create the transpose here for i in range(len(grid)): for j in range(len(grid[0])): max_height = min(max(grid[i]), max(grid_t[j])) # we find the min(max row, max column) result += max_height - grid[i][j] # we subtract the difference! return result # voila
max-increase-to-keep-city-skyline
Python | Six line solution | Intuitive | Matrix Transpose
dev-josh
0
79
max increase to keep city skyline
807
0.86
Medium
13,129
https://leetcode.com/problems/max-increase-to-keep-city-skyline/discuss/494701/Python3-90.86-faster
class Solution: def maxIncreaseKeepingSkyline(self, grid: List[List[int]]) -> int: left_to_right = [] top_to_bottom = [] temp = [] res_max = 0 for i in grid: left_to_right.append(max(i)) for i in range(len(grid)): for j in range(len(grid[i])): temp.append(grid[j][i]) top_to_bottom.append(max(temp)) temp = [] for k in range(len(grid)): for l in range(len(grid[k])): t += min(top_to_bottom[l], left_to_right[k]) - grid[k][l] return res_max
max-increase-to-keep-city-skyline
Python3 90.86% faster
Dmx2
0
88
max increase to keep city skyline
807
0.86
Medium
13,130
https://leetcode.com/problems/max-increase-to-keep-city-skyline/discuss/468105/Python3-simple-solution-faster-than-96.11
class Solution: def maxIncreaseKeepingSkyline(self, grid: List[List[int]]) -> int: max_row,max_col=list(map(max,grid)),list(map(max,zip(*grid))) #print(list(max_row),list(max_col)) res = 0 for i in range(len(grid)): for j in range(len(grid[i])): res += min(max_row[i],max_col[j]) - grid[i][j] return res
max-increase-to-keep-city-skyline
Python3 simple solution, faster than 96.11%
jb07
0
86
max increase to keep city skyline
807
0.86
Medium
13,131
https://leetcode.com/problems/max-increase-to-keep-city-skyline/discuss/433169/76ms-12.8Mb-Python3
class Solution: def maxIncreaseKeepingSkyline(self, grid: List[List[int]]) -> int: # the tallest building at colIdx, rowIdx cannot be taller than the tallest building in the row, and in that column # grid may not be square so numTop could be different from numOfLeft numOfTop = len(grid[0]) # no. of buildings looking at the top/bottom numOfLeft = len(grid) # no. of buildings looking at the left or right topLimits = [0] * numOfTop leftLimits = [0] * numOfLeft for rowIdx in range(numOfLeft): # find the tallest height in each row leftLimits[rowIdx] = max(grid[rowIdx]) for colIdx in range(numOfTop): # find the tallest height in each column. topLimits[colIdx] = max(topLimits[colIdx], grid[rowIdx][colIdx]) skySum = 0 for rowIdx in range(numOfLeft): for colIdx in range(numOfTop): # get the shorter of the tallest building in the row, and column limit = min(topLimits[colIdx], leftLimits[rowIdx]) skySum += limit - grid[rowIdx][colIdx] # add the difference from the initial grid value return skySum
max-increase-to-keep-city-skyline
76ms, 12.8Mb Python3
ainlovescode
0
76
max increase to keep city skyline
807
0.86
Medium
13,132
https://leetcode.com/problems/max-increase-to-keep-city-skyline/discuss/266138/Python3
class Solution: def maxIncreaseKeepingSkyline(self, grid: List[List[int]]) -> int: # the vertical skyline is the max # of each column # the horizontal skyline is the max # of each row # a building's height should be min(max of that row, max of that column) size = len(grid) columns = rows_to_columns(grid) row_maxs = list(max(row) for row in grid) # horizontal skyline column_maxs = list(max(column) for column in columns) # vertical skyline total_increase = 0 for row in range(size): row_max = row_maxs[row] for column in range(size): column_max = column_maxs[column] max_height = min(column_max, row_max) actual_height = grid[row][column] total_increase += max_height - actual_height return total_increase def rows_to_columns(grid: List[List[int]]): columns = [] for i in range(len(grid)): column = [] for row in grid: column.append(row[i]) columns.append(column) return columns
max-increase-to-keep-city-skyline
Python3
rajashravan32
0
256
max increase to keep city skyline
807
0.86
Medium
13,133
https://leetcode.com/problems/soup-servings/discuss/1651208/Python-3-or-Bottom-up-and-Top-down-DP-or-Explanation
class Solution: def soupServings(self, n: int) -> float: @cache # cache the result for input (a, b) def dfs(a, b): if a <= 0 and b > 0: return 1 # set criteria probability elif a <= 0 and b <= 0: return 0.5 elif a > 0 and b <= 0: return 0 return (dfs(a-4, b) + dfs(a-3, b-1) + dfs(a-2, b-2) + dfs(a-1, b-3)) * 0.25 # dfs if n > 4275: return 1 # observe the distribution you will find `a` tends to be easier to get used up than `b` n /= 25 # reduce the input scale return dfs(n, n) # both soup have `n` ml
soup-servings
Python 3 | Bottom-up & Top-down DP | Explanation
idontknoooo
5
660
soup servings
808
0.433
Medium
13,134
https://leetcode.com/problems/soup-servings/discuss/1651208/Python-3-or-Bottom-up-and-Top-down-DP-or-Explanation
class Solution: def soupServings(self, n: int) -> float: if n > 4275: return 1 # handle special case n = n // 25 + (n%25 > 0) # count size of tabulation dp = [[0] * (n+1) for _ in range(n+1)] dp[n][n] = 1 for i in range(n, 0, -1): # starting from (n, n) for each soup for j in range(n, 0, -1): for a, b in [[4, 0], [3, 1], [2, 2], [1, 3]]: dp[max(0, i-a)][max(0, j-b)] += dp[i][j] * 0.25 # traverse backwards from (n,n) to (0,0) ans = dp[0][0] / 2 # half the probability when `a` &amp; `b` both use up at the same time for j in range(1, n+1): # plus when `a` use up first ans += dp[0][j] return ans
soup-servings
Python 3 | Bottom-up & Top-down DP | Explanation
idontknoooo
5
660
soup servings
808
0.433
Medium
13,135
https://leetcode.com/problems/soup-servings/discuss/932658/Python3-top-down-dp
class Solution: def soupServings(self, N: int) -> float: if N > 5000: return 1 @lru_cache(None) def fn(x, y): """Return """ if x <= 0 and y <= 0: return 0.5 if x <= 0 or y <= 0: return x <= 0 return 0.25*(fn(x-100, y) + fn(x-75, y-25) + fn(x-50, y-50) + fn(x-25, y-75)) return fn(N, N)
soup-servings
[Python3] top-down dp
ye15
2
170
soup servings
808
0.433
Medium
13,136
https://leetcode.com/problems/soup-servings/discuss/2828316/Python-(Simple-Dynamic-Programming)
class Solution: def soupServings(self, n): @lru_cache(None) def dfs(a,b): if a<=0 and b<=0: return 0.5 if a<=0: return 1 if b<=0: return 0 return 0.25*(dfs(a-100,b) + dfs(a-75,b-25) + dfs(a-50,b-50) + dfs(a-25,b-75)) return dfs(n,n) if n < 4840 else 1
soup-servings
Python (Simple Dynamic Programming)
rnotappl
0
3
soup servings
808
0.433
Medium
13,137
https://leetcode.com/problems/soup-servings/discuss/2241561/Python3-Solution
class Solution: def soupServings(self, n: int) -> float: if n >= 4276: return 1.0 @lru_cache(None) def f(a: int, b: int)->float: if a <= 0 and b <= 0: return 0.5 if a <= 0: return 1 if b <= 0: return 0 return (f(a-100,b) + f(a-75,b-25) + f(a-50,b-50) + f(a-25,b-75))*.25 return f(n,n)
soup-servings
Python3 Solution
creativerahuly
0
120
soup servings
808
0.433
Medium
13,138
https://leetcode.com/problems/expressive-words/discuss/1507874/Problem-description-is-horrible...-but-here's-simple-python-solution
class Solution: def expressiveWords(self, s: str, words: List[str]) -> int: def summarize(word): res = [] n = len(word) i, j = 0, 0 while i<=j and j <= n-1: while j <= n-1 and word[j] == word[i]: j += 1 res.append(word[i]) res.append(j-i) i = j return res t = 0 start = summarize(s) n = len(start)//2 def compare(w): r = summarize(w) if len(r) != len(start): return False for i in range(0, 2*n, 2): if start[i] != r[i]: return False elif start[i] == r[i]: if start[i+1] < r[i+1]: return False elif start[i+1] == r[i+1]: pass elif start[i+1] < 3: return False return True for w in words: if compare(w): t += 1 return t
expressive-words
Problem description is horrible... but here's simple python solution
byuns9334
3
483
expressive words
809
0.463
Medium
13,139
https://leetcode.com/problems/expressive-words/discuss/1509894/Python-solution-O(nk)
class Solution: def expressiveWords(self, s: str, words) -> int: def condenseWord (s): wordTable = [] repeatCounter = 1 condenseWord = "" for i in range(len(s)): if i == 0: continue if s[i] == s[i-1]: repeatCounter += 1 else: condenseWord += s[i-1] wordTable.append(repeatCounter) repeatCounter = 1 else: condenseWord += s[len(s)-1] wordTable.append(repeatCounter) return condenseWord, wordTable matchCounter = 0 sampleCondenseWord, sampleWordTable = condenseWord(s) for word in words: testCondenseWord, testWordTable = condenseWord(word) if sampleCondenseWord == testCondenseWord: for i in range(len(sampleCondenseWord)): if sampleWordTable[i] >= 3 and sampleWordTable[i] < testWordTable[i]: break if sampleWordTable[i] < 3 and sampleWordTable[i] != testWordTable[i]: break else: matchCounter += 1 return matchCounter
expressive-words
Python solution O(nk)
cindy7b
2
364
expressive words
809
0.463
Medium
13,140
https://leetcode.com/problems/expressive-words/discuss/1255617/python-easy-and-simple-solution
class Solution: def expressiveWords(self, s: str, words: List[str]) -> int: res=[] for word in words: res.append(self.check(s,word)) print(res) return sum(res) def check(self,s,x): i = j = 0 while i < len(s) and j < len(x): counts = 1 while i<len(s)-1 and s[i]==s[i+1]: i+=1 counts+=1 countx = 1 while j<len(x)-1 and x[j]==x[j+1]: j+=1 countx+=1 if s[i]!=x[j]: return 0 i+=1 j+=1 if counts<countx: return 0 if countx==counts: continue if counts<=2: return 0 return 1 if i>=len(s) and j>=len(x) else 0
expressive-words
python easy and simple solution
jaipoo
2
892
expressive words
809
0.463
Medium
13,141
https://leetcode.com/problems/expressive-words/discuss/2704178/python%3A-easy-to-understand-with-helper-function
class Solution: def expressiveWords(self, s: str, words: List[str]) -> int: # edge cases if len(s) == 0 and len(words) != 0: return False if len(words) == 0 and len(s) != 0: return False if len(s) == 0 and len(words) == 0: return True # helper function, compressing string and extract counts def compressor(s_word): init_string =[s_word[0]] array = [] start = 0 for i,c in enumerate(s_word): if c == init_string[-1]: continue array.append(i-start) start = i init_string += c array.append(i-start+1) return init_string,array res = len(words) s_split, s_array = compressor(s) for word in words: word_split = [''] word_array = [] word_split,word_array = compressor(word) if s_split == word_split: for num_s,num_word in zip(s_array,word_array): if num_s != num_word and num_s < 3 or num_word > num_s: res -= 1 break else: res -= 1 return res
expressive-words
python: easy to understand with helper function
zoey513
1
193
expressive words
809
0.463
Medium
13,142
https://leetcode.com/problems/expressive-words/discuss/2137014/python-3-oror-simple-solution-oror-O(n)O(1)
class Solution: def expressiveWords(self, s: str, words: List[str]) -> int: def groupWord(word): size = 1 for i in range(1, len(word)): if word[i] == word[i - 1]: size += 1 else: yield word[i - 1], size size = 1 yield word[-1], size yield ' ', 0 res = len(words) for word in words: for (sChar, sSize), (wordChar, wordSize) in zip(groupWord(s), groupWord(word)): if sChar != wordChar or sSize < wordSize or wordSize < sSize < 3: res -= 1 break return res
expressive-words
python 3 || simple solution || O(n)/O(1)
dereky4
1
179
expressive words
809
0.463
Medium
13,143
https://leetcode.com/problems/expressive-words/discuss/2792977/Python-solution-with-two-pointers-(readable-code)-%2B-few-test-cases
class Solution: # Time : O(num_of_words * max(len(s), len(w)) | Space : O(1) # w : word in words list def expressiveWords(self, s: str, words = List[str]) -> int: total_count = 0 for w in words: i = 0 j = 0 stretch = True while i < len(s) and j < len(w): if s[i] == w[j]: s_count = 1 s_idx = i while s_idx < len(s) - 1 and s[s_idx] == s[s_idx + 1]: s_count += 1 s_idx += 1 w_count = 1 w_idx = j while w_idx < len(w) - 1 and w[w_idx] == w[w_idx + 1]: w_count += 1 w_idx += 1 if s_count >= w_count and (s_count == w_count or s_count >= 3): i = i + s_count j = j + w_count else: stretch = False break else: stretch = False break if stretch and i == len(s) and j == len(w): total_count += 1 return total_count
expressive-words
Python solution with two pointers (readable code) + few test cases
SuvroBaner
0
3
expressive words
809
0.463
Medium
13,144
https://leetcode.com/problems/expressive-words/discuss/2749994/Straightforwards-O(n)-in-python3-beats-92
class Solution: def expressiveWords(self, s: str, words: List[str]) -> int: def groupings(s): res = [] i = 0 while i < len(s): c = s[i] l = 1 while i+l < len(s) and s[i+l] == c: l += 1 res.append((c,l)) i += l return res def equal(word, s): if len(word) != len(s): return False for i in range(len(word)): c1, l1 = word[i] c2, l2 = s[i] if c1 != c2: return False if l1 != l2 and (l1 > l2 or l2 == 2): return False return True s = groupings(s) return len([1 for word in words if equal(groupings(word), s)])
expressive-words
Straightforwards O(n) in python3, beats 92%
faKealias
0
10
expressive words
809
0.463
Medium
13,145
https://leetcode.com/problems/expressive-words/discuss/2161820/Python3-simple-2-pointers-solution
class Solution: def expressiveWords(self, s: str, words: List[str]) -> int: ans = 0 for word in words: i = 0 j = 0 match_found = True while i < len(s) and j < len(word): start_i = i start_j = j if s[i] != word[j]: match_found = False break while i + 1 < len(s) and s[i + 1] == s[i]: i += 1 while j + 1 < len(word) and word[j + 1] == word[j]: j += 1 num_i_chars = i - start_i + 1 num_j_chars = j - start_j + 1 diff = num_i_chars - num_j_chars if diff < 0: match_found = False break elif diff > 0: if num_j_chars + diff < 3: match_found = False break i += 1 j += 1 if i < len(s) or j < len(word): match_found = False if match_found: ans += 1 return ans
expressive-words
Python3 simple 2 pointers solution
myvanillaexistence
0
107
expressive words
809
0.463
Medium
13,146
https://leetcode.com/problems/expressive-words/discuss/1511576/Fastest-Compress-String-Algo
class Solution: def compress_s(self, S): s_s, s_n = [], [] cnt, prev = 1, S[0] for i, s in enumerate(S[1:]): if s == prev: cnt+=1 else: if prev != '': s_s.append(prev) s_n.append(cnt) cnt = 1 prev = s if prev != '': s_s.append(prev) s_n.append(cnt) return s_s, s_n def expressiveWords(self, s, words): tgt_s, tgt_n = self.compress_s(s) ret = 0 for w in words: w_s, w_n = self.compress_s(w) if tgt_s != w_s: continue idx, extendable = 0, 1 for tgt_c, w_c in zip(tgt_n, w_n): if tgt_c < w_c or (tgt_c > w_c and tgt_c < 3): extendable = 0 break ret += extendable return ret
expressive-words
Fastest Compress String Algo
BichengWang
0
199
expressive words
809
0.463
Medium
13,147
https://leetcode.com/problems/expressive-words/discuss/933500/Python3-check-words-in-parallel
class Solution: def expressiveWords(self, S: str, words: List[str]) -> int: queue = deque([(i, 0) for i in range(len(words))]) # set k = kk = 0 for k in range(len(S)): if k+1 == len(S) or S[k] != S[k+1]: cnt = k - kk + 1 kk = k + 1 for _ in range(len(queue)): i, j = queue.popleft() jj = j while j < len(words[i]) and words[i][j] == S[k]: j += 1 if jj != j and (cnt == j-jj or cnt > j-jj and cnt >= 3): queue.append((i, j)) return sum(j == len(words[i]) for i, j in queue)
expressive-words
[Python3] check words in parallel
ye15
0
128
expressive words
809
0.463
Medium
13,148
https://leetcode.com/problems/expressive-words/discuss/406062/Python-3-(eleven-lines)
class Solution: def expressiveWords(self, S: str, W: List[str]) -> int: LW, C, n = len(W), [], 0 for s in [S]+W: C.append([[],[]]) for k,g in itertools.groupby(s): C[-1][0].append(k), C[-1][1].append(len(list(g))) LC = len(C[0][0]) for i in range(1,LW+1): if C[0][0] != C[i][0]: continue for j in range(LC): if C[i][1][j] > C[0][1][j] or (C[i][1][j] < C[0][1][j] and C[0][1][j] == 2): break else: n += 1 return n - Junaid Mansuri
expressive-words
Python 3 (eleven lines)
junaidmansuri
-8
663
expressive words
809
0.463
Medium
13,149
https://leetcode.com/problems/chalkboard-xor-game/discuss/2729320/Simple-python-code-with-explanation
class Solution: def xorGame(self, nums): #create a variable 0 x = 0 #iterate over the elements in the nums for i in nums: #do xor of all the elements x ^= i #Alice wins in two situations : #1.if the xor is already 0 (x == 0 ) #2.if the length of nums is even because if alice got chance with even length and xor != 0 he will select a number so that he will leave the odd number of same integer #if nums == [a,a,a,b] then alice erase b so bob must erase from [a,a,a] so he will lose if he erase any number return x == 0 or len(nums)%2 == 0 #in other situations bob will win
chalkboard-xor-game
Simple python code with explanation
thomanani
0
11
chalkboard xor game
810
0.554
Hard
13,150
https://leetcode.com/problems/chalkboard-xor-game/discuss/1309713/Python3-1-line
class Solution: def xorGame(self, nums: List[int]) -> bool: return reduce(xor, nums) == 0 or not len(nums)&amp;1
chalkboard-xor-game
[Python3] 1-line
ye15
0
111
chalkboard xor game
810
0.554
Hard
13,151
https://leetcode.com/problems/subdomain-visit-count/discuss/914736/Python3-100-faster-100-less-memory-(32ms-14.1mb)
class Solution: def subdomainVisits(self, cpdomains: List[str]) -> List[str]: d = defaultdict(int) for s in cpdomains: cnt, s = s.split() cnt = int(cnt) d[s] += cnt pos = s.find('.') + 1 while pos > 0: d[s[pos:]] += cnt pos = s.find('.', pos) + 1 for x, i in d.items(): yield f'{i} {x}'
subdomain-visit-count
Python3 100% faster, 100% less memory (32ms, 14.1mb)
haasosaurus
10
1,300
subdomain visit count
811
0.752
Medium
13,152
https://leetcode.com/problems/subdomain-visit-count/discuss/271503/Python3-clean-solution-(64ms)-O(N)
class Solution: def subdomainVisits(self, cpdomains: List[str]) -> List[str]: hashmap = {} for cpdom in cpdomains: (num, domain) = (int(x) if i==0 else x for i, x in enumerate(cpdom.split(" "))) domains = domain.split('.') # split the domain by '.' for idx in reversed(range(len(domains))): subdomain = '.'.join(domains[idx:]) val = hashmap.get(subdomain, 0) # 0 if not found in hashmap val += num hashmap[subdomain] = val # print(hashmap) ans = [] for subdomain, count in hashmap.items(): ans.append(" ".join([str(count), subdomain])) # join count and subdomain using empty space (" ") return ans # Run / Memory: O(N) N - number of elements in the cpdomains
subdomain-visit-count
Python3 clean solution (64ms) - O(N)
steveohmn
5
1,100
subdomain visit count
811
0.752
Medium
13,153
https://leetcode.com/problems/subdomain-visit-count/discuss/351029/Solution-in-Python-3-(beats-~100)
class Solution: def subdomainVisits(self, cpdomains: List[str]) -> List[str]: D = {} for c in cpdomains: s = c.replace('.',' ').split() n = int(s[0]) for i in range(len(s)-1,0,-1): t = ".".join(s[i:]) D[t] = D[t] + n if t in D else n return [str(D[i])+" "+i for i in D] - Junaid Mansuri
subdomain-visit-count
Solution in Python 3 (beats ~100%)
junaidmansuri
2
1,000
subdomain visit count
811
0.752
Medium
13,154
https://leetcode.com/problems/subdomain-visit-count/discuss/1278913/Python3-faster-than-90.99-using-hashmap.
class Solution: def subdomainVisits(self, cpdomains: List[str]) -> List[str]: result = [] store = dict() for combination in cpdomains: spaceIndex = combination.index(" ") visitTime = int(combination[:spaceIndex]) fullDomain = combination[spaceIndex + 1:] string = "" for i in reversed(range(-1, len(fullDomain))): if fullDomain[i] == "." or i == -1: if string not in store: store[string] = visitTime else: store[string] += visitTime if i == -1: break string = fullDomain[i] + string for domain, time in store.items(): result.append(f"{time} {domain}") return result
subdomain-visit-count
Python3 - faster than 90.99%, using hashmap.
CC_CheeseCake
1
246
subdomain visit count
811
0.752
Medium
13,155
https://leetcode.com/problems/subdomain-visit-count/discuss/2738844/Python-easy-solution
class Solution: def subdomainVisits(self, cpdomains: List[str]) -> List[str]: hashmap=collections.defaultdict(int) for i in cpdomains: port, website=i.split() port=int(port) url="" for domain in website.split(".")[::-1]: url=domain+url hashmap[url]+=port url="."+url print(hashmap.items()) return [ str(port)+" "+url for url,port in hashmap.items()]
subdomain-visit-count
Python easy solution
yodhan
0
22
subdomain visit count
811
0.752
Medium
13,156
https://leetcode.com/problems/subdomain-visit-count/discuss/2562170/python3-faster-than-86-by-using-a-dictionary
class Solution: def subdomainVisits(self, cpdomains: List[str]) -> List[str]: ans = [] dic = {} for cpdomain in cpdomains: times = int(cpdomain.split(' ')[0]) domains = cpdomain.split(' ')[1] sub_domains = domains.split('.') for i in range(len(sub_domains)): init = '' for j in range(i,len(sub_domains)): init+=sub_domains[j]+'.' key = init[:-1] if key not in dic.keys(): dic[key]=times else: dic[key]+=times for key in dic.keys(): ans.append(str(dic[key])+' '+key) return ans
subdomain-visit-count
[python3] faster than 86% by using a dictionary
hhlinwork
0
22
subdomain visit count
811
0.752
Medium
13,157
https://leetcode.com/problems/subdomain-visit-count/discuss/2502183/Python-easy-solution
class Solution: def subdomainVisits(self, cpdomains: List[str]) -> List[str]: D = {} for c in cpdomains: count, *domains = c.replace(" ", ".").split(".") for i in range(1, len(domains)+1): key = ".".join(domains[-i:]) D[key] = D.get(key, 0)+int(count) return [str(v)+" "+k for k, v in D.items()]
subdomain-visit-count
Python easy solution
yhc22593
0
28
subdomain visit count
811
0.752
Medium
13,158
https://leetcode.com/problems/subdomain-visit-count/discuss/2278073/modular-python-solution
class Solution: def subdomainVisits(self, cpdomains: List[str]) -> List[str]: output, ans = {}, [] for domain in cpdomains : number, domain = domain.split(' ') sub_domain = domain.split('.') pair = '' print(sub_domain) for i in reversed(range(len(sub_domain))) : if i == len(sub_domain)-1 : pair += sub_domain[i] else : pair = sub_domain[i] +'.'+ pair print(pair) # output.append(str(number) + ' '+pair) if pair not in output.keys() : output[pair] = int(number) else : output[pair] += int(number) for key in output.keys() : ans.append(str(output[key]) + ' '+key) return ans
subdomain-visit-count
modular python solution
sghorai
0
35
subdomain visit count
811
0.752
Medium
13,159
https://leetcode.com/problems/subdomain-visit-count/discuss/1897457/Python-Solution-or-Over-99-Faster-or-HashMap-Based-or-Brute-Force-or-Clean-Code
class Solution: def subdomainVisits(self, cpdomains: List[str]) -> List[str]: store = defaultdict(int) for ele in cpdomains: number, domain = ele.split(" ") number = int(number) store[domain] += number x = domain.split(".") # we can make it scalable by adding code to find position of . if len(x) == 2: store[x[-1]] += number elif len(x) == 3: store['.'.join(x[1:])] += number store[x[-1]] += number for domains,num in store.items(): yield f"{num} {domains}"
subdomain-visit-count
Python Solution | Over 99% Faster | HashMap Based | Brute Force | Clean Code
Gautam_ProMax
0
68
subdomain visit count
811
0.752
Medium
13,160
https://leetcode.com/problems/subdomain-visit-count/discuss/1815866/Python3-Easy-to-understand-oror-beats-75
class Solution: def subdomainVisits(self, cpdomains: List[str]) -> List[str]: lookup = {} for cpdom in cpdomains: count, dom = cpdom.split(' ') ds = dom.split('.') pos_doms = [] for d in ds[::-1]: if pos_doms: cur = pos_doms[-1] dd = f'{d}.{cur}' pos_doms.append(dd) else: pos_doms.append(d) for pd in pos_doms: if pd in lookup: lookup[pd] += int(count) else: lookup[pd] = int(count) return [f'{count} {dom}' for dom, count in lookup.items()]
subdomain-visit-count
Python3 Easy to understand || beats 75%
dos_77
0
44
subdomain visit count
811
0.752
Medium
13,161
https://leetcode.com/problems/subdomain-visit-count/discuss/1735438/Short-and-Easy-Understood-Solution-or-Python
class Solution: def subdomainVisits(self, cpdomains: List[str]) -> List[str]: domain_dict={} for domains in cpdomains: rep,domain=domains.split() domain_dict[domain]=domain_dict.get(domain,0)+int(rep) for i in range(len(domain)): if domain[i]=='.': sub_domain=domain[i+1:] domain_dict[sub_domain]=domain_dict.get(sub_domain,0)+int(rep) output=["{} {}".format(str(v),k) for k,v in domain_dict.items()] return output
subdomain-visit-count
Short & Easy Understood Solution | Python
shandilayasujay
0
51
subdomain visit count
811
0.752
Medium
13,162
https://leetcode.com/problems/subdomain-visit-count/discuss/1734691/Python-97.24-memory-49.73-faster
class Solution: def subdomainVisits(self, cpdomains: List[str]) -> List[str]: domains = {} for pair in cpdomains: countpair = pair.split(" ") rep = int(countpair[0]) domain = countpair[1].split(".") for i in range(len(domain)): sub = '.'.join(domain[i:]) domains.setdefault(sub, []).append(rep) return [f'{sum(j)} {i}' for i, j in domains.items()]
subdomain-visit-count
[Python] 97.24% memory 49.73% faster
angelique_
0
55
subdomain visit count
811
0.752
Medium
13,163
https://leetcode.com/problems/subdomain-visit-count/discuss/1555462/Python-Solution-with-using-hashmap
class Solution: def subdomainVisits(self, cpdomains: List[str]) -> List[str]: d = collections.defaultdict(int) for cp in cpdomains: count, domains = cp.split(' ') idx = 0 while idx != -1: d[domains] += int(count) idx = domains.find('.') domains = domains[idx + 1:] res = [] for key in d: res.append("{} {}".format(d[key], key)) return res
subdomain-visit-count
[Python] Solution with using hashmap
maosipov11
0
77
subdomain visit count
811
0.752
Medium
13,164
https://leetcode.com/problems/subdomain-visit-count/discuss/1168924/Brute-force-solution-in-Python
class Solution: def subdomainVisits(self, cpdomains: List[str]) -> List[str]: helper_dict = dict() for el in cpdomains: split_pairs = el.split(" ") count = int(split_pairs[0]) domains = split_pairs[1] if domains not in helper_dict: helper_dict[domains] = count else: helper_dict[domains] += count i = 0 while i < len(domains): if domains[i] == ".": if domains[i+1:] in helper_dict: helper_dict[domains[i+1:]] += count else: helper_dict[domains[i+1:]] = count i += 1 result = list() for pair in helper_dict: visit_times = str(helper_dict[pair]) + " " + pair result.append(visit_times) return result
subdomain-visit-count
Brute force solution in Python
nancydyc
0
89
subdomain visit count
811
0.752
Medium
13,165
https://leetcode.com/problems/subdomain-visit-count/discuss/1081079/Python-or-Easy-to-understand
class Solution: def subdomainVisits(self, cpdomains: List[str]) -> List[str]: domtocount = {} for cpd in cpdomains: num, dom = cpd.split(" ",1) domtocount[dom] = domtocount.get(dom,0) + int(num) while len(dom.split(".", 1)) > 1: dom = dom.split(".", 1)[1] domtocount[dom] = domtocount.get(dom,0) + int(num) res =[] for dom,count in domtocount.items(): res.append(str(count) +" " + str(dom)) return res
subdomain-visit-count
Python | Easy to understand
timotheeechalamet
0
108
subdomain visit count
811
0.752
Medium
13,166
https://leetcode.com/problems/subdomain-visit-count/discuss/1077227/Python-solution-beats-90%2B-runtime-and-memory
class Solution: def subdomainVisits(self, cpdomains: List[str]) -> List[str]: ans = [] domainVisit = dict() for i in cpdomains: num, domain = i.split() domainVisit[domain] = domainVisit[domain] + int(num) if domain in domainVisit else int(num) index = domain.find(".") while index > 0: domain = domain[index+1:] index = domain.find(".") domainVisit[domain] = domainVisit[domain] + int(num) if domain in domainVisit else int(num) for k, v in domainVisit.items(): ans.append(str(v) + " " + k) return ans
subdomain-visit-count
Python solution beats 90+% runtime and memory
Carol007
0
123
subdomain visit count
811
0.752
Medium
13,167
https://leetcode.com/problems/subdomain-visit-count/discuss/1041409/Python3-simple-solution
class Solution: def subdomainVisits(self, cpdomains: List[str]) -> List[str]: d = {} for i in cpdomains: x = i.split(' ') d[x[1]] = d.get(x[1],0) + int(x[0]) a = 0 while True: b = x[1].find('.',a) if b == -1: break a = b+1 d[x[1][a:]] = d.get(x[1][a:],0) + int(x[0]) return [(str(d[i])+' '+i) for i in d]
subdomain-visit-count
Python3 simple solution
EklavyaJoshi
0
73
subdomain visit count
811
0.752
Medium
13,168
https://leetcode.com/problems/subdomain-visit-count/discuss/718912/Python3-Clean-Code-adityarev
class Solution: def subdomainVisits(self, cpdomains: List[str]) -> List[str]: counter: Map = {} for cpdomain in cpdomains: count: str domain: str count, domain = cpdomain.split(" ") subdomains: List[str] = domain.split(".") for i in range(len(subdomains)): con_sub: str = ".".join(subdomains[i:]) if con_sub not in counter: counter[con_sub] = "0" counter[con_sub] = str(int(counter[con_sub]) + int(count)) ans: List[str] = [] for k, v in counter.items(): cpdomain: str = " ".join([v, k]) ans.append(cpdomain) return ans
subdomain-visit-count
Python3 Clean Code - adityarev
adityarev
0
70
subdomain visit count
811
0.752
Medium
13,169
https://leetcode.com/problems/subdomain-visit-count/discuss/453594/Python3-solution-90
class Solution: def subdomainVisits(self, cpdomains: List[str]): counts = {} for cpdomain in cpdomains: count, address = cpdomain.split(' ') domain = '' for part in address.split('.')[::-1]: if domain == '': domain = part else: domain = part + '.' + domain if domain in counts.keys(): counts[domain] += int(count) else: counts[domain] = int(count) return [f"{v:d} {k:s}" for k, v in counts.items()]
subdomain-visit-count
Python3 solution - 90%
amir83f14
0
102
subdomain visit count
811
0.752
Medium
13,170
https://leetcode.com/problems/subdomain-visit-count/discuss/338351/Simple-and-readable-python-solution-or-Beats-99.86
class Solution: def subdomainVisits(self, cpdomains: List[str]) -> List[str]: d= {} for cpdomain in cpdomains: page = "" count, full_page = cpdomain.split(' ') sub_doms = full_page.split('.')[::-1] curr_page ="" for dom in sub_doms: curr_page = dom + curr_page if curr_page in d: d[curr_page] += int(count) else: d[curr_page] = int(count) curr_page = '.' + curr_page return [ " ".join([str(count), site]) for site,count in d.items()]
subdomain-visit-count
Simple and readable python solution | Beats 99.86 %
athulmurali
0
177
subdomain visit count
811
0.752
Medium
13,171
https://leetcode.com/problems/largest-triangle-area/discuss/1585033/Python-oror-Faster-than-93-oror-Simple-maths-oror-with-explanation
class Solution: def largestTriangleArea(self, points: List[List[int]]) -> float: area = 0 n = len(points) for i in range(n): x1,y1 = points[i] for j in range(i+1,n): x2,y2 = points[j] for k in range(j+1,n): x3,y3 = points[k] curr = abs(0.5*(x1*(y2-y3)+x2*(y3-y1)+x3*(y1-y2))) if curr>area: area = curr return area
largest-triangle-area
Python || Faster than 93% || Simple maths || with explanation
ana_2kacer
19
1,300
largest triangle area
812
0.6
Easy
13,172
https://leetcode.com/problems/largest-triangle-area/discuss/333629/Two-Solutions-in-Python-3-(Shoelace-Method-and-Heron's-Formula)
class Solution: def largestTriangleArea(self, p: List[List[int]]) -> float: L, A = len(p), 0 for i in range(L-2): for j in range(i+1,L-1): for k in range(j+1,L): R = Area_Shoelace(p[i],p[j],p[k]) A = max(A,R) return A def Area_Shoelace(a,b,c): return abs(a[0]*b[1]+b[0]*c[1]+c[0]*a[1]-(a[0]*c[1]+c[0]*b[1]+b[0]*a[1]))/2
largest-triangle-area
Two Solutions in Python 3 (Shoelace Method and Heron's Formula)
junaidmansuri
9
1,100
largest triangle area
812
0.6
Easy
13,173
https://leetcode.com/problems/largest-triangle-area/discuss/333629/Two-Solutions-in-Python-3-(Shoelace-Method-and-Heron's-Formula)
class Solution: def largestTriangleArea(self, p: List[List[int]]) -> float: L, A = len(p), 0 for i in range(L-2): for j in range(i+1,L-1): for k in range(j+1,L): R = Area_Heron(p[i],p[j],p[k]) A = max(A,R) return A def Area_Heron(r,s,t): a, b, c = math.hypot(r[0]-s[0],r[1]-s[1]), math.hypot(r[0]-t[0],r[1]-t[1]), math.hypot(s[0]-t[0],s[1]-t[1]) s = (a + b + c)/2 return (max(0,s*(s-a)*(s-b)*(s-c)))**.5 - Junaid Mansuri (LeetCode ID)@hotmail.com
largest-triangle-area
Two Solutions in Python 3 (Shoelace Method and Heron's Formula)
junaidmansuri
9
1,100
largest triangle area
812
0.6
Easy
13,174
https://leetcode.com/problems/largest-triangle-area/discuss/1007970/Easy-and-Clear-Solution-Python
class Solution: def largestTriangleArea(self, p: List[List[int]]) -> float: res=0 n=len(p) r,l=0,0 for i in range (1,n-1): for r in range(0,i): for l in range(i+1,n): newArea=(p[i][0]*p[r][1] + p[r][0]*p[l][1] +p[l][0]*p[i][1] - p[i][0]*p[l][1] - p[r][0]*p[i][1] - p[l][0]*p[r][1] )/2 newArea=abs(newArea) print(newArea) if newArea>res: res=newArea return res
largest-triangle-area
Easy & Clear Solution Python
moazmar
3
449
largest triangle area
812
0.6
Easy
13,175
https://leetcode.com/problems/largest-triangle-area/discuss/1352571/Easy-Python-Solution(99.40)
class Solution: def largestTriangleArea(self, points: List[List[int]]) -> float: area = 0 for i in range(len(points)-2): x1,y1=points[i] for j in range(i+1,len(points)-1): x2,y2=points[j] for k in range(j+1,len(points)): x3,y3=points[k] if abs(0.5*(x1*(y2-y3)+x2*(y3-y1)+x3*(y1-y2))) > area : area = abs(0.5*(x1*(y2-y3)+x2*(y3-y1)+x3*(y1-y2))) return area
largest-triangle-area
Easy Python Solution(99.40%)
Sneh17029
2
589
largest triangle area
812
0.6
Easy
13,176
https://leetcode.com/problems/largest-triangle-area/discuss/1918049/python-3-oror-clean-solution
class Solution: def largestTriangleArea(self, points: List[List[int]]) -> float: def area(x1, y1, x2, y2, x3, y3): return abs(x1*(y2 - y3) + x2*(y3 - y1) + x3*(y1 - y2)) / 2 n = len(points) res = 0 for i in range(n - 2): x1, y1 = points[i] for j in range(i + 1, n - 1): x2, y2 = points[j] for k in range(j + 1, n): x3, y3 = points[k] res = max(res, area(x1, y1, x2, y2, x3, y3)) return res
largest-triangle-area
python 3 || clean solution
dereky4
0
278
largest triangle area
812
0.6
Easy
13,177
https://leetcode.com/problems/largest-sum-of-averages/discuss/1633894/Python-3-Solution-Using-Memoization
class Solution: def largestSumOfAverages(self, nums: List[int], k: int) -> float: @lru_cache(maxsize=None) def maxAvgSum(index: int, partitions_left: int) -> int: if partitions_left == 1: return sum(nums[index:]) / (len(nums) - index) max_sum: float = 0.0 for i in range(index, len(nums) - (partitions_left - 1)): cur_sum: float = sum(nums[index:i + 1])/(i + 1 - index) cur_sum += maxAvgSum(i + 1, partitions_left - 1) max_sum = max(cur_sum, max_sum) return max_sum return maxAvgSum(0, k)
largest-sum-of-averages
Python 3 Solution Using Memoization
mlalma
1
100
largest sum of averages
813
0.529
Medium
13,178
https://leetcode.com/problems/largest-sum-of-averages/discuss/2596349/Python-Solution-or-Memoization
class Solution: def largestSumOfAverages(self, nums: List[int], k: int) -> float: def helper(ind, k, currSum, count): if ind>=n: return 0 if k==0: return -int(1e9) if dp[ind][count][k]!=-1: return dp[ind][count][k] currSum+=nums[ind] notTake=currSum/count + helper(ind+1, k-1, 0, 1) take=helper(ind+1, k, currSum, count+1) dp[ind][count][k]=max(take, notTake) return dp[ind][count][k] n=len(nums) dp=[[[-1]*(k+1) for i in range(n+1)] for i in range(n+1)] return helper(0, k, 0, 1)
largest-sum-of-averages
Python Solution | Memoization
Siddharth_singh
0
11
largest sum of averages
813
0.529
Medium
13,179
https://leetcode.com/problems/largest-sum-of-averages/discuss/1490536/Python-3-or-DP-or-Explanation
class Solution: def largestSumOfAverages(self, nums: List[int], k: int) -> float: pre_sum = [0] for num in nums: pre_sum.append(pre_sum[-1] + num) avg = lambda i, j: (pre_sum[i+1]-pre_sum[j+1])/(i-j) n = len(nums) dp = [[0] * k for _ in range(n)] for i in range(n): dp[i][0] = pre_sum[i+1] / (i+1) for i in range(1, n): for kk in range(1, k): for j in range(kk-1, i): dp[i][kk] = max(dp[i][kk], dp[j][kk-1] + avg(i, j)) return dp[n-1][k-1]
largest-sum-of-averages
Python 3 | DP | Explanation
idontknoooo
0
136
largest sum of averages
813
0.529
Medium
13,180
https://leetcode.com/problems/largest-sum-of-averages/discuss/933886/Python3-top-down-dp
class Solution: def largestSumOfAverages(self, A: List[int], K: int) -> float: prefix = [0] for x in A: prefix.append(prefix[-1] + x) # prefix sum @lru_cache(None) def fn(i, k): """Return largest sum of average of A[lo:hi+1] with at most k groups.""" if i == 1 or k == 1: return prefix[i]/i # boundary condition if i <= k: return prefix[i] # shortcut ans = fn(i, k-1) for ii in range(1, i): ans = max(ans, fn(i-ii, k-1) + (prefix[i] - prefix[i-ii])/ii) return ans return fn(len(A), K)
largest-sum-of-averages
[Python3] top-down dp
ye15
0
77
largest sum of averages
813
0.529
Medium
13,181
https://leetcode.com/problems/largest-sum-of-averages/discuss/573682/Basic-Non-optimal-code-to-understand-dp-(python3)
class Solution: def largestSumOfAverages(self, A: List[int], K: int) -> float: s=[0] for i in A: s.append(i+s[-1]); n=len(s); mini= -200000 d={}; def fun(old,new,k): temp=(old,new,k); if(temp in d.keys()): return d[temp] if(new>=n) or (old>=n): return mini; if(k==1): return (s[-1]-s[old])/(n-1-old); d[temp]= max(fun(old,new+1,k),fun(new,new+1,k-1)+((s[new]-s[old])/(new-old)) ); return d[temp] return fun(0,1,K); ```
largest-sum-of-averages
Basic Non-optimal code to understand dp (python3)
wasnik353
0
76
largest sum of averages
813
0.529
Medium
13,182
https://leetcode.com/problems/binary-tree-pruning/discuss/298312/Python-faster-than-98-16-ms
class Solution(object): def pruneTree(self, root): """ :type root: TreeNode :rtype: TreeNode """ if root==None: return None _l = self.pruneTree(root.left) _r = self.pruneTree(root.right) if root.val == 0 and _l == None and _r == None: return None else: root.left = _l root.right = _r return root
binary-tree-pruning
Python - faster than 98%, 16 ms
il_buono
8
826
binary tree pruning
814
0.726
Medium
13,183
https://leetcode.com/problems/binary-tree-pruning/discuss/2538777/Python-Elegant-and-Short-or-DFS
class Solution: """ Time: O(n) Memory: O(n) """ def pruneTree(self, root: TreeNode) -> TreeNode: return self._prune(root) @classmethod def _prune(cls, root: Optional[TreeNode]) -> Optional[TreeNode]: if not root: return None root.left = cls._prune(root.left) root.right = cls._prune(root.right) return root if (root.val or root.left or root.right) else None
binary-tree-pruning
Python Elegant & Short | DFS
Kyrylo-Ktl
4
408
binary tree pruning
814
0.726
Medium
13,184
https://leetcode.com/problems/binary-tree-pruning/discuss/2537131/Python-or-Recursive-Postorder
class Solution: def pruneTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: if root is None: return None if self.pruneTree(root.left) is None: root.left = None if self.pruneTree(root.right) is None: root.right = None if root.val != 1 and root.left is None and root.right is None: root = None return root
binary-tree-pruning
Python | Recursive Postorder
sr_vrd
3
291
binary tree pruning
814
0.726
Medium
13,185
https://leetcode.com/problems/binary-tree-pruning/discuss/2538060/Easy-python-8-line-solution
class Solution: def pruneTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: if root is None: return root .left=self.pruneTree(root.left) root.right=self.pruneTree(root.right) if root.val==0 and (root.left==None) and (root.right==None): return None return root
binary-tree-pruning
Easy python 8 line solution
shubham_1307
2
22
binary tree pruning
814
0.726
Medium
13,186
https://leetcode.com/problems/binary-tree-pruning/discuss/1356787/Python-3-fast-iterative-(beats-95.99-of-python3-submissions)
class Solution: def pruneTree(self, root: TreeNode) -> TreeNode: stack = [(root, False)] toprune = set() while stack: node, visited = stack.pop() if node: if visited: if node.left in toprune: node.left = None if node.right in toprune: node.right = None if node.val == 0 and node.left is None and node.right is None: toprune.add(node) else: stack.extend([(node, True), (node.left, False), (node.right, False)]) return root if root not in toprune else None
binary-tree-pruning
Python 3, fast iterative (beats 95.99 % of python3 submissions)
MihailP
2
107
binary tree pruning
814
0.726
Medium
13,187
https://leetcode.com/problems/binary-tree-pruning/discuss/933430/Python3-post-order-traversal
class Solution: def pruneTree(self, root: TreeNode) -> TreeNode: def fn(node): """Prune binary tree via post-order traversal.""" if not node: return False if not (left := fn(node.left)): node.left = None if not (right := fn(node.right)): node.right = None return left or right or node.val == 1 return root if fn(root) else None
binary-tree-pruning
[Python3] post-order traversal
ye15
2
85
binary tree pruning
814
0.726
Medium
13,188
https://leetcode.com/problems/binary-tree-pruning/discuss/933430/Python3-post-order-traversal
class Solution: def pruneTree(self, root: TreeNode) -> TreeNode: def fn(node): """Return pruned tree.""" if node: node.left, node.right = fn(node.left), fn(node.right) if node.left or node.val == 1 or node.right: return node return fn(root)
binary-tree-pruning
[Python3] post-order traversal
ye15
2
85
binary tree pruning
814
0.726
Medium
13,189
https://leetcode.com/problems/binary-tree-pruning/discuss/2571188/Python-or-Simple-recursive-solution-or-Faster-than-98.59
class Solution: def pruneTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: if root: root.left = self.pruneTree(root.left) root.right = self.pruneTree(root.right) if root.val or root.left or root.right: return root
binary-tree-pruning
Python | Simple recursive solution | Faster than 98.59%
ahmadheshamzaki
1
48
binary tree pruning
814
0.726
Medium
13,190
https://leetcode.com/problems/binary-tree-pruning/discuss/2541585/python-iteration-dfs-solution
class Solution: def check(self,node): stk=[node] while stk: temp=stk.pop() if temp.val==1: return False if temp.left: stk.append(temp.left) if temp.right: stk.append(temp.right) return True def pruneTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: # print(self.check(root)) if self.check(root): return None r=root stk=[root] while stk: temp=stk.pop() if temp.left: if self.check(temp.left): temp.left=None else: stk.append(temp.left) if temp.right: if self.check(temp.right): temp.right=None else: stk.append(temp.right) return r
binary-tree-pruning
python iteration dfs solution
benon
1
25
binary tree pruning
814
0.726
Medium
13,191
https://leetcode.com/problems/binary-tree-pruning/discuss/2537859/Python3-Solution-or-DFS-or-4-line
class Solution: def pruneTree(self, root): if not root: return None root.left = self.pruneTree(root.left) root.right = self.pruneTree(root.right) return root if root.val or root.left or root.right else None
binary-tree-pruning
✔ Python3 Solution | DFS | 4 line
satyam2001
1
41
binary tree pruning
814
0.726
Medium
13,192
https://leetcode.com/problems/binary-tree-pruning/discuss/2537555/python3-or-explained-or-easy-to-understand-or-binary-tree
class Solution: def pruneTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: return self.trav(root) def trav(self, root): if not root: return None root.left = self.trav(root.left) root.right = self.trav(root.right) if root.val == 1: # if node == 1 then return it return root if not root.left and not root.right: # else if 1 is not present in both left and right subtree the return None return None return root # return root
binary-tree-pruning
python3 | explained | easy to understand | binary tree
H-R-S
1
22
binary tree pruning
814
0.726
Medium
13,193
https://leetcode.com/problems/binary-tree-pruning/discuss/2465650/Pythonic-O(n)
class Solution: def pruneTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: if root.left: root.left = self.pruneTree(root.left) if root.right: root.right = self.pruneTree(root.right) return root if root.left or root.right or root.val else None
binary-tree-pruning
Pythonic O(n)
user5285r
1
21
binary tree pruning
814
0.726
Medium
13,194
https://leetcode.com/problems/binary-tree-pruning/discuss/1486691/Python-Clean-Postorder-DFS-or-99.30-faster
class Solution: def pruneTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: head = TreeNode(0, root) def postorder(node = head): if not node: return True L, R = postorder(node.left), postorder(node.right) if L: node.left = None if R: node.right = None if not (node.left or node.right) and node.val == 0: return True return False postorder() return head.left
binary-tree-pruning
[Python] Clean Postorder DFS | 99.30% faster
soma28
1
96
binary tree pruning
814
0.726
Medium
13,195
https://leetcode.com/problems/binary-tree-pruning/discuss/372148/Python-96-Simple-Clear
class Solution: def pruneTree(self, root: TreeNode) -> TreeNode: if not root: return None root.left = self.pruneTree(root.left) root.right = self.pruneTree(root.right) if root.left or root.right or root.val == 1: return root else: return None
binary-tree-pruning
Python 96% Simple, Clear
ilkercankaya
1
106
binary tree pruning
814
0.726
Medium
13,196
https://leetcode.com/problems/binary-tree-pruning/discuss/2541934/python3-use-head-node-inplace
class Solution: def pruneTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: head = TreeNode() head.left = root def dfs(node): if not node: return False left = dfs(node.left) right = dfs(node.right) if not left: node.left = None if not right: node.right = None return left | right | node.val == 1 dfs(head) return head.left
binary-tree-pruning
python3, use head node, inplace
pjy953
0
1
binary tree pruning
814
0.726
Medium
13,197
https://leetcode.com/problems/binary-tree-pruning/discuss/2540615/6-line-DFS-in-Python-3
class Solution: def pruneTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: if not root: return None root.left, root.right = map(self.pruneTree, (root.left, root.right)) if not any((root.left, root.right, root.val)): return None return root
binary-tree-pruning
6-line DFS in Python 3
mousun224
0
11
binary tree pruning
814
0.726
Medium
13,198
https://leetcode.com/problems/binary-tree-pruning/discuss/2540383/5-Lines-Easy-Python-Solution
class Solution: def pruneTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: if root: if root.left: root.left = self.pruneTree(root.left) if root.right: root.right = self.pruneTree(root.right) if root.left == None and root.right == None and root.val == 0: return None return root
binary-tree-pruning
5 Lines Easy Python Solution
zip_demons
0
9
binary tree pruning
814
0.726
Medium
13,199