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/queue-reconstruction-by-height/discuss/2665310/Python-O(N2)-O(1) | class Solution:
def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:
people.sort(key=lambda x: x[1])
people.sort(key=lambda x: x[0], reverse=True)
res = []
for h1, k in people:
res.insert(k, (h1, k))
return res | queue-reconstruction-by-height | Python - O(N^2), O(1) | Teecha13 | 0 | 6 | queue reconstruction by height | 406 | 0.728 | Medium | 7,100 |
https://leetcode.com/problems/queue-reconstruction-by-height/discuss/2509953/Best-Python3-implementation-oror-Very-simple | class Solution:
def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:
n = len(people)
people.sort()
ans = [[]]*n
i = 0
while people:
h,p = people.pop(0)
count= p
for i in range(n):
if count== 0 and ans[i] == []:
ans[i] = [h,p]
break
elif not ans[i] or (ans[i] and ans[i][0] >= h ):
count -= 1
return ans | queue-reconstruction-by-height | ✔️ Best Python3 implementation || Very simple | UpperNoot | 0 | 62 | queue reconstruction by height | 406 | 0.728 | Medium | 7,101 |
https://leetcode.com/problems/queue-reconstruction-by-height/discuss/2215448/Python-ez-solution | class Solution:
def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:
people.sort(key = lambda x: (-x[0], x[1]))
output = []
for p in people:
output.insert(p[1], p)
return output | queue-reconstruction-by-height | Python ez solution | KOJI_LIU | 0 | 7 | queue reconstruction by height | 406 | 0.728 | Medium | 7,102 |
https://leetcode.com/problems/queue-reconstruction-by-height/discuss/2214973/Python-solution-or-Queue-Reconstruction-by-Height | class Solution:
def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:
people.sort(key = lambda x : (-x[0], x[1]))
res = []
for x in people:
res.insert(x[1],x)
return res | queue-reconstruction-by-height | Python solution | Queue Reconstruction by Height | nishanrahman1994 | 0 | 22 | queue reconstruction by height | 406 | 0.728 | Medium | 7,103 |
https://leetcode.com/problems/queue-reconstruction-by-height/discuss/2214860/Python-O(N2) | class Solution:
def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:
result = []
for p in sorted(people, key=lambda p: (-p[0], p[1])) :
result.insert(p[1], p)
return result | queue-reconstruction-by-height | Python O(N^2) | blue_sky5 | 0 | 3 | queue reconstruction by height | 406 | 0.728 | Medium | 7,104 |
https://leetcode.com/problems/queue-reconstruction-by-height/discuss/2213177/Custom-Sorting-oror-Simplest-Approach | class Solution:
def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:
peoples = sorted(people, key=lambda x : [-x[0], x[1]])
n = len(peoples)
reconstructedQueue = []
for people in peoples:
reconstructedQueue.insert(people[1], people)
return reconstructedQueue | queue-reconstruction-by-height | Custom Sorting || Simplest Approach | Vaibhav7860 | 0 | 27 | queue reconstruction by height | 406 | 0.728 | Medium | 7,105 |
https://leetcode.com/problems/queue-reconstruction-by-height/discuss/2212204/Not-Optimized-oror-Brute-Force | class Solution:
def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:
people.sort()
N=len(people)
ans=[None]*N
for height,q in people:
i,j=0,-1
while i<N:
if not ans[i] or ans[i][0]==height:
j+=1
if j==q:
break
i+=1
ans[i]=[height,q]
return ans | queue-reconstruction-by-height | Not Optimized || Brute Force | chaurasiya_g | 0 | 5 | queue reconstruction by height | 406 | 0.728 | Medium | 7,106 |
https://leetcode.com/problems/queue-reconstruction-by-height/discuss/2211904/Python-easy-within-5-lines | class Solution:
def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:
output=[]
people.sort(key=lambda x: (-x[0], x[1]))
for a in people:
output.insert(a[1], a)
return output | queue-reconstruction-by-height | Python easy within 5 lines | shivam-rathod | 0 | 38 | queue reconstruction by height | 406 | 0.728 | Medium | 7,107 |
https://leetcode.com/problems/queue-reconstruction-by-height/discuss/2211816/O(n2)-solution-that-is-different-than-everyone-else's-insertsort-solution | class Solution:
def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:
people.sort()
res = [None for _ in range(len(people))]
for height, count in people:
tmp = 0
for i in range(len(res)):
if count == tmp and res[i] is None:
res[i] = [height, count]
break
if res[i] is None or res[i][0] == height:
tmp += 1
return res | queue-reconstruction-by-height | O(n^2) solution that is different than everyone else's insert/sort solution | sicp_rush | 0 | 5 | queue reconstruction by height | 406 | 0.728 | Medium | 7,108 |
https://leetcode.com/problems/queue-reconstruction-by-height/discuss/2079884/Python-or-Sorting | class Solution:
def reconstructQueue(self, pe: List[List[int]]) -> List[List[int]]:
l = [[-1,-1] for i in range(len(pe))]
pe.sort()
for i in range(len(pe)):
c = pe[i][1]
for j in range(len(pe)):
if c>0:
if l[j][0] != -1:
if l[j][0] >= pe[i][0]:
c -= 1
else:
continue
else:
c -= 1
else:
if l[j][0] == -1:
l[j] = pe[i]
break
return l | queue-reconstruction-by-height | Python | Sorting | Shivamk09 | 0 | 56 | queue reconstruction by height | 406 | 0.728 | Medium | 7,109 |
https://leetcode.com/problems/queue-reconstruction-by-height/discuss/1613647/Pythonic-solution-with-comments | class Solution:
def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:
people.sort(key=lambda x: (-x[0], x[1])) # here we sort given sequence: firstly, we're looking at the person's height, then we compare by people in front of
final_queue = [] # variable where we're going to store final queue
for person in people:
final_queue.insert(person[1], person)
return final_queue | queue-reconstruction-by-height | Pythonic solution with comments | Dany_Sulimov | 0 | 71 | queue reconstruction by height | 406 | 0.728 | Medium | 7,110 |
https://leetcode.com/problems/queue-reconstruction-by-height/discuss/1613162/Python3-Solution-with-using-sorting | class Solution:
def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:
people.sort(key=lambda x: (-x[0], x[1]))
res = []
for p in people:
res.insert(p[1], p)
return res | queue-reconstruction-by-height | [Python3] Solution with using sorting | maosipov11 | 0 | 42 | queue reconstruction by height | 406 | 0.728 | Medium | 7,111 |
https://leetcode.com/problems/queue-reconstruction-by-height/discuss/1331472/Python-3-segment-tree-or-O(n*log2(n))-T-or-O(n)-S | class Solution:
def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:
import math
result = [None]*len(people)
# initialize segment tree
# leafs is len((0, 1, 1, ...)) = len(people)
# sum(0, i) is how many empties positions in [0, i-1]
# notice: (> len(people)) followings leafs is 0 because 0 is neutral for + operation
tree = [0] * (2**(math.ceil(math.log2(len(people))) + 1)-1)
for i in range(len(tree) // 2 + 1, len(tree) // 2 + len(people)):
tree[i] = 1
# build segment tree
for i in range(len(tree) // 2 - 1, -1 , -1):
left, right = 2 * i + 1, 2 * i + 2
tree[i] = tree[left] + tree[right]
# update leaf segment tree O(log n)
def update(i, x):
i += len(tree) // 2
tree[i] = x
parent = (i // 2 - 1) if i % 2 == 0 else i // 2
while parent >= 0:
tree[parent] = tree[2*parent+1] + tree[2*parent+2]
parent = (parent // 2 - 1) if parent % 2 == 0 else parent // 2
# reduce by monoid (+) on [i; j] submassive by segment tree O(log n)
def value(i, j):
left_res, right_res = 0, 0
i += len(tree) // 2
j += len(tree) // 2
while i < j:
if i % 2 == 0:
left_res = left_res + tree[i]
if j % 2 != 0:
right_res = tree[j] + right_res
i //= 2
j = (j-2)//2
if i == j:
left_res = left_res + tree[i]
return left_res + right_res
# greedy algorithm:
# insert (num, cnt) to leftest pos x where sum(0, x) = cnt
arr = sorted(people, key=lambda x: x[1], reverse=True)
arr.sort(key=lambda x: x[0])
for i in range(len(arr)):
_, cnt = arr[i]
# binary search - get leftest position to insert
left, right = 0, len(arr)
while left < right:
mid = (left+right)//2
val = value(0, mid)
if val < cnt:
left = mid + 1
else:
right = mid
result[left] = arr[i]
# set value finded position (leaf) to 0 in segment tree
# notice: set to -1 if this is zeroth empty position
if left == 0:
update(left, -1)
else:
update(left, 0)
return result | queue-reconstruction-by-height | Python 3 segment tree | O(n*log^2(n)) T | O(n) S | CiFFiRO | 0 | 105 | queue reconstruction by height | 406 | 0.728 | Medium | 7,112 |
https://leetcode.com/problems/queue-reconstruction-by-height/discuss/673145/Small-Python3-Solution%3A-O(n2)-Time-and-O(n)-Space | class Solution:
def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:
res = []
# Sort the array, with descending order for height and ascending order for the number of taller persons ahead
people_sorted = sorted(people, key=lambda p: (p[0], -p[1]), reverse=True)
# Add persons to the result, at respective indices
for p in people_sorted:
res.insert(p[1], p)
return res | queue-reconstruction-by-height | Small Python3 Solution: O(n^2) Time and O(n) Space | schedutron | 0 | 81 | queue reconstruction by height | 406 | 0.728 | Medium | 7,113 |
https://leetcode.com/problems/trapping-rain-water-ii/discuss/1138028/Python3Visualization-BFS-Solution-With-Explanation | class Solution:
def trapRainWater(self, heightMap: List[List[int]]) -> int:
if not heightMap or not heightMap[0]:
return 0
# Initial
# Board cells cannot trap the water
m, n = len(heightMap), len(heightMap[0])
if m < 3 or n < 3:
return 0
# Add Board cells first
heap = []
for i in range(m):
for j in range(n):
if i == 0 or i == m - 1 or j == 0 or j == n - 1:
heapq.heappush(heap, (heightMap[i][j], i, j))
heightMap[i][j] = -1
# Start from level 0
level, res = 0, 0
while heap:
height, x, y = heapq.heappop(heap)
level = max(height, level)
for i, j in [(x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)]:
if 0 <= i < m and 0 <= j < n and heightMap[i][j] != -1:
heapq.heappush(heap, (heightMap[i][j], i, j))
# If cell's height smaller than the level, then it can trap the rain water
if heightMap[i][j] < level:
res += level - heightMap[i][j]
# Set the height to -1 if the cell is visited
heightMap[i][j] = -1
return res | trapping-rain-water-ii | [Python3][Visualization] BFS Solution With Explanation | Picassos_Shoes | 209 | 4,700 | trapping rain water ii | 407 | 0.475 | Hard | 7,114 |
https://leetcode.com/problems/trapping-rain-water-ii/discuss/2594894/Share-my-novel-solution-with-horizontal-scanning-(No-heap-used) | class Solution:
def trapRainWater(self, heightMap: List[List[int]]) -> int:
m, n = len(heightMap), len(heightMap[0])
if m < 3 or n < 3: return 0
# to simplify the code
def adjacent(i,j):
return [(i-1,j), (i+1,j), (i,j-1), (i,j+1)]
# first we sort all heights from the matrix and store their corresponding positions
# heights will be [(h1,[p1, p2,...]), (h2,[p1, p2, ...]), ...]
d = defaultdict(list)
for i in range(m):
for j in range(n):
d[heightMap[i][j]].append((i,j))
heights = sorted(d.items())
# initialization
volumn, area, h_lower = 0, 0, heights[0][0]
level = [[1 for j in range(n)] for i in range(m)]
for h, positions in heights:
volumn += area*(h-h_lower)
h_lower = h
leak = []
for i, j in positions:
# due to height rising, now this position may hold water
level[i][j] = 0
area += 1
if i == 0 or i == m-1 or j == 0 or j == n-1 or any([level[a][b] == -1 for a, b in adjacent(i,j)]):
# this position is reachable from outside, therefore cannot hold water
leak.append((i,j))
level[i][j] = -1
area -= 1
while leak:
i, j = leak.pop()
for a, b in adjacent(i,j):
if 0 <= a < m and 0 <= b < n and not level[a][b]:
# new leaking position found through DFS
leak.append((a,b))
level[a][b] = -1
area -= 1
return volumn | trapping-rain-water-ii | Share my novel solution with horizontal scanning (No heap used) | SquirrelRay | 0 | 33 | trapping rain water ii | 407 | 0.475 | Hard | 7,115 |
https://leetcode.com/problems/trapping-rain-water-ii/discuss/1947461/Python3-or-Priority-Queue-or-Binary-Search-Tree | class Solution:
def __init__(self):
self.visited=dict()
self.length=0
self.width=0
def minPriorityQueueBSTAdd(self, minPriorityQueue, value):
length=len(minPriorityQueue)
start=0
end=length-1
while start<=end:
mid=(start+end)//2
if minPriorityQueue[mid][0]>value[0]:
end=mid-1
else:
start=mid+1
if start>end:
minPriorityQueue.insert(start, value)
return minPriorityQueue
def getNeighbours(self, coor):
neighbours=[]
if coor[0]+1<=self.length-1 and not self.visited[coor[0]+1][coor[1]]:
neighbours.append([coor[0]+1, coor[1]])
if coor[0]-1>=0 and not self.visited[coor[0]-1][coor[1]]:
neighbours.append([coor[0]-1, coor[1]])
if coor[1]+1<=self.width-1 and not self.visited[coor[0]][coor[1]+1]:
neighbours.append([coor[0], coor[1]+1])
if coor[1]-1>=0 and not self.visited[coor[0]][coor[1]-1]:
neighbours.append([coor[0], coor[1]-1])
return neighbours
def trapRainWater(self, heightMap: List[List[int]]) -> int:
self.length=len(heightMap)
self.width=len(heightMap[0])
minPriorityQueue=[]
row=0
while row<self.length:
col=0
while col<self.width:
if (row==0 or row==self.length-1 or col==0 or col==self.width-1):
minPriorityQueue=self.minPriorityQueueBSTAdd(minPriorityQueue, [heightMap[row][col], row, col])
try:
self.visited[row].update({col: True})
except:
self.visited[row]={col: True}
else:
try:
self.visited[row].update({col: False})
except:
self.visited[row]={col: False}
col+=1
row+=1
storage=0
currentMinimumHeight=0
while len(minPriorityQueue)>0:
coor=minPriorityQueue.pop(0)[1:]
currentMinimumHeight=max(currentMinimumHeight, heightMap[coor[0]][coor[1]])
neighbours=self.getNeighbours(coor)
for neighbour in neighbours:
currentHeight=heightMap[neighbour[0]][neighbour[1]]
if currentHeight<currentMinimumHeight:
storage+=(currentMinimumHeight-currentHeight)
minPriorityQueue=self.minPriorityQueueBSTAdd(minPriorityQueue, [heightMap[neighbour[0]][neighbour[1]], neighbour[0], neighbour[1]])
self.visited[neighbour[0]][neighbour[1]]=True
return storage | trapping-rain-water-ii | Python3 | Priority Queue | Binary Search Tree | rajoriyas | 0 | 139 | trapping rain water ii | 407 | 0.475 | Hard | 7,116 |
https://leetcode.com/problems/trapping-rain-water-ii/discuss/1922157/Python3-easy-to-read-and-understand-or-heapq-or-2-solutions | class Solution:
def trapRainWater(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
visited = [[False for _ in range(n)] for _ in range(m)]
pq = []
for i in range(m):
visited[i][0] = True
heapq.heappush(pq, (grid[i][0], i, 0))
visited[i][n-1] = True
heapq.heappush(pq, (grid[i][n-1], i, n-1))
for j in range(n):
visited[0][j] = True
heapq.heappush(pq, (grid[0][j], 0, j))
visited[m-1][j] = True
heapq.heappush(pq, (grid[m-1][j], m-1, j))
res = 0
while pq:
val, x, y = heapq.heappop(pq)
if x > 0 and visited[x-1][y] == False:
visited[x-1][y] = True
if grid[x-1][y] < val:
res += (val-grid[x-1][y])
grid[x-1][y] = val
heapq.heappush(pq, (grid[x-1][y], x-1, y))
if y > 0 and visited[x][y-1] == False:
visited[x][y-1] = True
if grid[x][y-1] < val:
res += (val-grid[x][y-1])
grid[x][y-1] = val
heapq.heappush(pq, (grid[x][y-1], x, y-1))
if x < m-1 and visited[x+1][y] == False:
visited[x+1][y] = True
if grid[x+1][y] < val:
res += (val-grid[x+1][y])
grid[x+1][y] = val
heapq.heappush(pq, (grid[x+1][y], x+1, y))
if y < n-1 and visited[x][y+1] == False:
visited[x][y+1] = True
if grid[x][y+1] < val:
res += (val-grid[x][y+1])
grid[x][y+1] = val
heapq.heappush(pq, (grid[x][y+1], x, y+1))
return res | trapping-rain-water-ii | Python3 easy to read and understand | heapq | 2 solutions | sanial2001 | 0 | 243 | trapping rain water ii | 407 | 0.475 | Hard | 7,117 |
https://leetcode.com/problems/trapping-rain-water-ii/discuss/1922157/Python3-easy-to-read-and-understand-or-heapq-or-2-solutions | class Solution:
def trapRainWater(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
visited = set()
pq = []
for i in range(m):
visited.add((i, 0))
heapq.heappush(pq, (grid[i][0], i, 0))
visited.add((i, n-1))
heapq.heappush(pq, (grid[i][n-1], i, n-1))
for j in range(n):
visited.add((0, j))
heapq.heappush(pq, (grid[0][j], 0, j))
visited.add((m-1, j))
heapq.heappush(pq, (grid[m-1][j], m-1, j))
res = 0
while pq:
val, x, y = heapq.heappop(pq)
if x > 0 and (x-1, y) not in visited:
visited.add((x-1, y))
if grid[x-1][y] < val:
res += (val-grid[x-1][y])
grid[x-1][y] = val
heapq.heappush(pq, (grid[x-1][y], x-1, y))
if y > 0 and (x, y-1) not in visited:
visited.add((x, y-1))
if grid[x][y-1] < val:
res += (val-grid[x][y-1])
grid[x][y-1] = val
heapq.heappush(pq, (grid[x][y-1], x, y-1))
if x < m-1 and (x+1, y) not in visited:
visited.add((x+1, y))
if grid[x+1][y] < val:
res += (val-grid[x+1][y])
grid[x+1][y] = val
heapq.heappush(pq, (grid[x+1][y], x+1, y))
if y < n-1 and (x, y+1) not in visited:
visited.add((x, y+1))
if grid[x][y+1] < val:
res += (val-grid[x][y+1])
grid[x][y+1] = val
heapq.heappush(pq, (grid[x][y+1], x, y+1))
return res | trapping-rain-water-ii | Python3 easy to read and understand | heapq | 2 solutions | sanial2001 | 0 | 243 | trapping rain water ii | 407 | 0.475 | Hard | 7,118 |
https://leetcode.com/problems/trapping-rain-water-ii/discuss/1491886/Python3-priority-queue | class Solution:
def trapRainWater(self, heightMap: List[List[int]]) -> int:
m, n = len(heightMap), len(heightMap[0])
pq = []
for i in range(m):
heappush(pq, (heightMap[i][0], i, 0))
heappush(pq, (heightMap[i][n-1], i, n-1))
for j in range(1, n-1):
heappush(pq, (heightMap[0][j], 0, j))
heappush(pq, (heightMap[m-1][j], m-1, j))
ans = most = 0
while pq:
ht, i, j = heappop(pq)
most = max(most, ht)
for ii, jj in (i-1, j), (i, j-1), (i, j+1), (i+1, j):
if 0 < ii < m-1 and 0 < jj < n-1 and heightMap[ii][jj] != -1:
ans += max(0, most - heightMap[ii][jj])
heappush(pq, (heightMap[ii][jj], ii, jj))
heightMap[ii][jj] = -1 # mark "visited"
return ans | trapping-rain-water-ii | [Python3] priority queue | ye15 | 0 | 119 | trapping rain water ii | 407 | 0.475 | Hard | 7,119 |
https://leetcode.com/problems/longest-palindrome/discuss/2221045/Python-oror-counter-oror-explanation | class Solution:
def longestPalindrome(self, s: str) -> int:
oddFlag=0
count=collections.Counter(s)
ans=0
for k,v in count.items():
if v%2==1:
ans+=v-1
oddFlag= 1
else:
ans+=v
if oddFlag == 1:
return ans+1
return ans | longest-palindrome | Python || counter || explanation | palashbajpai214 | 9 | 465 | longest palindrome | 409 | 0.547 | Easy | 7,120 |
https://leetcode.com/problems/longest-palindrome/discuss/2832908/Python-Hash-Table-faster-than-99.88 | class Solution:
def longestPalindrome(self, s: str) -> int:
count = {} # Hash Table
ans = [] # every word's frequency
odd= 0 # store an odd number's frequency
for word in s:
if word not in count:
count[word] = 1
else:
count[word] += 1
for times in count.values():
ans.append(times)
if times % 2 != 0:
odd += 1 # calculate an odd number's frequency
if odd != 0:
return sum(ans) - odd + 1
elif odd == 0:
return sum(ans) - odd | longest-palindrome | [Python] Hash Table faster than 99.88% | isu10903027A | 3 | 242 | longest palindrome | 409 | 0.547 | Easy | 7,121 |
https://leetcode.com/problems/longest-palindrome/discuss/1847975/Python-easy-to-read-and-understand-or-set | class Solution:
def longestPalindrome(self, s: str) -> int:
t = set()
for i in s:
if i in t:
t.remove(i)
else:
t.add(i)
if len(t) == 0:
return len(s)
else:
return len(s)-len(t) + 1 | longest-palindrome | Python easy to read and understand | set | sanial2001 | 3 | 242 | longest palindrome | 409 | 0.547 | Easy | 7,122 |
https://leetcode.com/problems/longest-palindrome/discuss/1798443/Python-Simple-Solution | class Solution:
def longestPalindrome(self, s: str) -> int:
s = Counter(s)
e = 0
ss = 0
for i in s.values():
if i%2==0:
ss+=i
else:
ss += i-1
if e==0:
e=1
return ss + e | longest-palindrome | [Python] Simple Solution | zouhair11elhadi | 3 | 280 | longest palindrome | 409 | 0.547 | Easy | 7,123 |
https://leetcode.com/problems/longest-palindrome/discuss/2630057/Python-solution-using-dictionary | class Solution:
def longestPalindrome(self, s: str) -> int:
dic ={}
res = 0
odd = False
for i in s:
dic.update({i:s.count(i)})
for key,value in dic.items():
if value%2==0:
res += value
else:
res += value - 1
odd = True
if odd:
return res+1
else:
return res | longest-palindrome | Python solution using dictionary | Ashwinpillai9 | 1 | 330 | longest palindrome | 409 | 0.547 | Easy | 7,124 |
https://leetcode.com/problems/longest-palindrome/discuss/2413593/JAVA-PYTHON3-C%2B%2B-Easy-Solution | class Solution:
def longestPalindrome(self, s: str) -> int:
counts = {}
for c in s: counts[c] = counts.get(c, 0) + 1
result, odd_found = 0, False
for _, c in counts.items():
if c % 2 == 0: result += c
else:
odd_found = True
result += c - 1
if odd_found: result += 1
return result | longest-palindrome | [JAVA, PYTHON3, C++] Easy Solution | WhiteBeardPirate | 1 | 76 | longest palindrome | 409 | 0.547 | Easy | 7,125 |
https://leetcode.com/problems/longest-palindrome/discuss/2208899/Python3-Runtime%3A-40ms-76.32-memory%3A-14mb-21.11 | class Solution:
# Runtime: 40ms 76.32% memory: 14mb 21.11%
# O(n) || O(1); we are dealing with only 26 letters of english lowercase and 26 letters of english uppercase, or say it O(k) where k is the number of english alphabets that would be store.
def longestPalindrome(self, s: str) -> int:
hashMap = dict()
for i in s:
hashMap[i] = hashMap.get(i, 0) + 1
length = 0
singleChar = 0
for key in hashMap:
if hashMap[key] % 2 == 0:
length += hashMap[key]
else:
length += hashMap[key] - 1
singleChar = 1
return (length + singleChar) | longest-palindrome | Python3 Runtime: 40ms 76.32% memory: 14mb 21.11% | arshergon | 1 | 92 | longest palindrome | 409 | 0.547 | Easy | 7,126 |
https://leetcode.com/problems/longest-palindrome/discuss/1643107/Easy-Python-or-90-Speed-or-Two-Liner | class Solution:
def longestPalindrome(self, s):
C = Counter(s)
return (sum( (v>>1) for v in C.values() )<<1) + any( v%2 for v in C.values() ) | longest-palindrome | Easy Python | 90% Speed | Two-Liner | Aragorn_ | 1 | 245 | longest palindrome | 409 | 0.547 | Easy | 7,127 |
https://leetcode.com/problems/longest-palindrome/discuss/1188518/Super-Simple-Python-Solution-with-Comments | class Solution:
def longestPalindrome(self, s: str) -> int:
res = 0
# Initialize Frequency counter
freqDict = defaultdict(int)
for char in s:
freqDict[char] += 1
# Add the largest even number in each frequency to the result to ensure symmetry
for key, value in freqDict.items():
res += (value//2)*2
# If there is an additional letter available, this could be the "middle" character
if res < len(s):
res += 1
return res
# Time Complexity: O(n)
# Space Complexity: O(n) | longest-palindrome | Super Simple Python Solution with Comments | kevinvle1997 | 1 | 223 | longest palindrome | 409 | 0.547 | Easy | 7,128 |
https://leetcode.com/problems/longest-palindrome/discuss/792730/Python-Simple-to-understand-and-implement | class Solution:
def longestPalindrome(self, s: str) -> int:
counts = collections.Counter(s)
tot = 0
odd = False
for freq in counts.values():
if freq % 2 != 0: # if odd number, set flag
odd = True
tot += freq-1 # make the odd even by subtracting and add to total
else:
tot += freq
if odd:
return tot + 1 # adding 1 to consider one odd letter for the center
else:
return tot | longest-palindrome | Python - Simple to understand and implement | vdhyani96 | 1 | 60 | longest palindrome | 409 | 0.547 | Easy | 7,129 |
https://leetcode.com/problems/longest-palindrome/discuss/342995/Solution-in-Python-3 | class Solution:
def longestPalindrome(self, s: str) -> int:
D = {}
for c in s:
if c in D:
D[c] += 1
else:
D[c] = 1
L = D.values()
E = len([i for i in L if i % 2 == 1])
return sum(L) - E + (E > 0)
- Python 3
- Junaid Mansuri | longest-palindrome | Solution in Python 3 | junaidmansuri | 1 | 771 | longest palindrome | 409 | 0.547 | Easy | 7,130 |
https://leetcode.com/problems/longest-palindrome/discuss/2843409/4-lines-of-code-Python-faster-than-99.12.-Hash-map-and-bitwise | class Solution:
def longestPalindrome(self, s: str) -> int:
sum, map = 0, {}
for ch in s: map[ch] = map.get(ch, 0) + 1 # frequency hash map
for f in map.values(): sum += f - (f & 1) # sum up frequencies, subtract one for each odd
return min(sum + 1, len(s)) # off by one error correction | longest-palindrome | 4 lines of code Python, faster than 99.12%. Hash map and bitwise | JacobSulewski | 0 | 1 | longest palindrome | 409 | 0.547 | Easy | 7,131 |
https://leetcode.com/problems/longest-palindrome/discuss/2839570/Simple-Python-Solution | class Solution:
def longestPalindrome(self, s: str) -> int:
dic = Counter(s)
even = 0
odd = 0
for k in dic.keys():
if dic[k]%2 == 1:
odd += 1
even += dic[k] - 1
else:
even += dic[k]
if odd:
return even + 1
return even | longest-palindrome | Simple Python Solution | ajayedupuganti18 | 0 | 1 | longest palindrome | 409 | 0.547 | Easy | 7,132 |
https://leetcode.com/problems/longest-palindrome/discuss/2829464/Longest-Palindrome-or-Optimum-Solution-in-Python | class Solution:
def longestPalindrome(self, s: str) -> int:
res = 0
for i in collections.Counter(s).values():
res += i // 2 * 2
return min(res+1, len(s)) | longest-palindrome | Longest Palindrome | Optimum Solution in Python | jashii96 | 0 | 5 | longest palindrome | 409 | 0.547 | Easy | 7,133 |
https://leetcode.com/problems/longest-palindrome/discuss/2829404/Easy-python-solution | class Solution:
def longestPalindrome(self, s: str) -> int:
pair = set()
ans = 0
for i in s:
if i in pair:
ans += 1
pair.remove(i)
else:
pair.add(i)
return ans*2 + 1 if len(pair)>0 else ans*2 | longest-palindrome | Easy python solution | _debanjan_10 | 0 | 3 | longest palindrome | 409 | 0.547 | Easy | 7,134 |
https://leetcode.com/problems/longest-palindrome/discuss/2827108/Python-solution-or-easy-to-understand | class Solution:
def longestPalindrome(self, s: str) -> int:
counter = {}
res = 0
remains = 0
for chr in s:
counter[chr] = counter.get(chr, 0) + 1
for val in counter.values():
remains += val % 2
res += val - val % 2
return res + (1 if remains else 0) | longest-palindrome | Python solution | easy to understand | LaggerKrd | 0 | 4 | longest palindrome | 409 | 0.547 | Easy | 7,135 |
https://leetcode.com/problems/longest-palindrome/discuss/2826245/finding-pairs-of-alphabet | class Solution:
def longestPalindrome(self, s: str) -> int:
sorted_s = sorted(s)
sorted_s.append(0)
ans , i = 0 , 0
flag = True
while i < len(sorted_s)-1:
if sorted_s[i] == sorted_s[i+1]:
ans += 2
i +=2
else:
if flag:
i += 1
ans += 1
flag = False
else: i += 1
return ans | longest-palindrome | finding pairs of alphabet | roger880327 | 0 | 1 | longest palindrome | 409 | 0.547 | Easy | 7,136 |
https://leetcode.com/problems/longest-palindrome/discuss/2824010/How-can-this-beat-over-90 | class Solution:
def longestPalindrome(self, s: str) -> int:
nums = dict()
for l in s:
if not l in nums:
nums[l] = 1
else:
nums[l] += 1
res = 0
hasOne = False
for i in nums:
if nums[i] > 1:
if nums[i] % 2 == 0:
res += nums[i]
else:
res += nums[i] - 1
hasOne = True
if nums[i] == 1:
hasOne = True
if hasOne:
res += 1
return res | longest-palindrome | How can this beat over 90%? | BinFan | 0 | 3 | longest palindrome | 409 | 0.547 | Easy | 7,137 |
https://leetcode.com/problems/longest-palindrome/discuss/2782571/Simple-and-Straightforward-Python-Solution. | class Solution:
def longestPalindrome(self, s: str) -> int:
if not s: return 0
s_list: list[str] = sorted(list(s))
repeated_letters: list[str] = []
other_letters: list[str] = []
while s_list:
total_appearances = s_list.count(s_list[0])
# ex count == 2,4,6, ...
if total_appearances > 1 and total_appearances % 2 == 0:
target: list[str] = s_list[:total_appearances]
# use extend because we want to **unpack**
# a list into another list
repeated_letters.extend(target)
# update the string list here
s_list = s_list[total_appearances:]
# ex count == 3, 5
elif total_appearances > 1:
target: list[str] = s_list[:total_appearances-1]
repeated_letters.extend(target)
s_list = s_list[total_appearances - 1:]
# ex 1
else:
other_letters.append(s_list.pop(0))
longest_possible_palindrome: int = 1 if other_letters else 0
longest_possible_palindrome += len(repeated_letters)
return longest_possible_palindrome | longest-palindrome | Simple and Straightforward Python Solution. | kahuni | 0 | 11 | longest palindrome | 409 | 0.547 | Easy | 7,138 |
https://leetcode.com/problems/longest-palindrome/discuss/2778764/Python-Solution | class Solution:
def longestPalindrome(self, s: str) -> int:
count = 0
seen = set()
for c in s:
if c in seen:
seen.remove(c)
count += 2
else:
seen.add(c)
return count if len(seen) == 0 else count + 1 | longest-palindrome | Python Solution | mansoorafzal | 0 | 9 | longest palindrome | 409 | 0.547 | Easy | 7,139 |
https://leetcode.com/problems/longest-palindrome/discuss/2753877/Easy-Python-Solution-using-dictionary | class Solution:
def longestPalindrome(self, s: str) -> int:
# Frequency Hash Map for keeping the frequency of each unique character
freq = {}
for i in s:
freq[i] = freq.get(i,0) + 1
maxOdd = 0
evenSum = 0
for i in freq.values():
if i % 2 == 0:
evenSum += i # Collects the characters occuring in even no.s
else:
if i > maxOdd:
# If found a new maxOdd then collect the previous one in evenSum and also check is it was zero so that it doesn't add -1 to evenSum
evenSum += maxOdd - 1 if maxOdd != 0 else 0
maxOdd = i
else:
evenSum += i - 1 # Collect the greatest even integer less than the frequency
return maxOdd + evenSum | longest-palindrome | Easy Python Solution using dictionary | Suryansh_Codes | 0 | 14 | longest palindrome | 409 | 0.547 | Easy | 7,140 |
https://leetcode.com/problems/longest-palindrome/discuss/2737325/Python-Easy | class Solution:
def longestPalindrome(self, s: str) -> int:
from collections import Counter
if (s == s[::-1]):
return len(s)
ans = 0
count = Counter(s)
check = True
for key in count:
if (check):
if (count[key] % 2 == 1):
ans += 1
check = False
ans += ((count[key] // 2) * 2)
return ans | longest-palindrome | Python Easy | lucasschnee | 0 | 6 | longest palindrome | 409 | 0.547 | Easy | 7,141 |
https://leetcode.com/problems/longest-palindrome/discuss/2695271/Python-using-Dictionary | class Solution:
def longestPalindrome(self, s: str) -> int:
d=dict()
for i in s:
if i in d:
d[i]+=1
else:
d[i]=1
c=0
k=[0]
for i,j in d.items():
if j%2==0:
c=c+j
else:
k.append(j)
if len(d)==1 :
return c+max(k)
x=0
t=max(k)
for i in k:
if i>1:
x=x+i-1
if len(k)>1:
return c+x+1
else:
return c+x | longest-palindrome | Python using Dictionary | Mani_23_ | 0 | 8 | longest palindrome | 409 | 0.547 | Easy | 7,142 |
https://leetcode.com/problems/longest-palindrome/discuss/2692609/Simple-Python-soln-O(n) | class Solution:
def longestPalindrome(self, s: str) -> int:
oddFlag = False
s = collections.Counter(s)
res = 0
for key, value in s.items():
if value % 2 == 0:
res += value
if value % 2 == 1:
oddFlag = True
res += value - 1
return res + 1 if oddFlag else res | longest-palindrome | Simple Python soln O(n) | 113377code | 0 | 17 | longest palindrome | 409 | 0.547 | Easy | 7,143 |
https://leetcode.com/problems/longest-palindrome/discuss/2692036/Python3-or-HashTable | class Solution:
def longestPalindrome(self, s: str) -> int:
counter = Counter(s)
total = 0
for key in counter:
value = counter[key]
if value == 1:
continue
if value % 2 == 0:
total += value
counter[key] = 0
else:
total += value-1
counter[key] = 1
occurances = [counter[key] for key in counter if counter[key] > 0]
if len(occurances) > 0:
total += 1
return total | longest-palindrome | Python3 | HashTable | honeybadgerofdoom | 0 | 1 | longest palindrome | 409 | 0.547 | Easy | 7,144 |
https://leetcode.com/problems/longest-palindrome/discuss/2683048/Python-Easy-O(n) | class Solution:
def longestPalindrome(self, s: str) -> int:
h = Counter(s)
odd = 0
even = 0
odd_count = 0
for i,v in h.items():
if v%2 == 0:
even += v
else:
odd_count +=1
odd += v-1
if odd_count > 0:
odd += 1
return even + odd | longest-palindrome | Python Easy O(n) | anu1rag | 0 | 4 | longest palindrome | 409 | 0.547 | Easy | 7,145 |
https://leetcode.com/problems/longest-palindrome/discuss/2671574/Python-Solution-or-Counter-or-Faster-than-97 | class Solution:
def longestPalindrome(self, s: str) -> int:
n=len(s)
ans=1
count=Counter(s)
# print(count)
ans=0
flag=False
for value in count.values():
if value%2==0:
ans+=value
else:
# take only even count
ans+=value-1
flag=True
# take odd count of any one (odd occurring character)
if flag:
ans+=1
return ans | longest-palindrome | Python Solution | Counter | Faster than 97% | Siddharth_singh | 0 | 8 | longest palindrome | 409 | 0.547 | Easy | 7,146 |
https://leetcode.com/problems/longest-palindrome/discuss/2666288/Simple-python-beats-99 | class Solution:
def longestPalindrome(self, s: str) -> int:
seen = set()
longest = 0
for char in s:
if char in seen:
seen.remove(char)
longest += 2
else:
seen.add(char)
return longest + int(bool(seen)) | longest-palindrome | Simple python beats 99% | AlecLeetcode | 0 | 3 | longest palindrome | 409 | 0.547 | Easy | 7,147 |
https://leetcode.com/problems/longest-palindrome/discuss/2655449/Using-Hashmap-or-Python | class Solution:
def longestPalindrome(self, s: str) -> int:
hm = dict(Counter(s))
print(hm)
odd_present = False
max_even_count = 0
for i in hm.values():
if i % 2 == 0:
max_even_count += i
else:
max_even_count += i-1
odd_present = True
return max_even_count + 1 if odd_present else max_even_count | longest-palindrome | Using Hashmap | Python | hk_davy | 0 | 5 | longest palindrome | 409 | 0.547 | Easy | 7,148 |
https://leetcode.com/problems/longest-palindrome/discuss/2650088/Python3-Hash-bitwise-operations-O(n)-time-O(1)-space | class Solution:
def longestPalindrome(self, s: str) -> int:
a = Counter(s)
ans = 0
odd = 0
for _, fre in a.items():
ans += (fre & -2)
if fre & 1:
odd |= 1
return ans + odd | longest-palindrome | [Python3] Hash, bitwise operations, O(n) time, O(1) space | DG_stamper | 0 | 48 | longest palindrome | 409 | 0.547 | Easy | 7,149 |
https://leetcode.com/problems/longest-palindrome/discuss/2640465/Simple-Python-Explanation.-O(n)-time-O(1)-space-beats-88.74. | class Solution:
def longestPalindrome(self, s: str) -> int:
chars = {}
length = 0
for letter in s:
if letter not in chars or chars[letter] == 0:
chars[letter] = 1
else:
length += 2
chars[letter] = 0
for key in chars.keys():
if chars[key] == 1:
return length + 1
return length | longest-palindrome | Simple Python Explanation. O(n) time, O(1) space beats 88.74%. | AdamPaslawski | 0 | 4 | longest palindrome | 409 | 0.547 | Easy | 7,150 |
https://leetcode.com/problems/longest-palindrome/discuss/2631092/Fast-python-solution | class Solution:
def longestPalindrome(self, s: str) -> int:
key_map = Counter(s)
odd = 0
res = 0
for value in key_map.values():
quotient, remainder = divmod(value, 2)
if remainder == 1:
odd = 1
res += quotient*2
else:
res += value
return res + odd | longest-palindrome | Fast python solution | minghuizzzz | 0 | 9 | longest palindrome | 409 | 0.547 | Easy | 7,151 |
https://leetcode.com/problems/longest-palindrome/discuss/2604793/Python-Easy-Intuitive | class Solution:
def longestPalindrome(self, s: str) -> int:
d = Counter(s)
odd = []
c = 0
for i in d.values():
if i%2==0:
c += i
else:
odd.append(i)
if odd:
c = c + sum(odd) - len(odd) + 1
return c | longest-palindrome | Python Easy Intuitive | Vedant_Aero | 0 | 59 | longest palindrome | 409 | 0.547 | Easy | 7,152 |
https://leetcode.com/problems/longest-palindrome/discuss/2552514/Easy-Understanding-Python | class Solution:
def longestPalindrome(self, s: str) -> int:
hashTable = {}
hashSet = set()
count = 0
oddCheck = 0
for c in s:
if(c in hashTable):
hashTable[c]+=1
else:
hashTable[c]=1
for c in s:
if(c in hashSet):
pass
else:
if(hashTable[c]%2==0):
count+=hashTable[c]
else:
count+=hashTable[c]
if(oddCheck):
count-=1
oddCheck=1
hashSet.add(c)
return count | longest-palindrome | Easy Understanding Python | jxswxnth | 0 | 54 | longest palindrome | 409 | 0.547 | Easy | 7,153 |
https://leetcode.com/problems/longest-palindrome/discuss/2550912/Python-3-Need-little-help-with-the-solution | class Solution:
def longestPalindrome(self, s: str) -> int:
hash_map = dict()
for l in s:
if l in hash_map:
hash_map[l] += 1
else:
hash_map[l] = 1
p_len = 0
only_even = True
for key in hash_map.keys():
if hash_map[key] > 1:
if only_even and hash_map[key]%2 != 0:
only_even = False
p_len += hash_map[key]
return p_len+1 if only_even and len(s) > p_len else p_len | longest-palindrome | Python 3 - Need little help with the solution | rakshithgowdahr | 0 | 27 | longest palindrome | 409 | 0.547 | Easy | 7,154 |
https://leetcode.com/problems/longest-palindrome/discuss/2522949/I-misunderstood-this-question | class Solution:
def find_palindrome(self, word: str, left: int, right: int):
while 0 <= left and right <= len(word) - 1:
if word[left] == word[right]:
yield word[left: right + 1]
left -= 1
right += 1
def longestPalindrome(self, s: str) -> int:
len_s = len(s)
if not len_s:
return 0
elif len_s == 1:
return 1
palindromes = []
for i in range(1, len_s):
# odd pattern
for palindrome in self.find_palindrome(s, i - 1, i + 1):
palindromes.append(palindrome)
# even pattern
for palindrome in self.find_palindrome(s, i, i + 1):
palindromes.append(palindrome)
max_length = 0
for palindrome in palindromes:
max_length = max(len(palindrome), max_length)
return max_length
if __name__ == '__main__':
s = "abccccdd"
S = Solution()
print(S.longestPalindrome(s))
# >>> 4 | longest-palindrome | I misunderstood this question | namashin | 0 | 59 | longest palindrome | 409 | 0.547 | Easy | 7,155 |
https://leetcode.com/problems/longest-palindrome/discuss/2517220/Python-Solution-Explained-oror-easy-to-understand | class Solution:
def longestPalindrome(self, s: str) -> int:
if len(s)==1:
return 1
d={}
for i in s: #frequency calculated of every element
if i in d:
d[i]+=1
else:
d[i]=1
v=list(d.values()) #all values array of dictionary d
s1=0
for i in range(len(v)):
if v[i]%2!=0 and v[i]!=1: #if element has odd frequency then make it even by decrement 1
s1=s1+(v[i]-1)
elif v[i]%2==0:
s1+=v[i]
# this below condition is mentioned becoz if every element frequency is even then all frequency
#will be added from above code but if any element having odd frequency present in v
#then we can take any single element to add it in middle of palindrome string eg : dccaccd ,
# here 'a' has odd frequency andadded in mid
if len(s)>s1:
return s1+1
else:
return s1 | longest-palindrome | Python Solution - Explained || easy to understand ✔ | T1n1_B0x1 | 0 | 67 | longest palindrome | 409 | 0.547 | Easy | 7,156 |
https://leetcode.com/problems/longest-palindrome/discuss/2470028/Python-simple-hashmap-solution | class Solution:
def longestPalindrome(self, s: str) -> int:
count = collections.Counter(s)
res = 0
carry = 0
for k,v in count.items():
if v % 2 == 0:
res += v
else:
res += v - 1
carry = 1
return res + carry | longest-palindrome | Python simple hashmap solution | aruj900 | 0 | 58 | longest palindrome | 409 | 0.547 | Easy | 7,157 |
https://leetcode.com/problems/longest-palindrome/discuss/2462884/Using-HashMap-or-Python | class Solution:
def longestPalindrome(self, s: str) -> int:
dic = Counter(s)
even , odd = 0, 0
for i in dic:
if dic[i]%2==0:
even += dic[i]
else:
odd += (dic[i] -1)
hasOdd = any(dic[i] %2==1 for i in dic)
return even + odd + hasOdd | longest-palindrome | Using HashMap | Python | Abhi_-_- | 0 | 35 | longest palindrome | 409 | 0.547 | Easy | 7,158 |
https://leetcode.com/problems/longest-palindrome/discuss/2395286/Python-solution-Faster-than-96 | class Solution:
def longestPalindrome(self, s: str) -> int:
#Builds map
letters = {}
for i in s:
letters[i] = letters[i]+1 if i in letters else 1
#Calculates longest palyndrome based on the available number of each letter.
length = 0
for i in letters:
if letters[i] %2 == 0:
length += letters[i]
letters[i] = 0
else:
length += letters[i]-1
letters[i] = 1
return length+1 if 1 in letters.values() else length | longest-palindrome | Python solution - Faster than 96% | GMFB | 0 | 33 | longest palindrome | 409 | 0.547 | Easy | 7,159 |
https://leetcode.com/problems/longest-palindrome/discuss/2366626/Can-anybody-tell-me-what-is-wrong-with-my-python-solution-using-hashmap | class Solution:
def longestPalindrome(self, s: str) -> int:
hashmap = {}
if len(s) == 0:
return 0
for i in s:
if i not in hashmap:
hashmap[i] = 1
else:
hashmap[i]+= 1
#Longest odd chars + even chars
longest_odd_char = 0
even_chars = 0
print(hashmap)
for i in hashmap.keys():
if hashmap[i]%2 == 1: #odd char string
if hashmap[i] > longest_odd_char:
longest_odd_char = hashmap[i]
else:
even_chars += hashmap[i]
return longest_char + even_chars | longest-palindrome | Can anybody tell me what is wrong with my python solution using hashmap? | Arana | 0 | 45 | longest palindrome | 409 | 0.547 | Easy | 7,160 |
https://leetcode.com/problems/split-array-largest-sum/discuss/1901138/Python-Short-and-Simple-NLogSum | class Solution:
def splitArray(self, nums: List[int], m: int) -> int:
def isPossible(maxSum):
curr = count = 0
for i in nums:
count += (i + curr > maxSum)
curr = curr + i if i + curr <= maxSum else i
return count + 1 <= m
lo, hi = max(nums), sum(nums)
while lo <= hi:
mid = (lo + hi) // 2
if isPossible(mid): hi = mid - 1
else: lo = mid + 1
return lo | split-array-largest-sum | ✅ Python Short and Simple NLogSum | dhananjay79 | 3 | 112 | split array largest sum | 410 | 0.533 | Hard | 7,161 |
https://leetcode.com/problems/split-array-largest-sum/discuss/1433241/python-memoization-%2B-binary-search-O(mn-log-n) | class Solution:
def splitArray(self, nums: [int], m: int) -> int:
prefixSum = []
curSum = 0
for num in nums:
curSum += num
prefixSum.append(curSum)
self.prefixSum = prefixSum
memo = dict()
minMax = self.helper(0, m-1, memo)
return minMax
def getSum(self, start: int, end: int) -> int:
res = self.prefixSum[end]
res -= self.prefixSum[start-1] if start-1 >= 0 else 0
return res
def helper(self, index: int, splits: int, memo: dict) -> int:
if splits == 0:
subarray = self.getSum(index, len(self.prefixSum)-1)
return subarray
key = (index, splits)
if key in memo:
return memo[key]
minMax = float('inf')
maxIndex = len(self.prefixSum)-splits
for i in range (index, maxIndex):
subarray = self.getSum(index, i)
maxLeftover = self.helper(i+1, splits-1, memo)
maximum = max(subarray, maxLeftover)
minMax = min(minMax, maximum)
memo[key] = minMax
return minMax | split-array-largest-sum | python memoization + binary search O(mn log n) | maxkmy | 2 | 127 | split array largest sum | 410 | 0.533 | Hard | 7,162 |
https://leetcode.com/problems/split-array-largest-sum/discuss/1433241/python-memoization-%2B-binary-search-O(mn-log-n) | class Solution:
def splitArray(self, nums: [int], m: int) -> int:
prefixSum = []
curSum = 0
for num in nums:
curSum += num
prefixSum.append(curSum)
self.prefixSum = prefixSum
memo = [[-1] * m for i in range (len(nums))]
minMax = self.helper(0, m-1, memo)
return minMax
def getSum(self, start: int, end: int) -> int:
res = self.prefixSum[end]
res -= self.prefixSum[start-1] if start-1 >= 0 else 0
return res
def helper(self, index: int, splits: int, memo: [[int]]) -> int:
if splits == 0:
subarray = self.getSum(index, len(self.prefixSum)-1)
return subarray
if memo[index][splits] != -1:
return memo[index][splits]
minMax = float('inf')
low = index
high = len(self.prefixSum)-splits-1
while low <= high:
mid = low + (high-low) // 2
subarray = self.getSum(index, mid)
maxLeftover = self.helper(mid+1, splits-1, memo)
minMax = min(minMax, max(subarray, maxLeftover))
if subarray < maxLeftover:
low = mid+1
elif subarray > maxLeftover:
high = mid-1
else:
break
memo[index][splits] = minMax
return minMax | split-array-largest-sum | python memoization + binary search O(mn log n) | maxkmy | 2 | 127 | split array largest sum | 410 | 0.533 | Hard | 7,163 |
https://leetcode.com/problems/split-array-largest-sum/discuss/2108110/Python3-Runtime%3A-52ms-55.70-memory%3A-13.9mb-65.09 | class Solution:
def splitArray(self, nums: List[int], m: int) -> int:
array = nums
left, right = max(array), sum(array)
while left < right:
mid = (left + right) // 2
if self.canSplit(array, mid, m):
right = mid
else:
left = mid + 1
return left
def canSplit(self, array, mid, m):
countSubArray = 1
sumSubArray = 0
for num in array:
sumSubArray += num
if sumSubArray > mid:
sumSubArray = num
countSubArray += 1
if countSubArray > m:
return False
return True | split-array-largest-sum | Python3 Runtime: 52ms 55.70% memory: 13.9mb 65.09% | arshergon | 1 | 34 | split array largest sum | 410 | 0.533 | Hard | 7,164 |
https://leetcode.com/problems/split-array-largest-sum/discuss/1969588/Easy-To-Understand-Python-Code-oror-O(n*logn) | class Solution:
def splitArray(self, nums: List[int], m: int) -> int:
def linear(maxLimit):
summ = 0
div = 1
for i in nums:
summ += i
if summ > maxLimit:
summ = i
div += 1
return div
low,high = max(nums),sum(nums)
while low<=high:
mid = (low+high)//2
if linear(mid) > m:
low = mid + 1
else:
high = mid - 1
return low | split-array-largest-sum | Easy To Understand Python Code || O(n*logn) | gamitejpratapsingh998 | 1 | 35 | split array largest sum | 410 | 0.533 | Hard | 7,165 |
https://leetcode.com/problems/split-array-largest-sum/discuss/1899360/Python-Binary-Search-Solution | class Solution:
def splitArray(self, nums: List[int], m: int) -> int:
low, high = 0, 0
for n in nums:
low = max(low, n)
high += n
while low < high:
mid = (low + high) // 2
partitions = self.split_nums(nums, mid)
if partitions <= m:
high = mid
else:
low = mid + 1
return high
def split_nums(self, nums: List[int], limit: int) -> int:
partitions, total = 1, 0
for n in nums:
if total + n > limit:
total = 0
partitions += 1
total += n
return partitions | split-array-largest-sum | Python Binary Search Solution | atiq1589 | 1 | 58 | split array largest sum | 410 | 0.533 | Hard | 7,166 |
https://leetcode.com/problems/split-array-largest-sum/discuss/1871287/94-faster-python-solution-using-Binary-Search-approach. | class Solution:
def splitArray(self, nums: List[int], m: int) -> int:
minV = max(nums) #or min(nums)
maxV = sum(nums)
while minV <= maxV:
mid = minV+(maxV-minV)//2 #or (minV+maxV)//2
def check(nums,mid,m):
pieces = 1
s = 0
for i in range(len(nums)):
s += nums[i]
if s > mid:
pieces += 1
s = nums[i]
if s > mid:
return False
if pieces > m:
return False
return True
res = check(nums,mid,m)
if res == True:
maxV = mid - 1
else:
minV = mid + 1
return minV #or maxV+1 | split-array-largest-sum | 94% faster python solution using Binary Search approach. | 1903480100017_A | 1 | 44 | split array largest sum | 410 | 0.533 | Hard | 7,167 |
https://leetcode.com/problems/split-array-largest-sum/discuss/1838981/Python-3-(50ms)-or-Binary-Search-Space-Approach-or-Similar-to-Book-Allocation-Problem | class Solution:
def splitArray(self, num: List[int], d: int) -> int:
def isPossible(num,d,m):
ws,c=0,1
for i in range(len(num)):
if ws+num[i]<=m:
ws+=num[i]
else:
c+=1
if c>d or num[i]>m:
return False
ws=num[i]
return True
s,e,ans=0,sum(num),-1
while s<=e:
m=s+(e-s)//2
if isPossible(num,d,m):
ans=m
e=m-1
else:
s=m+1
return ans | split-array-largest-sum | Python 3 (50ms) | Binary Search Space Approach | Similar to Book Allocation Problem | MrShobhit | 1 | 93 | split array largest sum | 410 | 0.533 | Hard | 7,168 |
https://leetcode.com/problems/split-array-largest-sum/discuss/797905/Python3-binary-search-the-sum-space | class Solution:
def splitArray(self, nums: List[int], m: int) -> int:
def fn(val):
"""Return True if it is possible to split."""
cnt = sm = 0
for x in nums:
if sm + x > val:
cnt += 1
sm = 0
sm += x
return cnt+1 <= m
lo, hi = max(nums), sum(nums)
while lo < hi:
mid = lo + hi >> 1
if fn(mid): hi = mid
else: lo = mid + 1
return lo | split-array-largest-sum | [Python3] binary search the sum space | ye15 | 1 | 125 | split array largest sum | 410 | 0.533 | Hard | 7,169 |
https://leetcode.com/problems/split-array-largest-sum/discuss/797905/Python3-binary-search-the-sum-space | class Solution:
def splitArray(self, nums: List[int], m: int) -> int:
# prefix sum
prefix = [0]
for x in nums: prefix.append(prefix[-1] + x)
@lru_cache(None)
def fn(i, m):
"""Return the minimum of largest sum among m subarrays of nums[i:]."""
if m == 1: return prefix[-1] - prefix[i]
ans = inf #if not enough elements for m subarrays, inf is returned
for ii in range(i+1, len(nums)):
left = prefix[ii] - prefix[i]
right = fn(ii, m-1)
ans = min(ans, max(left, right))
return ans
return fn(0, m) | split-array-largest-sum | [Python3] binary search the sum space | ye15 | 1 | 125 | split array largest sum | 410 | 0.533 | Hard | 7,170 |
https://leetcode.com/problems/split-array-largest-sum/discuss/2808202/Binary-Search-With-Thorough-Explanations | class Solution:
def splitArray(self, nums: List[int], k: int) -> int:
"""
Time: O(n * log(sum(n))) where sum(n) is the sum of all values in nums
Space: O(n)
"""
def can_split(cutoff):
nonlocal k
splits = 0
subarr_sum = 0
for n in nums:
subarr_sum += n
if subarr_sum > cutoff:
# mark that we have split off to make a subarray
splits += 1
# start a new subarray sum
subarr_sum = n
# we add 1 here because splits + 1 == num subarrays
return splits + 1 <= k
# left should be the largest single element in the arr
# right is the total sum of the arr. If k is greater than 1,
# this should never be a valid result
l, r = max(nums), sum(nums)
res = 0
# start binary search. Use <= so that we can test mid values calculated by
# our l and r values that are equal.
while l <= r:
m = l + (r - l)//2
if can_split(m):
res = m
# adjust r to shorten window to explore smaller subarrays
r = m - 1
# the subarray cuttoff value is too little, we need to split subarrays
# to a larger minimum sum
else:
l = m + 1
return res | split-array-largest-sum | Binary Search With Thorough Explanations | safarovd | 0 | 5 | split array largest sum | 410 | 0.533 | Hard | 7,171 |
https://leetcode.com/problems/split-array-largest-sum/discuss/2713137/Py3-BinSearch-Step-by-step-Visualization-Explanation | class Solution:
def splitArray(self, nums: List[int], k: int) -> int:
def minimizable(threshold):
groups = 1
total = 0
for num in nums:
total += num
if total > threshold:
total = num
groups += 1
if groups > k:
return False
return True
left, right = max(nums), sum(nums)
while left < right:
mid = left + (right-left) // 2
if minimizable(mid):
right = mid
else:
left = mid + 1
return left | split-array-largest-sum | ⭐[Py3] BinSearch Step by step Visualization Explanation | bromalone | 0 | 2 | split array largest sum | 410 | 0.533 | Hard | 7,172 |
https://leetcode.com/problems/split-array-largest-sum/discuss/2684341/Python3-easy-solution | class Solution:
def splitArray(self, nums: List[int], k: int) -> int:
n=len(nums)
if n<k:return -1
def binarySearch(mid):
arrSum = 0
count = 1
for i in range(n):
if arrSum+nums[i]<=mid:
arrSum += nums[i]
else:
count+=1
if count>k or nums[i]>mid:
return False
arrSum = nums[i]
return True
begin = max(nums)
end = sum(nums)
res = -1
while begin<=end :
mid = (begin+end)//2
if binarySearch(mid):
res = mid
end = mid-1
else:
begin = mid+1
return res | split-array-largest-sum | Python3 easy solution | shashank732001 | 0 | 15 | split array largest sum | 410 | 0.533 | Hard | 7,173 |
https://leetcode.com/problems/split-array-largest-sum/discuss/2662877/Easy-to-understand-or-binary-search | class Solution:
def splits_for_max_sum(self, a, s, m):
i = 0
max_sum = 0
max_split = 0
while i < len(a):
# if some array ele > max_sum we are looking for (s) then spliting is not possible return 0
if a[i] > s:
return 0
while i < len(a) and max_sum + a[i] <= s:
max_sum += a[i]
i += 1
max_split += 1
max_sum = 0
return max_split
def splitArray(self, nums, m: int) -> int:
low = min(nums[0], nums[-1])
high = sum(nums)
# edge case
if len(nums) == m:
return max(nums)
while low<=high:
mid = (low+high)//2
max_plit = self.splits_for_max_sum(nums, mid, m)
# if the split return 0 means no split possible -- so we need to increse the max_sum.
# if max_plit <= given split -- we need decreese the sum we have taken -- so reducing the search space.
if max_plit <= m and max_plit != 0:
high = mid - 1
else:
low = mid + 1
return low | split-array-largest-sum | Easy to understand | binary search | Ninjaac | 0 | 6 | split array largest sum | 410 | 0.533 | Hard | 7,174 |
https://leetcode.com/problems/split-array-largest-sum/discuss/2351520/Python3-or-DP-Approach | class Solution:
def splitArray(self, nums: List[int], m: int) -> int:
n=len(nums)
ans=float('inf')
dp=[[-1 for i in range(m)] for j in range(n+1)]
def dfs(ind,lineCrossed):
if lineCrossed==m-1:
return sum(nums[ind:])
if dp[ind][lineCrossed]!=-1:
return dp[ind][lineCrossed]
ans,currSum=float('inf'),0
for i in range(ind,n-(m-lineCrossed-1)):
currSum+=nums[i]
if currSum>ans:break
maxSum=max(currSum,dfs(i+1,lineCrossed+1))
ans=min(ans,maxSum)
dp[ind][lineCrossed]=ans
return dp[ind][lineCrossed]
return dfs(0,0) | split-array-largest-sum | [Python3] | DP Approach | swapnilsingh421 | 0 | 33 | split array largest sum | 410 | 0.533 | Hard | 7,175 |
https://leetcode.com/problems/split-array-largest-sum/discuss/2312659/Simple-Plain-Solution | class Solution(object):
def splitArray(self, nums, m):
"""
:type nums: List[int]
:type m: int
:rtype: int
"""
def cansplit(largest):
subarray = 0
curSum = 0
for n in nums:
curSum+=n
if curSum>largest:
subarray +=1
curSum = n
return subarray+1<=m
l = max(nums)
r = sum(nums)
res = r
while l<=r:
mid = (l+(r-l)//2)
if cansplit(mid):
res = mid
r = mid-1
else:
l = mid+1
return res | split-array-largest-sum | Simple Plain Solution | Abhi_009 | 0 | 34 | split array largest sum | 410 | 0.533 | Hard | 7,176 |
https://leetcode.com/problems/split-array-largest-sum/discuss/2143914/Python-Solution-using-Binary-Searchor-Efficient-than-93-solutions | class Solution:
def splitArray(self, nums: List[int], m: int) -> int:
#Helper function to split the array into m
def canSplit(largest):
subarray = 0
curSum = 0
for n in nums:
curSum += n
if curSum > largest:
subarray += 1
curSum = n
return subarray + 1 <= m
# l is the minimum value a sum can have which is max(nums)
# r is the maximum value a sum can have which is sum(nums)
l, r = max(nums), sum(nums)
res = r
while l <= r:
mid = l + ((r - l) // 2)
if canSplit(mid): #if return true, we update our result with mid as its less than the max value the result has
res = mid
r = mid - 1
else:
l = mid + 1
return res | split-array-largest-sum | Python Solution using Binary Search| Efficient than 93% solutions | nikhitamore | 0 | 36 | split array largest sum | 410 | 0.533 | Hard | 7,177 |
https://leetcode.com/problems/split-array-largest-sum/discuss/1972984/Python-oror-Clean-and-Simple-Binary-Search | class Solution:
def splitArray(self, nums: List[int], m: int) -> int:
n = len(nums)
if n == m: return max(nums)
def guess(X):
if not X >= max(nums): return -1
i, sum_, split = 0, 0, 0
while i<n:
if sum_ + nums[i] <= X: sum_ += nums[i]
else:
split += 1
sum_ = nums[i]
i += 1
return split + 1
start, end = max(nums), sum(nums)
while start < end:
mid = (start+end) // 2
if guess(mid) <= m: end = mid
else: start = mid + 1
return start | split-array-largest-sum | Python || Clean and Simple Binary Search | morpheusdurden | 0 | 34 | split array largest sum | 410 | 0.533 | Hard | 7,178 |
https://leetcode.com/problems/split-array-largest-sum/discuss/1933519/Python-Solution-oror-90-Faster-oror-Memory-less-than-96 | class Solution:
def splitArray(self, nums: List[int], m: int) -> int:
def minNbrSubArr(mid):
sm=0 ; splits=1
for num in nums:
sm+=num
if sm>mid: sm=num ; splits+=1
return splits
lo=max(nums) ; hi=sum(nums)
while lo<=hi:
mid=(lo+hi)//2
if minNbrSubArr(mid)<=m: hi=mid-1
else: lo=mid+1
return lo | split-array-largest-sum | Python Solution || 90% Faster || Memory less than 96% | Taha-C | 0 | 43 | split array largest sum | 410 | 0.533 | Hard | 7,179 |
https://leetcode.com/problems/split-array-largest-sum/discuss/1901020/Python3-Solution-with-using-binary-search | class Solution:
# We check how many intervals will be obtained, provided that each of them is less than or equal to 'mid'
def helper(self, nums, mid, m):
cur_sum = 0
cuts = 1
for num in nums:
cur_sum += num
if cur_sum > mid:
cuts += 1
cur_sum = num
return cuts <= m
def splitArray(self, nums: List[int], m: int) -> int:
left = max(nums)
right = sum(nums)
ans = -1
while left <= right:
mid = (left + right) // 2
# If, as a result, the intervals for such a value are less than or equal to m, then we are looking for a number with which the intervals will either become larger or the same number will remain that satisfies the condition (interval_count == m)
if self.helper(nums, mid, m):
ans = mid
right = mid - 1
else:
left = mid + 1
return ans | split-array-largest-sum | [Python3] Solution with using binary search | maosipov11 | 0 | 18 | split array largest sum | 410 | 0.533 | Hard | 7,180 |
https://leetcode.com/problems/split-array-largest-sum/discuss/1899742/Python3-oror-Binary-Searchoror-O(nlogn)-time-oror | class Solution:
def splitArray(self, nums: List[int], m: int) -> int:
if len(nums) == m:
return max(nums)
#minimize the maximum: Binary Search
low, high = 0, sum(nums)
if m == 1:
return high
while low <= high:
mid = (low+high) // 2
#if mid can be the largest sum
if self.helper(nums,m,mid):
high = mid - 1
else:
low = mid + 1
return low
def helper(self,nums,m,target):
curr_sum = 0
m -= 1
for val in nums:
if val > target:
return False
curr_sum += val
if curr_sum > target:
m -= 1
curr_sum = val
if m < 0:
return False
return True | split-array-largest-sum | Python3 || Binary Search|| O(nlogn) time || | s_m_d_29 | 0 | 39 | split array largest sum | 410 | 0.533 | Hard | 7,181 |
https://leetcode.com/problems/split-array-largest-sum/discuss/1899661/Python-3-or-Binary-Search-or-Explanation | class Solution:
def splitArray(self, nums: List[int], m: int) -> int:
l, r = min(nums), sum(nums)
def ok(mx):
nonlocal m
cur = cnt = 0
for num in nums:
if num > mx:
return False
elif cur + num <= mx:
cur += num
else:
cur, cnt = num, cnt + 1
return cnt + 1 <= m
while l <= r:
mid = (l + r) // 2
if ok(mid):
r = mid - 1
else:
l = mid + 1
return l | split-array-largest-sum | Python 3 | Binary Search | Explanation | idontknoooo | 0 | 53 | split array largest sum | 410 | 0.533 | Hard | 7,182 |
https://leetcode.com/problems/split-array-largest-sum/discuss/1899085/Python-Simple-and-Easy-Python-Solution-Using-Binary-Search-oror-87.57-Faster | class Solution:
def splitArray(self, nums: List[int], m: int) -> int:
def max_sum_required(max_sum_value):
current_sum = 0
split_required = 0
for i in range(len(nums)):
if current_sum + nums[i] <= max_sum_value:
current_sum = current_sum + nums[i]
else:
current_sum = nums[i]
split_required = split_required + 1
return split_required + 1
result = 0
low = max(nums)
high = sum(nums)
while low <= high:
max_sum_value = ( low + high ) // 2
if max_sum_required(max_sum_value) <= m:
high = max_sum_value - 1
result = max_sum_value
else:
low = max_sum_value + 1
return result | split-array-largest-sum | [ Python ] ✅ Simple and Easy Python Solution Using Binary Search || 87.57 Faster 🔥✌ | ASHOK_KUMAR_MEGHVANSHI | 0 | 85 | split array largest sum | 410 | 0.533 | Hard | 7,183 |
https://leetcode.com/problems/split-array-largest-sum/discuss/1539315/Python3-Linear-search-to-Binary-search | class Solution:
def splitArray(self, nums: List[int], m: int) -> int:
"""
nums = [7,2,5,10,8], m = 2
subarray sum search range[max(nums), sum(nums)]
search for maximum subarray sum.
same number of cuts will have different maximum subbarry sum.
looking for the largest maximum subbarry sum.
as show below: the number of cut == 2, the maximum subarray sum range from 18 to 31.
why left most cut or the first cut?
because other's cuts corrisponding maximum sum doesn't exist.
eg, you can't find a subarray sum equals to 19, 20...31.
maximum subarray sum: 10 11 12 13 14 15 16 17 18 19 20........31 32
number of cuts needed: 4 4 4 3 3 3 3 3 2 2 2.........2 1
^
search leftmost number in a sorted(decreasing) array with duplicate numbers.
binary search
"""
ans1 = self.binarySearch(nums,m)
#ans2 = self.linerSearch(nums,m) # time limit exceeded when the search range is huge.
return ans1
def linerSearch(self,nums,m):
low = max(nums)
high = sum(nums)
ans = -1
for i in range(low, high+1):
if (self.validSplit(nums,m,i)):
return i
def binarySearch(self,nums,m):
low = max(nums)
high = sum(nums)
ans = -1
while low <= high:
mid = low + (high - low)//2
if (self.validSplit(nums,m,mid)):
high = mid - 1
ans = mid
else:
low = mid + 1
return ans
def validSplit(self,nums,m,mid):
cuts = 0
curSum = 0
for n in nums:
curSum += n
if curSum > mid:
cuts += 1
curSum = n
cuts += 1
#print( mid, cuts)
return cuts <= m | split-array-largest-sum | [Python3] Linear search to Binary search | zhanweiting | 0 | 179 | split array largest sum | 410 | 0.533 | Hard | 7,184 |
https://leetcode.com/problems/split-array-largest-sum/discuss/482582/Python3-binary-search-faster-than-98.09 | class Solution:
def splitArray(self, nums: List[int], m: int) -> int:
#return self.bruteForce(nums,m)
#self.cache=collections.defaultdict(dict)
#return self.memo(0,nums,m)
low,high,res=max(nums),sum(nums),-1
while low<=high:
pivot=(low+high)//2
if self.isValid(nums,m,pivot):
res,high=pivot,pivot-1
else:
low=pivot+1
return res
def isValid(self,nums,m,pivot):
chunk,current=0,0
for v in nums:
current+=v
if current>pivot:
chunk,current=chunk+1,v
return chunk + 1 <= m
def memo(self,i,nums,m):
if not nums: return 0
if m == 1: return sum(nums[i:])
if i in self.cache and m in self.cache[i]:
return self.cache[i][m]
self.cache[i][m]=float("inf")
for j in range(1,len(nums)+1):
left,right=sum(nums[i:i+j]),self.memo(i+j,nums,m-1)
self.cache[i][m]=min(self.cache[i][m],max(left,right))
if left>right: break
return self.cache[i][m]
def bruteForce(self,nums,m):
if not nums: return 0
if m == 1: return sum(nums)
min_value=float("inf")
for i in range(1,len(nums)+1):
left,right=sum(nums[:i]),self.bruteForce(nums[i:],m-1)
min_value=min(min_value,max(left,right))
return min_value | split-array-largest-sum | Python3 binary search faster than 98.09% | jb07 | 0 | 174 | split array largest sum | 410 | 0.533 | Hard | 7,185 |
https://leetcode.com/problems/fizz-buzz/discuss/380065/Solution-in-Python-3-(beats-~98)-(one-line) | class Solution:
def fizzBuzz(self, n: int) -> List[str]:
return ['FizzBuzz' if i%15 == 0 else 'Buzz' if i%5 == 0 else 'Fizz' if i%3 == 0 else str(i) for i in range(1,n+1)]
- Junaid Mansuri
(LeetCode ID)@hotmail.com | fizz-buzz | Solution in Python 3 (beats ~98%) (one line) | junaidmansuri | 6 | 1,900 | fizz buzz | 412 | 0.69 | Easy | 7,186 |
https://leetcode.com/problems/fizz-buzz/discuss/1786245/Python-3-(20ms)-or-Faster-than-99.7-or-Easy-to-Understand | class Solution:
def fizzBuzz(self, n: int) -> List[str]:
r=[]
while n:
if n%3==0 and n%5==0:
r.append("FizzBuzz")
elif n%3==0:
r.append("Fizz")
elif n%5==0:
r.append("Buzz")
else:
r.append(str(n))
n-=1
return r[::-1] | fizz-buzz | Python 3 (20ms) | Faster than 99.7% | Easy to Understand | MrShobhit | 5 | 490 | fizz buzz | 412 | 0.69 | Easy | 7,187 |
https://leetcode.com/problems/fizz-buzz/discuss/1707713/Easy-Without-Modulo-()-Operator | class Solution:
def fizzBuzz(self, n: int) -> List[str]:
a=1
b=1
l=[]
for i in range(1,n+1):
if a==3 and b==5:
l.append('FizzBuzz')
a=1
b=1
elif b==5:
l.append('Buzz')
b=1
a=a+1
elif a==3:
l.append('Fizz')
a=1
b=b+1
else:
l.append(str(i))
a=a+1
b=b+1
return l | fizz-buzz | Easy, Without Modulo (%) Operator | vkadu68 | 4 | 99 | fizz buzz | 412 | 0.69 | Easy | 7,188 |
https://leetcode.com/problems/fizz-buzz/discuss/1103629/Python3-Solution-%3A-Faster-than-94.80-and-Less-memory-usage-than-90.13 | class Solution:
def fizzBuzz(self, n: int) -> List[str]:
res = []
c3,c5 = 0,0
for i in range(1,n+1):
d = ""
c3 = c3+1
c5 = c5+1
if c3 == 3:
d += "Fizz"
c3 = 0
if c5 == 5:
d += "Buzz"
c5 = 0
res.append(d or str(i))
return res | fizz-buzz | Python3 Solution : Faster than 94.80% and Less memory usage than 90.13% | bhagwataditya226 | 3 | 278 | fizz buzz | 412 | 0.69 | Easy | 7,189 |
https://leetcode.com/problems/fizz-buzz/discuss/2178012/Python3-O(n)-oror-O(1)-Runtime%3A-359ms-91.92-Memory%3A-14.3mb-78.65 | class Solution:
# O(n) || O(n)
# Runtime: 44ms 90.88ms ; Memory: 14.9mb 84.93%
def fizzBuzz(self, n: int) -> List[str]:
result = []
for i in range(1, n + 1):
if i % 15 == 0:
char = "FizzBuzz"
elif i % 3 == 0:
char = "Fizz"
elif i % 5 == 0:
char = "Buzz"
else:
char = str(i)
result.append(char)
return result | fizz-buzz | Python3 O(n) || O(1) # Runtime: 359ms 91.92% ; Memory: 14.3mb 78.65% | arshergon | 2 | 240 | fizz buzz | 412 | 0.69 | Easy | 7,190 |
https://leetcode.com/problems/fizz-buzz/discuss/1623086/Python3-one-liner-easily-expandable | class Solution:
def fizzBuzz(self, n: int) -> List[str]:
return ["".join(s for d,s in [(3,"Fizz"),(5,"Buzz")] if i%d == 0) or str(i) for i in range(1,n+1)] | fizz-buzz | Python3 one liner easily expandable | pknoe3lh | 2 | 113 | fizz buzz | 412 | 0.69 | Easy | 7,191 |
https://leetcode.com/problems/fizz-buzz/discuss/1323879/Python-or-Most-Production-Ready-Code-or-Beats-99-in-Time-or-Compatibility-Awesome | class Solution:
def fizzBuzz(self, n: int) -> List[str]:
ans, num1, num2, bothTrue, firstTrue, secondTrue = [0]*n, 3, 5, "FizzBuzz", "Fizz", "Buzz"
for i in range(1,n+1):
first, second = i % num1 == 0, i % num2 == 0
if first and second: ans[i-1] = bothTrue
elif first: ans[i-1] = firstTrue
elif second: ans[i-1] = secondTrue
else: ans[i-1] = str(i)
return ans | fizz-buzz | Python | Most Production Ready Code | Beats 99% in Time | Compatibility Awesome | paramvs8 | 2 | 501 | fizz buzz | 412 | 0.69 | Easy | 7,192 |
https://leetcode.com/problems/fizz-buzz/discuss/2698601/Python-oror-O(N)ororRuntime-43-ms-Beats-95.46-Memory-15.1-MB-Beats-42.94 | class Solution:
def fizzBuzz(self, n: int) -> List[str]:
ans=[]
for i in range(1,n+1):
if i%3==0 and i%5==0:
ans.append("FizzBuzz")
elif i%5==0:
ans.append("Buzz")
elif i%3==0:
ans.append("Fizz")
else:
ans.append(str(i))
return ans | fizz-buzz | Python || O(N)||Runtime 43 ms Beats 95.46% Memory 15.1 MB Beats 42.94% | Sneh713 | 1 | 250 | fizz buzz | 412 | 0.69 | Easy | 7,193 |
https://leetcode.com/problems/fizz-buzz/discuss/2611048/Python3-most-easy-solution | class Solution:
def fizzBuzz(self, n: int) -> List[str]:
l=[]
for i in range(1,n+1):
if i%3==0 and i%5==0:
l.append("FizzBuzz")
elif i%3==0:
l.append("Fizz")
elif i%5==0:
l.append("Buzz")
else:
l.append(str(i))
return l | fizz-buzz | Python3 most easy solution | khushie45 | 1 | 334 | fizz buzz | 412 | 0.69 | Easy | 7,194 |
https://leetcode.com/problems/fizz-buzz/discuss/2373799/Memory-efficient-Python3-solution-oror-15MB-oror-Faster-than-65-oror-Explained! | class Solution:
def fizzBuzz(self, n: int) -> List[str]:
# Create dictionary to store mappings
dict_maps = {3: "Fizz", 5:"Buzz"}
fizzBuzz_list = []
#iterate over the keys
for i in range(1, n+1):
temp_str = ""
for key in dict_maps.keys():
#if number is divisible by key->append to string
if (i%key) == 0:
temp_str += dict_maps[key]
if not temp_str:
temp_str = str(i)
#append string to list at i-th place
fizzBuzz_list.append(temp_str)
return fizzBuzz_list | fizz-buzz | Memory efficient Python3 solution || 15MB || Faster than 65% || Explained! | harishmanjunatheswaran | 1 | 148 | fizz buzz | 412 | 0.69 | Easy | 7,195 |
https://leetcode.com/problems/fizz-buzz/discuss/2155863/Python-or-very-simple-solution-95-faster | class Solution:
def fizzBuzz(self, n: int) -> List[str]:
res = []
for i in range(1,n+1):
if i % 15 == 0:
res.append('FizzBuzz')
elif i % 3 == 0:
res.append('Fizz')
elif i % 5 == 0:
res.append('Buzz')
else:
res.append(str(i))
return res | fizz-buzz | Python | very simple solution 95% faster | __Asrar | 1 | 145 | fizz buzz | 412 | 0.69 | Easy | 7,196 |
https://leetcode.com/problems/fizz-buzz/discuss/1960630/Python-99-faster-and-99-less-memory-usage | class Solution:
def fizzBuzz(self, n: int) -> List[str]:
for i in range(1,n+1):
to_yield = ''
if i % 3 == 0:to_yield += 'Fizz'
if i % 5 == 0:to_yield += 'Buzz'
elif to_yield == '': to_yield = str(i)
yield to_yield | fizz-buzz | Python 99% faster and 99% less memory usage | Ipicon | 1 | 238 | fizz buzz | 412 | 0.69 | Easy | 7,197 |
https://leetcode.com/problems/fizz-buzz/discuss/1960568/Python-solution-using-yield-operator | class Solution:
def fizzBuzz(self, n: int) -> List[str]:
for i in range(1, n+1):
if i % 3 == 0 and i % 5 == 0:
yield 'FizzBuzz'
elif i%3==0:
yield 'Fizz'
elif i%5==0:
yield 'Buzz'
else:
yield f'{i}' | fizz-buzz | Python solution using yield operator | constantine786 | 1 | 54 | fizz buzz | 412 | 0.69 | Easy | 7,198 |
https://leetcode.com/problems/fizz-buzz/discuss/1072221/Python3-simple-solution-using-%22dictionary%22-and-%22if-else%22 | class Solution:
def fizzBuzz(self, n: int) -> List[str]:
d = {3 : "Fizz", 5 : "Buzz"}
res = []
for i in range(1,n+1):
ans = ''
if i % 3 == 0:
ans += d[3]
if i % 5 == 0:
ans += d[5]
if not ans:
ans = str(i)
res.append(ans)
return res | fizz-buzz | Python3 simple solution using "dictionary" and "if-else" | EklavyaJoshi | 1 | 97 | fizz buzz | 412 | 0.69 | Easy | 7,199 |
Subsets and Splits