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/boats-to-save-people/discuss/2319206/Python-2-pointers | class Solution(object):
def numRescueBoats(self, people, limit):
"""
:type people: List[int]
:type limit: int
:rtype: int
"""
people.sort()
count = 0
i = 0
j = len(people)-1
while i<=j:
sum_ = people[i]+people[j]
if sum_ > limit:
j-=1
count+=1
else:
i+=1
j-=1
count+=1
return count | boats-to-save-people | Python 2 pointers | Abhi_009 | 0 | 27 | boats to save people | 881 | 0.527 | Medium | 14,300 |
https://leetcode.com/problems/boats-to-save-people/discuss/1998783/Python-O(NlogN)-time-and-O(1)-space-oror-Two-pointers-oror-Easy-to-understand | class Solution:
def numRescueBoats(self, people: List[int], limit: int) -> int:
i, j = 0, len(people)-1
count = 0
people.sort()
while(i<=j):
if(people[i] + people[j] <= limit):
i+=1
j-=1
count+=1
return count | boats-to-save-people | Python O(NlogN) time and O(1) space || Two pointers || Easy to understand | shiva1gandluri | 0 | 44 | boats to save people | 881 | 0.527 | Medium | 14,301 |
https://leetcode.com/problems/boats-to-save-people/discuss/1883278/Python-SolutionorT%3AO(n)orS%3AO(1) | class Solution(object):
def numRescueBoats(self, people, limit):
people.sort()
num_boats, i, j = 0, 0, len(people) - 1
while i <= j:
if people[i] + people[j] > limit:
j -= 1
else:
i += 1
j -= 1
num_boats += 1
return num_boats | boats-to-save-people | Python Solution|T:O(n)|S:O(1) | pradeep288 | 0 | 11 | boats to save people | 881 | 0.527 | Medium | 14,302 |
https://leetcode.com/problems/boats-to-save-people/discuss/1880897/Python-simple-with-greedy-sorting-and-two-pointers.-O(nlogn)-time-and-O(1)-space-complexity | class Solution:
def numRescueBoats(self, people: List[int], limit: int) -> int:
n = len(people)
light, heavy = 0, n - 1
boats = 0
people.sort()
while light <= heavy:
if people[light] + people[heavy] <= limit and light != heavy:
boats += 1
light += 1
elif people[heavy] <= limit:
boats += 1
heavy -= 1
return boats | boats-to-save-people | Python, simple with greedy, sorting and two pointers. O(nlogn) time and O(1) space complexity | HunkWhoCodes | 0 | 13 | boats to save people | 881 | 0.527 | Medium | 14,303 |
https://leetcode.com/problems/boats-to-save-people/discuss/1880751/Easy-2-Pointer-Python3 | class Solution:
def numRescueBoats(self, people: List[int], limit: int) -> int:
counter = 0
people.sort()
l = 0
r = len(people)-1
while l <= r:
sm = people[l] + people[r]
if sm <= limit:
l += 1
r -= 1
elif people[r] <= limit:
r -= 1
else:
l += 1
counter += 1
return counter | boats-to-save-people | Easy 2 Pointer Python3 | neth_37 | 0 | 10 | boats to save people | 881 | 0.527 | Medium | 14,304 |
https://leetcode.com/problems/boats-to-save-people/discuss/1879902/Python-Straight-Forward-Simple-Two-Pointers | class Solution:
def numRescueBoats(self, people: List[int], limit: int) -> int:
# Track the number of boat rides
boats = 0
# Sort the weights
people.sort()
# Two pointers to start on both ends
lighter, heavier = 0, len(people)-1
# Keep trying to match lighter and heavier person
while lighter <= heavier:
# But if match exceeds limit, then just add heavier person
if people[lighter] + people[heavier] > limit:
heavier -= 1
# Otherwise we can add both persons to the next boat
else:
lighter += 1
heavier -= 1
# Either way, we used up a boat
boats += 1
return boats | boats-to-save-people | Python Straight Forward Simple Two Pointers | codewithcoffee | 0 | 7 | boats to save people | 881 | 0.527 | Medium | 14,305 |
https://leetcode.com/problems/boats-to-save-people/discuss/1879098/Python-Easy-6-lines-code-or-2-Ptr-Solution | class Solution:
def numRescueBoats(self, people: List[int], limit: int) -> int:
people.sort()
i,j, count = 0, len(people)-1, 0
while i<=j:
if people[i] + people[j] > limit: j-=1
else: i,j = i+1,j-1
count+=1
return count | boats-to-save-people | Python Easy 6 lines code | 2 Ptr Solution | sathwickreddy | 0 | 24 | boats to save people | 881 | 0.527 | Medium | 14,306 |
https://leetcode.com/problems/boats-to-save-people/discuss/1878708/easy-python-solution | class Solution:
def numRescueBoats(self, people: List[int], limit: int) -> int:
people.sort()
ans = 0
i = 0
j = len(people)-1
while i<=j:
ans+=1
if people[i]+people[j]<=limit:
i+=1
j-=1
return ans | boats-to-save-people | easy python solution | Brillianttyagi | 0 | 12 | boats to save people | 881 | 0.527 | Medium | 14,307 |
https://leetcode.com/problems/boats-to-save-people/discuss/1878592/Python3-Solution-with-using-two-pointers | class Solution:
def numRescueBoats(self, people: List[int], limit: int) -> int:
people.sort()
left, right = 0, len(people) - 1
res = 0
while left <= right:
if people[left] + people[right] <= limit:
left += 1
right -= 1
else:
right -= 1
res += 1
return res | boats-to-save-people | [Python3] Solution with using two-pointers | maosipov11 | 0 | 6 | boats to save people | 881 | 0.527 | Medium | 14,308 |
https://leetcode.com/problems/boats-to-save-people/discuss/1878241/Simple-2-Pointer-Python-Solution.-Faster-Than-91.4.-O(n)-Time-Complexity | class Solution:
def numRescueBoats(self, people: List[int], limit: int) -> int:
people.sort()
startPtr = 0
endPtr = len(people) - 1
boatCnt = 0
while startPtr <= endPtr:
if (people[startPtr] + people[endPtr]) <= limit:
startPtr += 1
endPtr -= 1
boatCnt += 1
else:
endPtr -= 1
boatCnt += 1
if startPtr == endPtr:
boatCnt += 1
return boatCnt | boats-to-save-people | Simple 2 Pointer Python Solution. Faster Than 91.4%. O(n) Time Complexity | harshnavingupta | 0 | 20 | boats to save people | 881 | 0.527 | Medium | 14,309 |
https://leetcode.com/problems/boats-to-save-people/discuss/1878105/python-3-oror-greedy-two-pointer-oror-O(nlogn)-O(n) | class Solution:
def numRescueBoats(self, people: List[int], limit: int) -> int:
people.sort()
n = len(people)
left, right = 0, n - 1
while left < right:
if people[left] + people[right] <= limit:
left += 1
right -= 1
return n - left | boats-to-save-people | python 3 || greedy / two pointer || O(nlogn) / O(n) | dereky4 | 0 | 20 | boats to save people | 881 | 0.527 | Medium | 14,310 |
https://leetcode.com/problems/boats-to-save-people/discuss/1878094/Python-Solution | class Solution:
def numRescueBoats(self, people: List[int], limit: int) -> int:
people.sort()
ans = 0
while people:
mx = people.pop()
if people:
if mx + people[0] <= limit:
ans += 1
people.pop(0)
else:
ans += 1
else:
ans += 1
return ans | boats-to-save-people | Python Solution | MS1301 | 0 | 12 | boats to save people | 881 | 0.527 | Medium | 14,311 |
https://leetcode.com/problems/boats-to-save-people/discuss/1878016/Two-pointer-%2B-Sorting-Time-O(n-log-n)-Solution-Faster-than-93 | class Solution:
def numRescueBoats(self, people: List[int], limit: int) -> int:
people.sort(reverse=True)
left = 0
right = len(people) - 1
boat_count = 0
while left <= right:
if left == right:
boat_count+=1
return boat_count
if people[left] + people[right] > limit:
boat_count+=1
left+=1
else:
boat_count+=1
left+=1
right-=1
return boat_count | boats-to-save-people | Two pointer + Sorting Time O(n log n) Solution Faster than 93% | EnergyBoy | 0 | 5 | boats to save people | 881 | 0.527 | Medium | 14,312 |
https://leetcode.com/problems/boats-to-save-people/discuss/1877980/Python-Easy-and-Simple-Solution-in-Python-Using-Two-Pointers-Approach | class Solution:
def numRescueBoats(self, people: List[int], limit: int) -> int:
people = sorted(people)
result = 0
start = 0
end = len(people) - 1
while start <= end:
if people[end] + people[start] <= limit:
start = start + 1
end = end - 1
result = result + 1
elif people[end] <= limit:
end = end - 1
result = result + 1
return result | boats-to-save-people | [Python]✔✌🔥✔ Easy and Simple Solution in Python Using Two Pointers Approach | ASHOK_KUMAR_MEGHVANSHI | 0 | 12 | boats to save people | 881 | 0.527 | Medium | 14,313 |
https://leetcode.com/problems/boats-to-save-people/discuss/1877861/Python-or-Greedy-or-Two-Pointers | class Solution:
def numRescueBoats(self, people: List[int], limit: int) -> int:
people.sort()
n = len(people)
# left point to the minimum
# right point to the maximum
left = 0
right = n -1
boats = 0
while left <= right:
if people[left] + people[right] <= limit:
left += 1
right -= 1
boats += 1
else:
boats += 1
right -= 1
return boats | boats-to-save-people | Python | Greedy | Two Pointers | Mikey98 | 0 | 12 | boats to save people | 881 | 0.527 | Medium | 14,314 |
https://leetcode.com/problems/boats-to-save-people/discuss/1876842/Python-easy-to-read-and-understand-or-two-pointers | class Solution:
def numRescueBoats(self, people: List[int], limit: int) -> int:
people.sort()
i, j = 0, len(people)-1
ans = 0
while i < j:
sums = people[i] + people[j]
if sums <= limit:
ans += 1
i, j = i+1, j-1
elif sums > limit:
ans += 1
j = j-1
ans += 1 if i == j else 0
return ans | boats-to-save-people | Python easy to read and understand | two-pointers | sanial2001 | 0 | 33 | boats to save people | 881 | 0.527 | Medium | 14,315 |
https://leetcode.com/problems/boats-to-save-people/discuss/1862845/Greedy-solution | class Solution:
def numRescueBoats(self, people: List[int], limit: int) -> int:
people.sort()
dp=[False for i in range(len(people))]
left=0
right=len(people)-1
answer=0
while left<=right:
if people[left]+people[right]<=limit:
answer+=1
left+=1
right-=1
else:
answer+=1
right-=1
return answer | boats-to-save-people | Greedy solution | g0urav | 0 | 14 | boats to save people | 881 | 0.527 | Medium | 14,316 |
https://leetcode.com/problems/boats-to-save-people/discuss/1813789/Python-3-(400ms)-or-Two-Pointers-Solution-or-Easy-to-Understand | class Solution:
def numRescueBoats(self, p: List[int], l: int) -> int:
p.sort()
c,i,j=0,0,len(p)-1
while i<=j:
if p[i]+p[j]<=l:
i+=1
c+=1
j-=1
return c | boats-to-save-people | Python 3 (400ms) | Two Pointers Solution | Easy to Understand | MrShobhit | 0 | 35 | boats to save people | 881 | 0.527 | Medium | 14,317 |
https://leetcode.com/problems/boats-to-save-people/discuss/946606/Python3-greedy-O(NlogN) | class Solution:
def numRescueBoats(self, people: List[int], limit: int) -> int:
people.sort() # ascending
ans, lo, hi = 0, 0, len(people)-1
while lo <= hi:
ans += 1
if lo < hi and people[lo] + people[hi] <= limit: lo += 1
hi -= 1
return ans | boats-to-save-people | [Python3] greedy O(NlogN) | ye15 | 0 | 76 | boats to save people | 881 | 0.527 | Medium | 14,318 |
https://leetcode.com/problems/reachable-nodes-in-subdivided-graph/discuss/2568608/BFS-intuitive | class Solution:
def reachableNodes(self, edges: List[List[int]], maxMoves: int, n: int) -> int:
graph = collections.defaultdict(dict)
for s, e, n in edges: # n: subnodes in edge
graph[s][e] = n
graph[e][s] = n
seen = set() # (start, end, step)
q = collections.deque()
for n in graph[0]:
q.append((0, n, 0))
res = 1
move = maxMoves
while q:
for _ in range(len(q)):
start, end, step = q.popleft()
seen.add((start, end, step))
seen.add((end, start, graph[end][start]-step+1))
if step == graph[start][end] + 1: #check if reached next node
for n in graph[end]:
if (end, n, 1) not in seen:
q.append((end, n, 1))
res += 1
else:
if (start, end, step+1) not in seen and (end, start, graph[end][start]-step) not in seen:
q.append((start, end, step+1))
res += 1
move -= 1
if move == 0:
break
return res | reachable-nodes-in-subdivided-graph | BFS intuitive | scr112 | 0 | 15 | reachable nodes in subdivided graph | 882 | 0.503 | Hard | 14,319 |
https://leetcode.com/problems/reachable-nodes-in-subdivided-graph/discuss/1463514/Python3-Dijkstra's-algo | class Solution:
def reachableNodes(self, edges: List[List[int]], maxMoves: int, n: int) -> int:
graph = defaultdict(dict)
for u, v, w in edges: graph[u][v] = graph[v][u] = w
ans = 0
pq = [(0, 0)] # min-heap
seen = [False] * n
used = defaultdict(int)
while pq:
x, u = heappop(pq)
if not seen[u]:
ans += 1
seen[u] = True
for v, c in graph[u].items():
if not used[u, v]:
if used[v, u] < graph[v][u]:
used[u, v] = min(maxMoves - x, graph[v][u] - used[v, u])
ans += used[u, v]
if x + c + 1 <= maxMoves and not seen[v]: heappush(pq, (x + c + 1, v))
return ans | reachable-nodes-in-subdivided-graph | [Python3] Dijkstra's algo | ye15 | 0 | 46 | reachable nodes in subdivided graph | 882 | 0.503 | Hard | 14,320 |
https://leetcode.com/problems/reachable-nodes-in-subdivided-graph/discuss/1459614/Python-or-Dijkstra-or-Clear-Explanation | class Solution:
def reachableNodes(self, edges: List[List[int]], maxMoves: int, n: int) -> int:
graph = defaultdict(dict)
dp = defaultdict(dict)
for v1, v2, wt in edges:
graph[v1][v2] = wt + 1
graph[v2][v1] = wt + 1
dp[v1][v2] = 0
dp[v2][v1] = 0
#print(graph)
def dijkstra(graph, dp):
myheap = [(0, 0)]
distances = [float(inf)] * n
distances[0] = 0
while myheap:
cost, node = heappop(myheap)
if cost > maxMoves or cost > distances[node]:
continue
for nxtNode, nxtCost in graph[node].items():
totalCost = nxtCost + cost
remainingMoves = maxMoves - cost
# nxtCost is the distance bw node and nxtNode so there are nxtCost - 1 new nodes in bw them
# If remainingMoves are greater than number of new nodes bw them -> it mean we can reach all nodes between the current pair of nodes
dp[node][nxtNode] = max(dp[node][nxtNode], min(remainingMoves, nxtCost - 1))
if totalCost > distances[nxtNode] or totalCost > maxMoves:
continue
distances[nxtNode] = totalCost
heappush(myheap, (totalCost, nxtNode))
#print(nxtNode, distances)
return dp, distances
dp, dist = dijkstra(graph, dp)
#print(dist)
#print(dp)
ans = 0
for key in dp:
for node, num in dp[key].items():
total = dp[node][key] + num
ans += min(total, graph[key][node] - 1)
# each pair is counted twice so we need to divide by 2
ans = ans // 2
# count how many old nodes are reachable
for elem in dist:
if elem != float(inf):
ans += 1
return ans | reachable-nodes-in-subdivided-graph | Python | Dijkstra | Clear Explanation | detective_dp | 0 | 98 | reachable nodes in subdivided graph | 882 | 0.503 | Hard | 14,321 |
https://leetcode.com/problems/projection-area-of-3d-shapes/discuss/1357263/Python3-dollarolution | class Solution:
def projectionArea(self, grid: List[List[int]]) -> int:
p = len(grid)
x, y, c = [], [0]*p, 0
for i in range(p):
x.append(0)
for j in range(p):
n = grid[i][j]
if n > 0:
c += 1
if x[i] < n:
x[i] = n
if y[j] < n:
y[j] = n
return (sum(x)+sum(y)+c) | projection-area-of-3d-shapes | Python3 $olution | AakRay | 1 | 105 | projection area of 3d shapes | 883 | 0.708 | Easy | 14,322 |
https://leetcode.com/problems/projection-area-of-3d-shapes/discuss/1201138/Python3-simple-solution-beats-98-users | class Solution:
def projectionArea(self, grid: List[List[int]]) -> int:
area = 0
for i in grid:
area += len(i) - i.count(0) + max(i)
for i in zip(*grid):
area += max(i)
return area | projection-area-of-3d-shapes | Python3 simple solution beats 98% users | EklavyaJoshi | 1 | 76 | projection area of 3d shapes | 883 | 0.708 | Easy | 14,323 |
https://leetcode.com/problems/projection-area-of-3d-shapes/discuss/381846/Solution-in-Python-3-(one-line)-(beats-~96) | class Solution:
def projectionArea(self, G: List[List[int]]) -> int:
return sum([1 for i in G for j in i if j != 0]+[max(i) for i in G]+[max(i) for i in list(zip(*G))])
- Junaid Mansuri
(LeetCode ID)@hotmail.com | projection-area-of-3d-shapes | Solution in Python 3 (one line) (beats ~96%) | junaidmansuri | 1 | 169 | projection area of 3d shapes | 883 | 0.708 | Easy | 14,324 |
https://leetcode.com/problems/projection-area-of-3d-shapes/discuss/2660630/Python3-Solution-oror-O(N2)-Time-and-O(1)-Space-Complexity | class Solution:
def projectionArea(self, grid: List[List[int]]) -> int:
n=len(grid)
area=0
for i in range(n):
maxVal1=0
maxVal2=0
for j in range(n):
if grid[i][j]>maxVal1:
maxVal1=grid[i][j]
if grid[j][i]>maxVal2:
maxVal2=grid[j][i]
if grid[i][j]>0:
area+=1
area+=maxVal1+maxVal2
return area | projection-area-of-3d-shapes | Python3 Solution || O(N^2) Time & O(1) Space Complexity | akshatkhanna37 | 0 | 2 | projection area of 3d shapes | 883 | 0.708 | Easy | 14,325 |
https://leetcode.com/problems/projection-area-of-3d-shapes/discuss/2556927/python-easy-Sol | class Solution:
def projectionArea(self, grid: List[List[int]]) -> int:
t,s,f=0,0,0
for i in range(len(grid)):
maxRow,maxCol=0,0
for j in range(len(grid[i])):
if grid[i][j]>0:
t+=1
maxRow=max(grid[i][j],maxRow)
maxCol=max(grid[j][i],maxCol)
s+=maxRow
f+=maxCol
return t+s+f | projection-area-of-3d-shapes | python easy Sol | pranjalmishra334 | 0 | 16 | projection area of 3d shapes | 883 | 0.708 | Easy | 14,326 |
https://leetcode.com/problems/projection-area-of-3d-shapes/discuss/2454830/python-simple-solution | class Solution:
def projectionArea(self, grid: List[List[int]]) -> int:
top=len(grid)*len(grid)
front,side=0,0
for i in grid:
front+=max(i)
for j in range(0,len(grid)):
if i[j]==0:
top-=1
for k in range(len(grid)):
mx=-9999999
for i in grid:
if mx<=i[k]:
mx=i[k]
side+=mx
return top+front+side | projection-area-of-3d-shapes | python simple solution | Sadika12 | 0 | 13 | projection area of 3d shapes | 883 | 0.708 | Easy | 14,327 |
https://leetcode.com/problems/projection-area-of-3d-shapes/discuss/1952570/easy-python-code | class Solution:
def projectionArea(self, grid: List[List[int]]) -> int:
a = 0
#xy - plane
for i in grid:
for j in i:
if j != 0:
a += 1
#yz - plane
for i in grid:
a += max(i)
#zx - plane
for i in range(len(grid[0])):
temp = []
for j in range(len(grid)):
temp.append(grid[j][i])
a+= max(temp)
return a | projection-area-of-3d-shapes | easy python code | dakash682 | 0 | 36 | projection area of 3d shapes | 883 | 0.708 | Easy | 14,328 |
https://leetcode.com/problems/projection-area-of-3d-shapes/discuss/1375033/Python3oror-one-nested-for-loop-oror-most-optimised-faster-than-90 | class Solution:
def projectionArea(self, grid: List[List[int]]) -> int:
#up view-- m*n
#view on left grid-- sigma(max of each eleemnt in each row)
#view front --- sigma(max of each element in column)
#net is add all the above
#what happens to the upper view if "0" value cubebs are kept?
#if k such cubes exist then, up_v= m*n -k
n=len(grid)
up_v= n*n
left_v=0
front_v=0
for i in range(n):
maxi=-1#keeps column wise max
left_v+=max(grid[i])#adds row wise max
for j in range(n):
val =grid[j][i]
maxi=max(val,maxi)
if val==0:up_v-=1
front_v+=maxi
#print(up_v-k,left_v,front_v)
return up_v+left_v+front_v | projection-area-of-3d-shapes | Python3|| one nested for loop || most optimised faster than 90% | ana_2kacer | 0 | 54 | projection area of 3d shapes | 883 | 0.708 | Easy | 14,329 |
https://leetcode.com/problems/projection-area-of-3d-shapes/discuss/1015334/python3-pure-math-one-line-solution-with-explanation | class Solution:
def projectionArea(self, grid: List[List[int]]) -> int:
return sum(len(i) - i.count(0) for i in grid) + sum(max(i) for i in zip(*grid)) + sum(max(i) for i in grid) | projection-area-of-3d-shapes | python3 pure math one-line solution with explanation | JuanNiMaNe | 0 | 54 | projection area of 3d shapes | 883 | 0.708 | Easy | 14,330 |
https://leetcode.com/problems/projection-area-of-3d-shapes/discuss/607578/Intuitive-solution-in-four-lines | class Solution:
def projectionArea(self, grid: List[List[int]]) -> int:
tp_area = sum(list(map(lambda r: sum(list(map(lambda e: e>0, r))),grid)))
''' Count number of 1'''
rp_area = sum(list(map(lambda r: max(r), grid)))
''' Get max of each row'''
cp_area = sum(list(map(lambda c: max(c), zip(*grid))))
''' Get max of each column'''
return tp_area + rp_area + cp_area | projection-area-of-3d-shapes | Intuitive solution in four lines | puremonkey2001 | 0 | 43 | projection area of 3d shapes | 883 | 0.708 | Easy | 14,331 |
https://leetcode.com/problems/projection-area-of-3d-shapes/discuss/469303/Python3-simple-solution-using-a-for()-loop | class Solution:
def projectionArea(self, grid: List[List[int]]) -> int:
res=0
for i in range(len(grid)):
ver,hor = 0,0
for j in range(len(grid[i])):
if grid[i][j] > 0: res += 1
hor = max(hor,grid[i][j])
ver = max(ver,grid[j][i])
res += ver + hor
return res | projection-area-of-3d-shapes | Python3 simple solution using a for() loop | jb07 | 0 | 36 | projection area of 3d shapes | 883 | 0.708 | Easy | 14,332 |
https://leetcode.com/problems/uncommon-words-from-two-sentences/discuss/1219754/Python3-99-Faster-Solution | class Solution:
def uncommonFromSentences(self, A: str, B: str) -> List[str]:
uncommon = []
def find_uncommon(s , t):
ans = []
for i in s:
if(s.count(i) == 1 and i not in t):
ans.append(i)
return ans
return find_uncommon(A.split() , B.split()) + find_uncommon(B.split() , A.split()) | uncommon-words-from-two-sentences | [Python3] 99% Faster Solution | VoidCupboard | 3 | 188 | uncommon words from two sentences | 884 | 0.66 | Easy | 14,333 |
https://leetcode.com/problems/uncommon-words-from-two-sentences/discuss/1189860/PythonPython3-Solution-with-using-dict-and-without-using-dict | class Solution:
def uncommonFromSentences(self, A: str, B: str) -> List[str]:
A = A.split() + B.split() # Simply add both the strings by converting it into list using split()
resLis = [] # to store the result list
for i in A: #traverse the list
if A.count(i) == 1: #if the count of string present in list is 1 then append it to the resLis
resLis.append(i)
return resLis #return the resLis | uncommon-words-from-two-sentences | Python/Python3 Solution with using dict and without using dict | prasanthksp1009 | 1 | 201 | uncommon words from two sentences | 884 | 0.66 | Easy | 14,334 |
https://leetcode.com/problems/uncommon-words-from-two-sentences/discuss/1189860/PythonPython3-Solution-with-using-dict-and-without-using-dict | class Solution:
def uncommonFromSentences(self, A: str, B: str) -> List[str]:
dic = {} # initialize the dictionary
resLis = []#list for storing result
for i in A.split(): #traverse the loop till last string in the list where A.split() will convert it to list
if i in dic: #if the word presentl in dic the simply add 1 to it
dic[i] += 1
else: #else add the word to dic and assign it to 1
dic[i] = 1
for i in B.split():#traverse the loop till last string in the list where B.split() will convert it to list
if i in dic:#if the word presentl in dic the simply add 1 to it
dic[i] += 1
else:#else add the word to dic and assign it to 1
dic[i] = 1
print(dic) #just visualize how the key and values gets stored
for i in dic: #traverse the loop in the dic
if dic[i] == 1: # if value of the respective key is 1 then append it to result list
resLis.append(i)
return resLis #return the resLis | uncommon-words-from-two-sentences | Python/Python3 Solution with using dict and without using dict | prasanthksp1009 | 1 | 201 | uncommon words from two sentences | 884 | 0.66 | Easy | 14,335 |
https://leetcode.com/problems/uncommon-words-from-two-sentences/discuss/946372/Python-one-liner | class Solution:
def uncommonFromSentences(self, A: str, B: str) -> List[str]:
return [k for k,v in Counter(A.split()+B.split()).items() if v==1] | uncommon-words-from-two-sentences | Python one-liner | lokeshsenthilkumar | 1 | 132 | uncommon words from two sentences | 884 | 0.66 | Easy | 14,336 |
https://leetcode.com/problems/uncommon-words-from-two-sentences/discuss/734964/Python3-Solution-Faster-than-about-94 | class Solution:
def uncommonFromSentences(self, A: str, B: str) -> List[str]:
unique = []
sentences = A.split(" ") + B.split(" ")
for i in sentences:
if sentences.count(i) == 1:
unique.append(i)
return unique | uncommon-words-from-two-sentences | Python3 Solution - Faster than about 94% | ywilliam | 1 | 62 | uncommon words from two sentences | 884 | 0.66 | Easy | 14,337 |
https://leetcode.com/problems/uncommon-words-from-two-sentences/discuss/2834121/Simple-and-short-python-solution | class Solution:
def uncommonFromSentences(self, s1: str, s2: str) -> List[str]:
words = s1.split(" ")
words += s2.split(" ")
count = Counter(words)
res = []
for k,v in count.items():
if v == 1:
res.append(k)
return res | uncommon-words-from-two-sentences | Simple and short python solution | aruj900 | 0 | 3 | uncommon words from two sentences | 884 | 0.66 | Easy | 14,338 |
https://leetcode.com/problems/uncommon-words-from-two-sentences/discuss/2812931/Simple-Python-Solution | class Solution:
def uncommonFromSentences(self, s1: str, s2: str) -> List[str]:
hashMap ={}
new_lst=[]
lst = s1.split(" ") + s2.split(" ")
for word in lst:
hashMap[word] = lst.count(word)
for i in hashMap:
if hashMap[i] == 1:
new_lst.append(i)
return new_lst | uncommon-words-from-two-sentences | Simple Python Solution | danishs | 0 | 4 | uncommon words from two sentences | 884 | 0.66 | Easy | 14,339 |
https://leetcode.com/problems/uncommon-words-from-two-sentences/discuss/2805353/884.-Uncommon-Words-from-Two-Sentences-oror-Pyhton3-oror-Dictionary | class Solution:
def uncommonFromSentences(self, s1: str, s2: str) -> List[str]:
ans=[]
s1=s1.split()
s2=s2.split()
d1=Counter(s1)
d2=Counter(s2)
#print(d1,d2)
for i in d1.keys():
if d1[i]==1 and i not in d2.keys():
ans.append(i)
for i in d2.keys():
if d2[i]==1 and i not in d1.keys():
ans.append(i)
#print(ans)
return ans | uncommon-words-from-two-sentences | 884. Uncommon Words from Two Sentences || Pyhton3 || Dictionary | shagun_pandey | 0 | 2 | uncommon words from two sentences | 884 | 0.66 | Easy | 14,340 |
https://leetcode.com/problems/uncommon-words-from-two-sentences/discuss/2805349/884.-Uncommon-Words-from-Two-Sentences-oror-Pyhton3-oror-Dictionary | class Solution:
def uncommonFromSentences(self, s1: str, s2: str) -> List[str]:
ans=[]
s1=s1.split()
s2=s2.split()
d1=Counter(s1)
d2=Counter(s2)
#print(d1,d2)
for i in d1.keys():
if d1[i]==1 and i not in d2.keys():
ans.append(i)
for i in d2.keys():
if d2[i]==1 and i not in d1.keys():
ans.append(i)
#print(ans)
return ans | uncommon-words-from-two-sentences | 884. Uncommon Words from Two Sentences || Pyhton3 || Dictionary | shagun_pandey | 0 | 1 | uncommon words from two sentences | 884 | 0.66 | Easy | 14,341 |
https://leetcode.com/problems/uncommon-words-from-two-sentences/discuss/2703572/Python-solution-using-dictionary | class Solution:
def uncommonFromSentences(self, s1: str, s2: str) -> List[str]:
d = {}
ans = []
l = s1.split() + s2.split()
for word in l:
if word in d:
d[word]+=1
else:
d[word]=1
for key, value in d.items():
if value == 1:
ans.append(key)
return ans | uncommon-words-from-two-sentences | Python solution using dictionary | imkprakash | 0 | 2 | uncommon words from two sentences | 884 | 0.66 | Easy | 14,342 |
https://leetcode.com/problems/uncommon-words-from-two-sentences/discuss/2656646/Python-1-line | class Solution:
def uncommonFromSentences(self, s1: str, s2: str) -> List[str]:
return list(filter(lambda x: y.count(x) == True, y:=f"{s1} {s2}".split(" "))) | uncommon-words-from-two-sentences | Python 1 line | phantran197 | 0 | 3 | uncommon words from two sentences | 884 | 0.66 | Easy | 14,343 |
https://leetcode.com/problems/uncommon-words-from-two-sentences/discuss/2099758/Python-fast-solution | class Solution:
def uncommonFromSentences(self, s1: str, s2: str) -> List[str]:
arr = s1.split() + s2.split()
ans = []
for i in arr:
if arr.count(i) == 1:
ans.append(i)
return ans | uncommon-words-from-two-sentences | Python fast solution | StikS32 | 0 | 37 | uncommon words from two sentences | 884 | 0.66 | Easy | 14,344 |
https://leetcode.com/problems/uncommon-words-from-two-sentences/discuss/2066702/Basic-solution-using-2-loops | class Solution:
def uncommonFromSentences(self, s1: str, s2: str) -> List[str]:
res = []
s1, s2 = s1.split(), s2.split()
for w in s1:
if s1.count(w) == 1 and w not in s2:
res.append(w)
for w in s2:
if s2.count(w) == 1 and w not in s1:
res.append(w)
return res | uncommon-words-from-two-sentences | Basic solution using 2 loops | andrewnerdimo | 0 | 26 | uncommon words from two sentences | 884 | 0.66 | Easy | 14,345 |
https://leetcode.com/problems/uncommon-words-from-two-sentences/discuss/1988465/Python-Three-Line-Solution | class Solution:
def uncommonFromSentences(self, s1: str, s2: str) -> List[str]:
str_map = collections.Counter(s1.split()+s2.split())
for k, v in str_map.items() :
if v == 1 : yield k | uncommon-words-from-two-sentences | [ Python ] Three Line Solution | crazypuppy | 0 | 42 | uncommon words from two sentences | 884 | 0.66 | Easy | 14,346 |
https://leetcode.com/problems/uncommon-words-from-two-sentences/discuss/1925855/Uncommon-Words-from-2-sentences | class Solution:
def uncommonFromSentences(self, s1: str, s2: str) -> List[str]:
l1 = s1.split()
l2 = s2.split()
r = []
for i in l1:
if i not in l2 and l1.count(i) == 1:
r.append(i)
for i in l2:
if i not in l1 and l2.count(i) == 1:
r.append(i)
return r | uncommon-words-from-two-sentences | Uncommon Words from 2 sentences | Sanjana_Gadagoju | 0 | 30 | uncommon words from two sentences | 884 | 0.66 | Easy | 14,347 |
https://leetcode.com/problems/uncommon-words-from-two-sentences/discuss/1893402/Python-one-line-solution-faster-than-75-and-memory-less-than-73 | class Solution:
def uncommonFromSentences(self, s1: str, s2: str) -> List[str]:
return [x for x in set(s1.split() + s2.split()) if (s1.split() + s2.split()).count(x) == 1] | uncommon-words-from-two-sentences | Python one line solution faster than 75% and memory less than 73% | alishak1999 | 0 | 53 | uncommon words from two sentences | 884 | 0.66 | Easy | 14,348 |
https://leetcode.com/problems/uncommon-words-from-two-sentences/discuss/1854459/Python-Simple-and-Elegant!-Multiple-Solutions | class Solution(object):
def uncommonFromSentences(self, s1, s2):
c = Counter(s1.split()+s2.split())
return [k for k, v in c.items() if v == 1] | uncommon-words-from-two-sentences | Python - Simple and Elegant! Multiple Solutions | domthedeveloper | 0 | 46 | uncommon words from two sentences | 884 | 0.66 | Easy | 14,349 |
https://leetcode.com/problems/uncommon-words-from-two-sentences/discuss/1854459/Python-Simple-and-Elegant!-Multiple-Solutions | class Solution(object):
def uncommonFromSentences(self, s1, s2):
return [k for k, v in Counter(s1.split()+s2.split()).items() if v == 1] | uncommon-words-from-two-sentences | Python - Simple and Elegant! Multiple Solutions | domthedeveloper | 0 | 46 | uncommon words from two sentences | 884 | 0.66 | Easy | 14,350 |
https://leetcode.com/problems/uncommon-words-from-two-sentences/discuss/1854459/Python-Simple-and-Elegant!-Multiple-Solutions | class Solution(object):
def uncommonFromSentences(self, s1, s2):
c = Counter(s1.split() + s2.split())
return dict(filter(lambda x : x[1] == 1 , c.items())).keys() | uncommon-words-from-two-sentences | Python - Simple and Elegant! Multiple Solutions | domthedeveloper | 0 | 46 | uncommon words from two sentences | 884 | 0.66 | Easy | 14,351 |
https://leetcode.com/problems/uncommon-words-from-two-sentences/discuss/1854459/Python-Simple-and-Elegant!-Multiple-Solutions | class Solution(object):
def uncommonFromSentences(self, s1, s2):
return dict(filter(lambda x:x[1]==1,(Counter((s1+" "+s2).split())).items())).keys() | uncommon-words-from-two-sentences | Python - Simple and Elegant! Multiple Solutions | domthedeveloper | 0 | 46 | uncommon words from two sentences | 884 | 0.66 | Easy | 14,352 |
https://leetcode.com/problems/uncommon-words-from-two-sentences/discuss/1644036/Faster-than-96 | class Solution:
def uncommonFromSentences(self, s1: str, s2: str) -> List[str]:
hash1={}
hash2={}
lis1=s1.split(' ')
lis2=s2.split(' ')
for word in lis1:
if word not in hash1:
hash1[word]=1
else:
hash1[word]+=1
for word in lis2:
if word not in hash2:
hash2[word]=1
else:
hash2[word]+=1
print(hash1,hash2)
res=[]
for k,v in hash1.items():
if k not in hash2:
if(v==1):
res.append(k)
for k,v in hash2.items():
if k not in hash1:
if(v==1):
res.append(k)
return(res) | uncommon-words-from-two-sentences | Faster than 96% | naren_nadig | 0 | 54 | uncommon words from two sentences | 884 | 0.66 | Easy | 14,353 |
https://leetcode.com/problems/uncommon-words-from-two-sentences/discuss/1384873/Simple-dictionary-solution(faster-than-98.98-) | class Solution(object):
def uncommonFromSentences(self, s1, s2):
"""
:type s1: str
:type s2: str
:rtype: List[str]
"""
st1=s1.split(" ")
st2=s2.split(" ")
d={}
for i in st1:
d[i]=d.get(i,0)+1
for j in st2:
d[j]=d.get(j,0)+1
#print(d)
out=[]
for key,value in d.items():
if value==1:
out.append(key)
return out | uncommon-words-from-two-sentences | Simple dictionary solution(faster than 98.98% ) | Qyum | 0 | 53 | uncommon words from two sentences | 884 | 0.66 | Easy | 14,354 |
https://leetcode.com/problems/uncommon-words-from-two-sentences/discuss/1368274/Python3 | class Solution:
def uncommonFromSentences(self, s1: str, s2: str) -> List[str]:
min_s = ""
words = []
uncommon = []
common = []
my_list = []
s3 = s1 + " " + s2
for i, element in enumerate(s3):
if s3[i] != " ":
min_s = min_s + s3[i]
if s3[i] == " " or len(s3)-1 == i:
words.append(min_s)
min_s = ""
for i in words:
if i not in my_list:
my_list.append(i)
else:
common.append(i)
for i in my_list:
if i not in common:
uncommon.append(i)
return uncommon | uncommon-words-from-two-sentences | Python3 | FlorinnC1 | 0 | 45 | uncommon words from two sentences | 884 | 0.66 | Easy | 14,355 |
https://leetcode.com/problems/uncommon-words-from-two-sentences/discuss/1357381/Python3-dollarolution | class Solution:
def uncommonFromSentences(self, s1: str, s2: str) -> List[str]:
s1, s2 = s1.split(), s2.split()
d, v = {}, []
for i in s1:
if i not in d:
d[i] = 1
else:
d[i] += 1
for i in s2:
if i not in d:
d[i] = 1
else:
d[i] = 0
for i in d:
if d[i] == 1:
v.append(i)
return v | uncommon-words-from-two-sentences | Python3 $olution | AakRay | 0 | 139 | uncommon words from two sentences | 884 | 0.66 | Easy | 14,356 |
https://leetcode.com/problems/uncommon-words-from-two-sentences/discuss/1146515/Python-pythonic-wo-counter | class Solution:
def uncommonFromSentences(self, A: str, B: str) -> List[str]:
dct = {}
# loop for both strings
for word in A.split() + B.split():
# count each word
dct[word] = dct.get(word, 0) + 1
# return only unique words
return [key for key, value in dct.items() if value == 1] | uncommon-words-from-two-sentences | [Python] pythonic, w/o counter | cruim | 0 | 40 | uncommon words from two sentences | 884 | 0.66 | Easy | 14,357 |
https://leetcode.com/problems/uncommon-words-from-two-sentences/discuss/1049720/Python3-easy-solution-using-dictionary | class Solution:
def uncommonFromSentences(self, A: str, B: str) -> List[str]:
A += ' ' + B
d = {}
for i in A.split():
d[i] = d.get(i,0) + 1
l = []
for i,j in d.items():
if j == 1:
l.append(i)
return l | uncommon-words-from-two-sentences | Python3 easy solution using dictionary | EklavyaJoshi | 0 | 44 | uncommon words from two sentences | 884 | 0.66 | Easy | 14,358 |
https://leetcode.com/problems/uncommon-words-from-two-sentences/discuss/381853/Solution-in-Python-3-(beats-~96)-(two-lines) | class Solution:
def uncommonFromSentences(self, A: str, B: str) -> List[str]:
S = [collections.Counter(A.split()),collections.Counter(B.split())]
return [j for i in range(2) for j in S[i] if S[i][j] == 1 and j not in S[1-i]]
- Junaid Mansuri
(LeetCode ID)@hotmail.com | uncommon-words-from-two-sentences | Solution in Python 3 (beats ~96%) (two lines) | junaidmansuri | 0 | 110 | uncommon words from two sentences | 884 | 0.66 | Easy | 14,359 |
https://leetcode.com/problems/spiral-matrix-iii/discuss/2718364/Easy-Python-Solution-Based-on-Spiral-Matrix-I-and-II | class Solution:
def spiralMatrixIII(self, rows: int, cols: int, rStart: int, cStart: int) -> List[List[int]]:
ans = []
left, right = cStart, cStart+1
top, bottom = rStart, rStart+1
current = 1
move = 0
while current <= rows*cols:
# fill top
for i in range(left+move, right+1):
if self.inbound(top, i, rows, cols):
ans.append([top, i])
current += 1
left -= 1
# fill right
for i in range(top+1, bottom+1):
if self.inbound(i, right, rows, cols):
ans.append([i, right])
current += 1
top -= 1
# fill bottom
for i in range(right-1, left-1, -1):
if self.inbound(bottom, i, rows, cols):
ans.append([bottom, i])
current += 1
right += 1
# fill left
for i in range(bottom-1, top-1, -1):
if self.inbound(i, left, rows, cols):
ans.append([i, left])
current += 1
bottom += 1
move = 1
return ans
def inbound(self, r, c, rows, cols):
return 0<=r<rows and 0<=c<cols | spiral-matrix-iii | Easy Python Solution Based on Spiral Matrix I and II | Naboni | 3 | 77 | spiral matrix iii | 885 | 0.732 | Medium | 14,360 |
https://leetcode.com/problems/spiral-matrix-iii/discuss/1426785/Python-3-or-Simulation-or-Explanation | class Solution:
def spiralMatrixIII(self, rows: int, cols: int, rStart: int, cStart: int) -> List[List[int]]:
total, cnt, step, i = rows * cols, 1, 1, 0
ans = [[rStart, cStart]]
direction = {0: (0, 1), 1: (1, 0), 2: (0, -1), 3: (-1, 0)} # setup direction movements
while cnt < total:
for k in range(step):
rStart, cStart = rStart+direction[i][0], cStart + direction[i][1]
if 0 <= rStart < rows and 0 <= cStart < cols:
ans.append([rStart, cStart])
cnt += 1 # count visited
i = (i + 1) % 4 # changing direction
step += not i % 2 # increase step every 2 directions
return ans | spiral-matrix-iii | Python 3 | Simulation | Explanation | idontknoooo | 3 | 198 | spiral matrix iii | 885 | 0.732 | Medium | 14,361 |
https://leetcode.com/problems/spiral-matrix-iii/discuss/1285754/Python3-solution | class Solution:
def spiralMatrixIII(self, rows: int, cols: int, rStart: int, cStart: int) -> List[List[int]]:
i ,j = rStart, cStart
inc = 1
ans = [[rStart, cStart]]
while len(ans) < rows*cols:
if inc % 2 == 0:
c = inc * -1
else:
c = inc
z = abs(c)
while z > 0:
if c < 0:
j -= 1
else:
j += 1
if i in range(0, rows) and j in range(0, cols):
ans.append([i, j])
z -= 1
z = abs(c)
while z > 0:
if c < 0:
i -= 1
else:
i += 1
if i in range(0, rows) and j in range(0, cols):
ans.append([i, j])
z -= 1
inc += 1
return ans | spiral-matrix-iii | Python3 solution | EklavyaJoshi | 1 | 94 | spiral matrix iii | 885 | 0.732 | Medium | 14,362 |
https://leetcode.com/problems/spiral-matrix-iii/discuss/979712/Python-solution-faster-than-96 | class Solution:
def spiralMatrixIII(self, R: int, C: int, r0: int, c0: int) -> List[List[int]]:
res = [[r0, c0]]
c_r, c_c = r0, c0 # current row, current column
s, d = 1, 1 # step, direction
while len(res) < R * C:
for _ in range(s):
c_c = c_c + 1 * d
if 0 <= c_r < R and 0 <= c_c < C:
res.append([c_r, c_c])
for _ in range(s):
c_r = c_r + 1 * d
if 0 <= c_r < R and 0 <= c_c < C:
res.append([c_r, c_c])
s += 1
d *= -1
return res | spiral-matrix-iii | Python solution, faster than 96% | stom1407 | 1 | 209 | spiral matrix iii | 885 | 0.732 | Medium | 14,363 |
https://leetcode.com/problems/spiral-matrix-iii/discuss/2786478/python3-98-very-very-easy-and-ugly | class Solution:
def spiralMatrixIII(self, rows: int, cols: int, y: int, x: int) -> List[List[int]]:
ans = [(y, x)]
step = 0
total = (rows * cols) - 1
while total:
step += 1
for _ in range(step):
x += 1
if 0 <= x < cols and 0 <= y < rows:
total -= 1
ans.append((y, x))
for _ in range(step):
y += 1
if 0 <= x < cols and 0 <= y < rows:
total -= 1
ans.append((y, x))
step += 1
for _ in range(step):
x -= 1
if 0 <= x < cols and 0 <= y < rows:
total -= 1
ans.append((y, x))
for _ in range(step):
y -= 1
if 0 <= x < cols and 0 <= y < rows:
total -= 1
ans.append((y, x))
return ans | spiral-matrix-iii | python3 98% very very easy and ugly 😆 | 1ncu804u | 0 | 10 | spiral matrix iii | 885 | 0.732 | Medium | 14,364 |
https://leetcode.com/problems/spiral-matrix-iii/discuss/2737124/Python3-What-Even-Is-A-Spiral | class Solution:
def spiralMatrixIII(self, rows: int, cols: int, rStart: int, cStart: int) -> List[List[int]]:
r = []
visited = set()
to_visit = set([(i, j) for i in range(rows) for j in range(cols)])
id, jd = -1, 0 # i delta j delta
i = rStart
j = cStart
while len(to_visit) > 0:
c = i, j
visited.add(c)
if c in to_visit:
to_visit.remove(c)
r.append(c)
rid, rjd = jd, -id
if (i + rid, j+rjd) not in visited: # can turn right
id, jd = rid, rjd
i += id
j += jd
return r | spiral-matrix-iii | Python3 What Even Is A Spiral? | godshiva | 0 | 8 | spiral matrix iii | 885 | 0.732 | Medium | 14,365 |
https://leetcode.com/problems/spiral-matrix-iii/discuss/1435286/Python-Concise-solution-w-directions-array | class Solution(object):
def spiralMatrixIII(self, rows, cols, rStart, cStart):
"""
:type rows: int
:type cols: int
:type rStart: int
:type cStart: int
:rtype: List[List[int]]
"""
directions = [(0,1), (1,0), (0, -1), (-1, 0)]
output = []
a_n = 0 # Sequence number
d = 0 # Current direction (-> ↓ <- ↑)
while len(output) < rows * cols:
for i in range(a_n/2 + 1):
if 0 <= rStart < rows and 0 <= cStart < cols:
output.append([rStart, cStart])
rStart += directions[d][0]
cStart += directions[d][1]
a_n += 1
d = (d + 1) % 4
return output | spiral-matrix-iii | [Python] Concise solution w/ directions array | jsanchez78 | 0 | 92 | spiral matrix iii | 885 | 0.732 | Medium | 14,366 |
https://leetcode.com/problems/spiral-matrix-iii/discuss/784851/Python-Spiral-Simulation | class Solution:
def spiralMatrixIII(self, R: int, C: int, r0: int, c0: int) -> List[List[int]]:
directions = [(0,1), (1,0), (0,-1), (-1,0)]
pointer,j = 0,1
result = [[r0,c0]]
while len(result) < R*C:
for _ in range(2):
rd, cd = directions[pointer]
for i in range(j):
r0 += rd
c0 += cd
if 0<=r0<R and 0<=c0<C:
result.append([r0,c0])
if pointer == 3:
pointer = 0
else:
pointer +=1
j += 1
return result | spiral-matrix-iii | Python Spiral Simulation | Jean-Ralphio | 0 | 135 | spiral matrix iii | 885 | 0.732 | Medium | 14,367 |
https://leetcode.com/problems/spiral-matrix-iii/discuss/640504/Intuitive-approach-by-observation-of-the-spiral-movement | class Solution:
def spiralMatrixIII(self, R: int, C: int, r0: int, c0: int) -> List[List[int]]:
right = lambda p: (p[0], p[1]+1)
left = lambda p: (p[0], p[1]-1)
up = lambda p: (p[0]-1, p[1])
down = lambda p: (p[0]+1, p[1])
moves = [right, down, left, up]
mi = 0
def next_move(mi):
return (mi + 1) % 4
def prev_move(mi):
return (mi - 1 + 4) % 4
def move(p):
return moves[mi](p)
visited_cells = set([(r0, c0)])
pos = (r0, c0)
cells = [pos]
cell_numbers = R * C
hit_boundary = False
while len(visited_cells) < cell_numbers:
next_pos = move(pos)
print("{} -> {}".format(pos, next_pos))
if next_pos[0] < 0 or next_pos[0] >= R or next_pos[1] < 0 or next_pos[1] >= C:
print("{} hit boundary with mi={}".format(pos, mi))
mi = next_move(mi)
hit_boundary = True
continue
if next_pos not in visited_cells:
hit_boundary = False
visited_cells.add(next_pos)
cells.append(next_pos)
mi = next_move(mi)
pos = next_pos
elif hit_boundary:
pos = next_pos
else:
mi = prev_move(mi)
print("visited_cells={}".format(visited_cells))
return cells | spiral-matrix-iii | Intuitive approach by observation of the spiral movement | puremonkey2001 | 0 | 75 | spiral matrix iii | 885 | 0.732 | Medium | 14,368 |
https://leetcode.com/problems/spiral-matrix-iii/discuss/461217/Python-3-(nine-lines)-(beats-~100) | class Solution:
def spiralMatrixIII(self, M: int, N: int, x: int, y: int) -> List[List[int]]:
A, d = [[x,y]], 0
while len(A) < M*N:
for s in 1,-1:
d += 1
for y in range(y+s,y+s*(d+1),s):
if 0<=x<M and 0<=y<N: A.append([x,y])
for x in range(x+s,x+s*(d+1),s):
if 0<=x<M and 0<=y<N: A.append([x,y])
return A
- Junaid Mansuri
- Chicago, IL | spiral-matrix-iii | Python 3 (nine lines) (beats ~100%) | junaidmansuri | -1 | 194 | spiral matrix iii | 885 | 0.732 | Medium | 14,369 |
https://leetcode.com/problems/possible-bipartition/discuss/2593419/Clean-Python3-or-Bipartite-Graph-w-BFS-or-Faster-Than-99 | class Solution:
def possibleBipartition(self, n: int, dislikes: List[List[int]]) -> bool:
dislike = [[] for _ in range(n)]
for a, b in dislikes:
dislike[a-1].append(b-1)
dislike[b-1].append(a-1)
groups = [0] * n
for p in range(n):
if groups[p] == 0:
groups[p] = 1
q = deque([p])
while q: # bfs
a = q.pop()
for b in dislike[a]:
if groups[b] == 0:
groups[b] = 1 if groups[a] == 2 else 2
q.appendleft(b)
elif groups[a] == groups[b]:
return False
return True | possible-bipartition | Clean Python3 | Bipartite Graph w/ BFS | Faster Than 99% | ryangrayson | 2 | 148 | possible bipartition | 886 | 0.485 | Medium | 14,370 |
https://leetcode.com/problems/possible-bipartition/discuss/2741179/Python-BFS-solution | class Solution:
def possibleBipartition(self, n: int, dislikes: List[List[int]]) -> bool:
visited=[0]*n
group=[-1]*n
adj=[[] for _ in range(n)]
for i,j in dislikes:
adj[i-1].append(j-1)
adj[j-1].append(i-1)
for k in range(n):
if visited[k]==0:
lst=[[k,0]]
visited[k]=1
group[k]=0
while lst:
x,c=lst.pop(0)
for i in adj[x]:
if visited[i]==0:
lst.append([i,(c+1)%2])
visited[i]=1
group[i]=(c+1)%2
else:
if group[i]!=(c+1)%2:
return False
return True | possible-bipartition | Python BFS solution | beneath_ocean | 1 | 234 | possible bipartition | 886 | 0.485 | Medium | 14,371 |
https://leetcode.com/problems/possible-bipartition/discuss/2032462/Python3-DFS-solution-explained | class Solution:
def possibleBipartition(self, n: int, dislikes: List[List[int]]) -> bool:
def constructGraph(n: int, pairs: List[List[int]]):
graph = []
for i in range(n):
graph.append([])
for pair in pairs:
personA = pair[0] - 1
personB = pair[1] - 1
graph[personA].append(personB)
graph[personB].append(personA)
return graph
graph = constructGraph(n, dislikes)
visited = [False] * n
marked = [False] * n
def traverse(cur):
visited[cur] = True
for neighbor in graph[cur]:
if visited[neighbor]:
if marked[neighbor] == marked[cur]:
return False
else:
marked[neighbor] = not marked[cur]
traverse(neighbor)
for i in range(n):
if not visited[i]:
if False == traverse(i):
return False
return True | possible-bipartition | Python3 DFS solution explained | TongHeartYes | 1 | 35 | possible bipartition | 886 | 0.485 | Medium | 14,372 |
https://leetcode.com/problems/possible-bipartition/discuss/656048/Python3-bipartite-no-odd-cycle | class Solution:
def possibleBipartition(self, N: int, dislikes: List[List[int]]) -> bool:
graph = dict()
for u, v in dislikes:
graph.setdefault(u-1, []).append(v-1)
graph.setdefault(v-1, []).append(u-1)
def dfs(n, i=1):
"""Return True if bipartite"""
if seen[n]: return (i-seen[n])%2 == 0
seen[n] = i
return all(dfs(nn, i+1) for nn in graph.get(n, []))
seen = [0]*N
return all(dfs(n) for n in range(N) if not seen[n]) | possible-bipartition | [Python3] bipartite == no odd cycle | ye15 | 1 | 79 | possible bipartition | 886 | 0.485 | Medium | 14,373 |
https://leetcode.com/problems/possible-bipartition/discuss/2822241/Python-BFS-Solution-using-BiPartition | class Solution:
def possibleBipartition(self, n: int, dislikes: List[List[int]]) -> bool:
res = True
visited = [0] * n
groups = [-1] * n
graph = [[] for _ in range(n)]
# store the edges
for i,j in dislikes:
graph[i-1].append(j-1)
graph[j-1].append(i-1)
for v in range(n):
if visited[v] == 0:
q = []
visited[v] = 1
groups[v] = 0
q.append(v)
while q and res:
cur = q.pop(0)
for nei in graph[cur]:
if visited[nei] == 0:
groups[nei] = 1 if groups[cur] != 1 else 0
visited[nei] = 1
q.append(nei)
else:
if groups[nei] == groups[cur]:
res = False
return res | possible-bipartition | Python BFS Solution using BiPartition | taoxinyyyun | 0 | 2 | possible bipartition | 886 | 0.485 | Medium | 14,374 |
https://leetcode.com/problems/possible-bipartition/discuss/2806269/Same-question-as-785.-Is-Graph-Bipartite-using-BFS | class Solution:
def possibleBipartition(self, n: int, dislikes: List[List[int]]) -> bool:
adj = defaultdict(list)
for a, b in dislikes:
adj[a].append(b)
adj[b].append(a)
seen = {} #0 and 1
for node in range(1, n + 1):
if node not in seen:
seen[node] = 0
stack = [node]
while stack:
cur = stack.pop()
for nei in adj[cur]:
if nei not in seen:
stack.append(nei)
seen[nei] = seen[cur] ^ 1
elif seen[nei] == seen[cur]:
return False
return True | possible-bipartition | Same question as 785. Is Graph Bipartite? using BFS | mohitkumar36 | 0 | 7 | possible bipartition | 886 | 0.485 | Medium | 14,375 |
https://leetcode.com/problems/possible-bipartition/discuss/2782881/DFS-solution-by-UC-Berkeley-Computer-Science-Honor-Society. | class Solution:
def possibleBipartition(self, n: int, dislikes: List[List[int]]) -> bool:
import collections
"""
we just want to see if our graph is two colorable
"""
graph = collections.defaultdict(list)
for u, v in dislikes:
graph[u].append(v)
graph[v].append(u)
color = [-1] * (n + 1)
def isBipartite(node, col):
color[node] = col
for child in graph[node]:
if color[child] == 1 - col:
continue
elif color[child] == col:
return False
if not isBipartite(child, 1 - col):
return False
return True
for i in range(1, n + 1):
if color[i] != -1:
continue
if not isBipartite(i, 0):
return False
return True | possible-bipartition | DFS solution by UC Berkeley Computer Science Honor Society. | berkeley_upe | 0 | 3 | possible bipartition | 886 | 0.485 | Medium | 14,376 |
https://leetcode.com/problems/possible-bipartition/discuss/2736406/Python-DFS-solution | class Solution:
def possibleBipartition(self, n: int, dislikes: List[List[int]]) -> bool:
colored = {}
# construct adjacency matrix
neighbor_map = collections.defaultdict(list)
for dislike_pair in dislikes:
a = dislike_pair[0]
b = dislike_pair[1]
neighbor_map[a].append(b)
neighbor_map[b].append(a)
# check if Bipartition
for node in range(1, n+1):
if node not in colored:
colored[node] = 0
stack = [node]
while stack:
cur = stack.pop()
for neighbor in neighbor_map[cur]:
if neighbor not in colored:
colored[neighbor] = colored[cur] ^ 1
stack.append(neighbor)
elif colored[neighbor] == colored[cur]:
return False
return True | possible-bipartition | Python DFS solution | gcheng81 | 0 | 9 | possible bipartition | 886 | 0.485 | Medium | 14,377 |
https://leetcode.com/problems/possible-bipartition/discuss/2734714/Simple-Python-or-Graph-or-DFS | class Solution:
def reversed(self, point, color_now):
self.color[point] = color_now
for i in self.graph[point]:
if self.color[i] == 0:
self.reversed(i, color_now*(-1))
elif self.color[i] == color_now:
self.flag = False
return
else:
continue
def possibleBipartition(self, n: int, dislikes: List[List[int]]) -> bool:
self.graph = [[]for _ in range(n+1) ]
for i in dislikes:
a = i[0]
b = i[1]
self.graph[a].append(b)
self.graph[b].append(a)
self.color = [0 for _ in range(n+1)]
self.flag = True
for i in range(1,n+1):
if self.color[i] == 0:
self.reversed(i,1)
if not self.flag:
return False
return True | possible-bipartition | Simple Python | Graph | DFS | lucy_sea | 0 | 6 | possible bipartition | 886 | 0.485 | Medium | 14,378 |
https://leetcode.com/problems/possible-bipartition/discuss/1901081/Python3-DFS | class Solution:
def possibleBipartition(self, n: int, dislikes: List[List[int]]) -> bool:
colors = {}
visited = set()
adjList = [[] for _ in range(n + 1)]
for x, y in dislikes:
adjList[x].append(y)
adjList[y].append(x)
for i in range(1, n + 1):
stack = [i]
while stack:
curNode = stack.pop()
if curNode in visited:
continue
visited.add(curNode)
if curNode not in colors:
colors[curNode] = 1
for neighbor in adjList[curNode]:
if neighbor not in colors:
colors[neighbor] = -1 * colors[curNode]
if colors[curNode] == colors[neighbor]:
return False
stack.append(neighbor)
return True | possible-bipartition | Python3 DFS | EricX91 | 0 | 20 | possible bipartition | 886 | 0.485 | Medium | 14,379 |
https://leetcode.com/problems/possible-bipartition/discuss/1875362/Python3-DFS-solution | class Solution:
ok = True
colors = []
visited = []
def __init(self):
self.ok = ok
self.colors = colors
self.visited = visited
def possibleBipartition(self, n: int, dislikes: List[List[int]]) -> bool:
# bool array storing color(true/false) for each node
self.colors = [False]*(n+1)
# bool array storing whether the node is visited or not
self.visited = [False]*(n+1)
graph = self.buildGraph(n, dislikes)
for i in range(0, len(graph)):
if (self.visited[i] == False):
self.traverse(graph, i)
return self.ok
def buildGraph(self, n, dislikes):
graph = [[] for i in range(n+1)]
for pair in dislikes:
k = pair[0]
v = pair[1]
graph[k].append(v)
graph[v].append(k) | possible-bipartition | [Python3] DFS solution | leqinancy | 0 | 24 | possible bipartition | 886 | 0.485 | Medium | 14,380 |
https://leetcode.com/problems/possible-bipartition/discuss/1544601/Python-simple-dfs-solution-using-two-while-loops | class Solution:
def possibleBipartition(self, n: int, dislikes: List[List[int]]) -> bool:
graph = defaultdict(set)
color = {}
for i in dislikes:
graph[i[0]].add(i[1])
graph[i[1]].add(i[0])
unseen = set()
for i in range(1, n+1):
unseen.add(i) # unseen = {1, 2, ..., n}
while unseen:
for e in unseen:
break
stack = [(e, 0)] # 0: b, 1: r
seen = set()
while stack:
node, c = stack.pop()
seen.add(node)
color[node] = c
for nei in graph[node]:
if nei in color and color[nei] == c:
return False
elif nei not in color:
stack.append((nei, 1-c))
color[nei] = 1-c
unseen = unseen - seen
return True | possible-bipartition | Python simple dfs solution using two while loops | byuns9334 | 0 | 136 | possible bipartition | 886 | 0.485 | Medium | 14,381 |
https://leetcode.com/problems/possible-bipartition/discuss/1172959/easy-to-understand!-Graph-Coloring-Solution! | class Solution:
def possibleBipartition(self, N: int, dislikes: List[List[int]]) -> bool:
graph: dict[int, list[int]] = collections.defaultdict(list)
for u, v in dislikes:
graph[u].append(v)
graph[v].append(u)
visited: dict[int, bool] = {vertex: False for vertex in graph}
result: list[bool] = [True]
two_colors: list[set] = [set(), set()]
level: int = 0
def dfs_visit(current: int, two_colors: list[set], level: int, result: list[bool]) -> None:
visited[current] = True
two_colors[level].add(current)
for neighbour in graph[current]:
if neighbour in two_colors[level]:
result[0] = False
return result[0]
if not visited[neighbour]:
dfs_visit(neighbour, two_colors, 1 if level == 0 else 0, result)
for vertex in graph:
if not visited[vertex]:
dfs_visit(vertex, two_colors, level, result)
return result[0] | possible-bipartition | easy to understand! Graph Coloring Solution! | rahul_sawhney | 0 | 33 | possible bipartition | 886 | 0.485 | Medium | 14,382 |
https://leetcode.com/problems/possible-bipartition/discuss/919425/Python3-BFS-O(V%2BE) | class Solution:
def possibleBipartition(self, N: int, dislikes: List[List[int]]) -> bool:
d = deque([])
colors = {}
graph = {i: [] for i in range(1, N+1)}
for a, b in dislikes:
graph[a].append(b)
graph[b].append(a)
for i in graph.keys():
if i not in colors:
colors[i] = 1
d.append(i)
while d:
item = d.popleft()
for ch in graph[item]:
if ch in colors:
if colors[ch] == colors[item]:
return False
else:
colors[ch] = 1 - colors[item]
d.append(ch)
return True | possible-bipartition | Python3 BFS O(V+E) | ermolushka2 | 0 | 79 | possible bipartition | 886 | 0.485 | Medium | 14,383 |
https://leetcode.com/problems/super-egg-drop/discuss/1468875/Python3-a-few-solutions | class Solution:
def superEggDrop(self, k: int, n: int) -> int:
@cache
def fn(n, k):
"""Return min moves given n floors and k eggs."""
if k == 1: return n
if n == 0: return 0
lo, hi = 1, n + 1
while lo < hi:
mid = lo + hi >> 1
if fn(mid-1, k-1) < fn(n-mid, k): lo = mid + 1
else: hi = mid
return 1 + max(fn(lo-1, k-1), fn(n-lo, k))
return fn(n, k) | super-egg-drop | [Python3] a few solutions | ye15 | 4 | 210 | super egg drop | 887 | 0.272 | Hard | 14,384 |
https://leetcode.com/problems/super-egg-drop/discuss/1468875/Python3-a-few-solutions | class Solution:
def superEggDrop(self, k: int, n: int) -> int:
dp = [[0]*(k+1) for _ in range(n+1) ] # (n+1) x (k+1)
for i in range(n+1): dp[i][1] = i
for j in range(k+1): dp[0][j] = 0
for j in range(2, k+1): # j eggs
x = 1
for i in range(1, n+1): # i floors
while x <= i and dp[i-x][j] > dp[x-1][j-1]: x += 1
dp[i][j] = 1 + dp[x-1][j-1]
return dp[n][k] | super-egg-drop | [Python3] a few solutions | ye15 | 4 | 210 | super egg drop | 887 | 0.272 | Hard | 14,385 |
https://leetcode.com/problems/super-egg-drop/discuss/1468875/Python3-a-few-solutions | class Solution:
def superEggDrop(self, k: int, n: int) -> int:
@cache
def fn(m, k):
"""Return max floor reachable with m moves and k eggs."""
if m == 0 or k == 0: return 0
return 1 + fn(m-1, k-1) + fn(m-1, k)
return next(m for m in range(1, n+1) if fn(m, k) >= n) | super-egg-drop | [Python3] a few solutions | ye15 | 4 | 210 | super egg drop | 887 | 0.272 | Hard | 14,386 |
https://leetcode.com/problems/super-egg-drop/discuss/1425145/Python-DP-solution-with-a-pinch-of-binary-search | class Solution:
def superEggDrop(self, k: int, n: int) -> int:
return self.solve(k,n)
def solve(self,e,f):
if f == 0 or f == 1:
return f
if e == 1:
return f
ans = float('inf')
for k in range(1,f):
temp = 1 + max(self.solve(e-1,k-1), self.solve(e,f-k))
ans = min(ans,temp)
return ans | super-egg-drop | Python DP solution with a pinch of binary search | Saura_v | 1 | 329 | super egg drop | 887 | 0.272 | Hard | 14,387 |
https://leetcode.com/problems/fair-candy-swap/discuss/1088075/Python.-Super-simple-solution. | class Solution:
def fairCandySwap(self, A: List[int], B: List[int]) -> List[int]:
difference = (sum(A) - sum(B)) / 2
A = set(A)
for candy in set(B):
if difference + candy in A:
return [difference + candy, candy] | fair-candy-swap | Python. Super simple solution. | m-d-f | 9 | 1,000 | fair candy swap | 888 | 0.605 | Easy | 14,388 |
https://leetcode.com/problems/fair-candy-swap/discuss/264171/Python-two-pointers | class Solution:
def fairCandySwap(self, A: List[int], B: List[int]) -> List[int]:
a,b=sum(A),sum(B)
diff=(a-b)//2
i,j=0,0
A.sort()
B.sort()
while i<len(A) and j<len(B):
temp = A[i]-B[j]
if temp == diff:
return [A[i],B[j]]
elif temp<diff:
i+=1
else:
j+=1 | fair-candy-swap | Python two pointers | iamhehe | 7 | 832 | fair candy swap | 888 | 0.605 | Easy | 14,389 |
https://leetcode.com/problems/fair-candy-swap/discuss/1641633/Python-Binary-Search-with-explanation | class Solution(object):
def fairCandySwap(self, aliceSizes, bobSizes):
"""
:type aliceSizes: List[int]
:type bobSizes: List[int]
:rtype: List[int]
"""
# Calculate the total value each list should satisfy
alice, bob = 0, 0
for i in aliceSizes: alice += i
for j in bobSizes: bob += j
each = (alice+bob)/2
# Sort each list first to utilize the binary search
aliceSizes.sort()
bobSizes.sort()
for i in range(len(aliceSizes)):
alice_change = aliceSizes[i]
bl, br = 0, len(bobSizes)-1
while bl <= br:
bm = bl + (br-bl)//2
bob_change = bobSizes[bm]
new_alice = alice - alice_change + bob_change
new_bob = bob + alice_change - bob_change
# If two list have the same value, then break
if new_alice == new_bob:
return [alice_change, bob_change]
break
# If new_alice > new_bob, we should choose a larger value for exchanging
elif new_alice > new_bob:
br = bm - 1
# If new_alice < new_bob, we should choose a smaller value for exchanging
elif new_alice < new_bob:
bl = bm + 1 | fair-candy-swap | [Python] Binary Search with explanation | Xueting_Cassie | 3 | 354 | fair candy swap | 888 | 0.605 | Easy | 14,390 |
https://leetcode.com/problems/fair-candy-swap/discuss/1929167/python3-with-explanation | class Solution:
def fairCandySwap(self, aliceSizes: List[int], bobSizes: List[int]) -> List[int]:
total_alice=sum(aliceSizes)
total_bob=sum(bobSizes)
diff=(total_alice-total_bob)//2
for i in set(aliceSizes):
if i-diff in set(bobSizes):
return [i,i-diff]
``` | fair-candy-swap | python3 with explanation | prateek4463 | 2 | 104 | fair candy swap | 888 | 0.605 | Easy | 14,391 |
https://leetcode.com/problems/fair-candy-swap/discuss/1570739/Python-3-O(n)-solution | class Solution:
def fairCandySwap(self, aliceSizes: List[int], bobSizes: List[int]) -> List[int]:
diff = (sum(aliceSizes) - sum(bobSizes)) // 2
s = set(aliceSizes)
for bag in bobSizes:
if bag + diff in s:
return [bag + diff, bag] | fair-candy-swap | Python 3 O(n) solution | dereky4 | 1 | 224 | fair candy swap | 888 | 0.605 | Easy | 14,392 |
https://leetcode.com/problems/fair-candy-swap/discuss/381856/Solution-in-Python-3-(two-lines) | class Solution:
def fairCandySwap(self, A: List[int], B: List[int]) -> List[int]:
d, SA, SB = (sum(A) - sum(B))//2, set(A), set(B)
return [[i, i - d] for i in SA if i - d in SB][0]
- Junaid Mansuri
(LeetCode ID)@hotmail.com | fair-candy-swap | Solution in Python 3 (two lines) | junaidmansuri | 1 | 502 | fair candy swap | 888 | 0.605 | Easy | 14,393 |
https://leetcode.com/problems/fair-candy-swap/discuss/2798792/Simple-python-solution | class Solution:
def fairCandySwap(self, aliceSizes: List[int], bobSizes: List[int]) -> List[int]:
## TC O(len(aliceSize))
## SC O(len(bobSizes))
s1 = sum(aliceSizes)
s2 = sum(bobSizes)
my_set = set(bobSizes)
for x in aliceSizes:
if x + (s2-s1)//2 in my_set:
return [x, x + (s2-s1)//2] | fair-candy-swap | Simple python solution | MPoinelli | 0 | 1 | fair candy swap | 888 | 0.605 | Easy | 14,394 |
https://leetcode.com/problems/fair-candy-swap/discuss/2531603/Python3-or-Solved-Using-Binary-Search-%2B-Satisfying-the-Equation | class Solution:
#Let n = len(aliceSizes) and let m = len(bobSizes)!
#Time-Complexity: O(mlogm + n * log(m))
#Space-Complexity: O(1)
def fairCandySwap(self, aliceSizes: List[int], bobSizes: List[int]) -> List[int]:
#Approach: Use equation and solve it! The equation you derive that provides
#relationship between amount of candies alice and bob have to exchange in order
#for it to be fair will dictate what values we are particularly looking for!
#If we let Ca = number of candies alice originally had, Cb = number of candies
#bob originally had, x number of candies alice gives away, and y number of candies given by
#bob, if exchange is to be fair it must satisfy the following equation!
#in order for binary search to work, input array BobSizes to iterate to
#search for particular y that satisfies the eq. must be sorted!
bobSizes.sort()
#helper function that does binary search!
def helper(e, a):
L, R = 0, (len(a) - 1)
#as long as search space has at least one element, continue binary searching!
while L <= R:
mid = (L + R) // 2
middle = a[mid]
if(middle == e):
return True
elif(middle > e):
R = mid - 1
continue
else:
L = mid + 1
continue
return False
#Eq: y = (x) - (Ca - Cb / 2)
total_a = sum(aliceSizes)
total_b = sum(bobSizes)
subtract_term = (total_a - total_b) / 2
#now iterate through each and every box of candies alice can give away! Based on the
#particular box number of candies alice can give away, see if any boxes of candies
#bob owns satisfies the equation(for given x, does particular y that satsify eq. exists?)
for x in aliceSizes:
req = (x) - (subtract_term)
#we can perform binary search to search whether req number of candies exist
#in one of the boxes bob owns in logarithmic time rather than linear!
if(helper(req, bobSizes)):
return [x, int(req)]
#the problem gaurantees that there will be at least one fair way to exchange candies! | fair-candy-swap | Python3 | Solved Using Binary Search + Satisfying the Equation | JOON1234 | 0 | 49 | fair candy swap | 888 | 0.605 | Easy | 14,395 |
https://leetcode.com/problems/fair-candy-swap/discuss/2450731/Python-commented-with-rundown-of-example-problem-O(N) | class Solution:
def fairCandySwap(self, aliceSizes: List[int], bobSizes: List[int]) -> List[int]:
# get the needed/surplus candies from Alice (when compared with Bob's stash)
alices_share_of_diff = (sum(aliceSizes) - sum(bobSizes)) / 2
# get unique candies from Alice and Bob
alice_set, bob_set = set(aliceSizes), set(bobSizes)
# go through each bag of candies in Bob's stash
for bob_candies in bob_set:
# we're looking for candies size in Bob's such that it with Alice's share of difference is found
target = alices_share_of_diff + bob_candies
# if so, and we're guaranteed at least 1, then return
if target in alice_set:
return [target, bob_candies]
'''
So, using the first example: aliceSizes = [1,1], bobSizes = [2,2]
The difference needed (split in half to share the difference) is -1 (2-4)/2=-1
And at the iteration where Bob has candies 2
the target accounting for Alice's share of difference is 1 (2-1)=1
We swap the two, to make both Alice and Bob have equal amount of candies =)
Time and Space O(N)
''' | fair-candy-swap | Python commented with rundown of example problem O(N) | graceiscoding | 0 | 52 | fair candy swap | 888 | 0.605 | Easy | 14,396 |
https://leetcode.com/problems/fair-candy-swap/discuss/2393510/Memory-Usage%3A-16.2-MB-less-than-74.20-of-Python3-or-Accepted | class Solution:
def fairCandySwap(self, aliceSizes: List[int], bobSizes: List[int]) -> List[int]:
def search(val,arr):
start=0
end=len(arr)-1
while start<=end:
mid=start+(end-start)//2
if arr[mid]==val:
return arr[mid]
elif arr[mid]<val:
start=mid+1
else:
end=mid-1
return -1
def solve(big,small,val):
for j in range(len(big)):
value=search(big[j]-val,small)
print(value)
if value!=-1:
return big[j],value
aliceSizes.sort()
bobSizes.sort()
sum_a=sum(aliceSizes)
sum_b=sum(bobSizes)
val=abs(sum_a-sum_b)//2
if sum_a>sum_b:
alice,bob=solve(aliceSizes,bobSizes,val)
else:
bob,alice=solve(bobSizes,aliceSizes,val)
return [alice,bob] | fair-candy-swap | Memory Usage: 16.2 MB, less than 74.20% of Python3 | Accepted | pheraram | 0 | 41 | fair candy swap | 888 | 0.605 | Easy | 14,397 |
https://leetcode.com/problems/fair-candy-swap/discuss/1991153/Python-3-Solution-O(n)-Time | class Solution:
def counting_sort(self, nums: List[int]) -> List[int]:
max_elm = max(nums)
count_nums = [0] * (max_elm + 1)
for i in range(len(nums)):
count_nums[nums[i]] += 1
for i in range(1, len(count_nums)):
count_nums[i] += count_nums[i - 1]
output_nums = [0] * len(nums)
for i in range(len(nums)):
output_nums[count_nums[nums[i]] - 1] = nums[i]
count_nums[nums[i]] -= 1
return output_nums
def fairCandySwap(self, aliceSizes: List[int], bobSizes: List[int]) -> List[int]:
aliceSizes = self.counting_sort(aliceSizes)
bobSizes = self.counting_sort(bobSizes)
alice_total = 0
bob_total = 0
for i in range(len(aliceSizes)):
alice_total += aliceSizes[i]
for i in range(len(bobSizes)):
bob_total += bobSizes[i]
diff = (alice_total - bob_total) // 2
first, second = 0, 0
while first < len(aliceSizes) and second < len(bobSizes):
temp = aliceSizes[first] - bobSizes[second]
if temp < diff:
first += 1
elif temp > diff:
second += 1
else:
return [aliceSizes[first], bobSizes[second]] | fair-candy-swap | Python 3 Solution O(n) Time | AprDev2011 | 0 | 110 | fair candy swap | 888 | 0.605 | Easy | 14,398 |
https://leetcode.com/problems/fair-candy-swap/discuss/1831011/2-Lines-Python-Solution-oror-85-Faster-oror-Memory-less-than-10 | class Solution:
def fairCandySwap(self, A: List[int], B: List[int]) -> List[int]:
d=(sum(A)-sum(B))//2 ; A=set(A) ; B=set(B)
return [[x, x-d] for x in A if x-d in B][0] | fair-candy-swap | 2-Lines Python Solution || 85% Faster || Memory less than 10% | Taha-C | 0 | 108 | fair candy swap | 888 | 0.605 | Easy | 14,399 |
Subsets and Splits
Top 2 Solutions by Upvotes
Identifies the top 2 highest upvoted Python solutions for each problem, providing insight into popular approaches.