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/find-the-middle-index-in-array/discuss/1444549/Python-or-Running-Sum-or-6-lines
class Solution: def findMiddleIndex(self, nums: List[int]) -> int: total, running = sum(nums), 0 for i, num in enumerate(nums): target = total - num if target % 2 == 0 and running == target // 2: return i running += num return -1
find-the-middle-index-in-array
Python | Running Sum | 6 lines
leeteatsleep
0
26
find the middle index in array
1,991
0.673
Easy
27,800
https://leetcode.com/problems/find-the-middle-index-in-array/discuss/1444343/Python-oror-Very-Easy-Approach
class Solution: def findMiddleIndex(self, lst: List[int]) -> int: count = sum(lst) ls, rs = 0, 0 for i in range(len(lst)): if i == 0: rs = count - lst[i] if rs == 0: return i elif i == len(lst) - 1: ls = count - lst[i] if ls == 0: return i else: ls += lst[i - 1] rs = count - ls - lst[i] if ls == rs: return i return -1
find-the-middle-index-in-array
Python || Very Easy Approach
naveenrathore
0
27
find the middle index in array
1,991
0.673
Easy
27,801
https://leetcode.com/problems/find-the-middle-index-in-array/discuss/1444210/Python-3or-Cumulative-Sumor-O(N)
class Solution: def findMiddleIndex(self, nums: List[int]) -> int: cur_sum = 0 total_sum = sum(nums) for i in range(len(nums)): if total_sum-nums[i] ==cur_sum: return i else: cur_sum+=nums[i] total_sum-=nums[i] return -1
find-the-middle-index-in-array
Python 3| Cumulative Sum| O(N)
deepak1210
0
21
find the middle index in array
1,991
0.673
Easy
27,802
https://leetcode.com/problems/find-the-middle-index-in-array/discuss/1444615/Python-two-linear-passes
class Solution: def findMiddleIndex(self, nums: List[int]) -> int: right = sum(nums) left = 0 for i in range(len(nums)): right -= nums[i] if left == right: return i left += nums[i] return -1
find-the-middle-index-in-array
Python, two linear passes
blue_sky5
-1
19
find the middle index in array
1,991
0.673
Easy
27,803
https://leetcode.com/problems/find-all-groups-of-farmland/discuss/1444115/Python3-dfs
class Solution: def findFarmland(self, land: List[List[int]]) -> List[List[int]]: m, n = len(land), len(land[0]) ans = [] for i in range(m): for j in range(n): if land[i][j]: # found farmland mini, minj = i, j maxi, maxj = i, j stack = [(i, j)] land[i][j] = 0 # mark as visited while stack: i, j = stack.pop() for ii, jj in (i-1, j), (i, j-1), (i, j+1), (i+1, j): if 0 <= ii < m and 0 <= jj < n and land[ii][jj]: stack.append((ii, jj)) land[ii][jj] = 0 maxi = max(maxi, ii) maxj = max(maxj, jj) ans.append([mini, minj, maxi, maxj]) return ans
find-all-groups-of-farmland
[Python3] dfs
ye15
5
207
find all groups of farmland
1,992
0.687
Medium
27,804
https://leetcode.com/problems/find-all-groups-of-farmland/discuss/1444212/Python-BFS-solution
class Solution: def findFarmland(self, land: List[List[int]]) -> List[List[int]]: res = [] visited = {} rows, cols = len(land), len(land[0]) def bfs(i, j): q = deque([(i, j)]) max_i, max_j = i, j while q: i, j = q.popleft() max_i, max_j = max(max_i, i), max(max_j, j) for a, b in ((0, 1), (1, 0)): u, v = i + a, j + b if 0 <= u <= rows - 1 and 0 <= v <= cols - 1 and land[u][v] and (u, v) not in visited: visited[(u, v)] = 1 q.append((u, v)) return max_i, max_j for i in range(rows): for j in range(cols): if land[i][j] and (i, j) not in visited: visited[(i, j)] = 1 x, y = bfs(i, j) res.append([i, j, x, y]) return res
find-all-groups-of-farmland
Python - BFS solution
ajith6198
2
201
find all groups of farmland
1,992
0.687
Medium
27,805
https://leetcode.com/problems/find-all-groups-of-farmland/discuss/1444966/Python-3-or-BFS-Deque-O(M*N)-or-Explanation
class Solution: def findFarmland(self, land: List[List[int]]) -> List[List[int]]: m, n = len(land), len(land[0]) ans = [] for i in range(m): for j in range(n): if land[i][j] < 1: continue q = collections.deque([[i, j]]) while q: x, y = q.popleft() if land[x][y] == -1: continue land[x][y] = -1 for dx, dy in [[0, 1], [1, 0]]: xx, yy = x + dx, y + dy if xx < m and yy < n and land[xx][yy] == 1: q.append([xx, yy]) ans.append([i, j, x, y]) return ans
find-all-groups-of-farmland
Python 3 | BFS, Deque, O(M*N) | Explanation
idontknoooo
1
91
find all groups of farmland
1,992
0.687
Medium
27,806
https://leetcode.com/problems/find-all-groups-of-farmland/discuss/1444167/Python-DFS-O(MN)
class Solution: def findFarmland(self, land: List[List[int]]) -> List[List[int]]: movements = [(0, 1), (0, -1), (-1, 0), (1, 0)] def dfs(i, j): nonlocal r2, c2 land[i][j] = 2 # visited for row, col in movements: r = i + row c = j + col if 0 <= r < len(land) and 0 <= c < len(land[0]) and land[r][c] == 1: r2 = max(r2, r) c2 = max(c2, c) dfs(r, c) answer = [] for i in range(len(land)): for j in range(len(land[0])): if land[i][j] == 1: r2, c2 = i, j dfs(i, j) answer.append((i, j, r2, c2)) return answer
find-all-groups-of-farmland
[Python] DFS O(MN)
asbefu
1
74
find all groups of farmland
1,992
0.687
Medium
27,807
https://leetcode.com/problems/find-all-groups-of-farmland/discuss/2839337/Python-easy-solution
class Solution: def findFarmland(self, land: List[List[int]]) -> List[List[int]]: n, m = len(land), len(land[0]) visited = set() res = [] def dfs(r, c , max_coords): if r < 0 or c < 0 or r >= n or c >= m or (r, c) in visited or land[r][c] == 0: return visited.add((r, c)) max_coords[0] = max(max_coords[0], r) max_coords[1] = max(max_coords[1], c) dfs(r + 1, c, max_coords) dfs(r, c + 1, max_coords) dfs(r - 1, c, max_coords) dfs(r, c - 1, max_coords) for i in range(n): for j in range(m): if land[i][j] == 1 and (i, j) not in visited: start = [i, j] end = [-1, -1] dfs(i, j, end) res.append(start+end) return res
find-all-groups-of-farmland
Python easy solution
dhanu084
0
2
find all groups of farmland
1,992
0.687
Medium
27,808
https://leetcode.com/problems/find-all-groups-of-farmland/discuss/2839336/Python-easy-solution
class Solution: def findFarmland(self, land: List[List[int]]) -> List[List[int]]: n, m = len(land), len(land[0]) visited = set() res = [] def dfs(r, c , max_coords): if r < 0 or c < 0 or r >= n or c >= m or (r, c) in visited or land[r][c] == 0: return visited.add((r, c)) max_coords[0] = max(max_coords[0], r) max_coords[1] = max(max_coords[1], c) dfs(r + 1, c, max_coords) dfs(r, c + 1, max_coords) dfs(r - 1, c, max_coords) dfs(r, c - 1, max_coords) for i in range(n): for j in range(m): if land[i][j] == 1 and (i, j) not in visited: start = [i, j] end = [-1, -1] dfs(i, j, end) res.append(start+end) return res
find-all-groups-of-farmland
Python easy solution
dhanu084
0
2
find all groups of farmland
1,992
0.687
Medium
27,809
https://leetcode.com/problems/find-all-groups-of-farmland/discuss/2701134/Python3-oror-easy-to-understand
class Solution: def findFarmland(self, land: List[List[int]]) -> List[List[int]]: result = [] n = len(land) m = len(land[0]) for i in range(n): for j in range(m): if land[i][j]==1: x1,y1,x2,y2 = i,j,i,j while True: if y2+1<m and land[x2][y2+1]==1: y2+=1 land[x2][y2]=0 elif x2+1<n and land[x2+1][y1]==1: x2,y2=x2+1,y1 land[x2][y2]=0 else: break result.append([x1,y1,x2,y2]) return result
find-all-groups-of-farmland
Python3 || easy to understand
KateIV
0
6
find all groups of farmland
1,992
0.687
Medium
27,810
https://leetcode.com/problems/find-all-groups-of-farmland/discuss/2594644/Python-iterative-bfs-solution....
class Solution: def findFarmland(self, land: List[List[int]]) -> List[List[int]]: q=deque() result=[] for i in range(0,len(land)): for j in range(0,len(land[0])): if land[i][j]==1: land[i][j]=3 q.append((i,j)) self.helper(q,land,result) return result def helper(self,q,land,result): temp=[] x,y=q[0] temp.append([x,y]) while q: x,y=q.popleft() for i,j in [x+1,y],[x-1,y],[x,y+1],[x,y-1]: if 0<=i<len(land) and 0<=j<len(land[0]) and land[i][j]==1: land[i][j]=3 q.append((i,j)) temp.append([i,j]) temp.sort() temp1=temp[0] temp2=temp[-1] result.append([temp1[0],temp1[1],temp2[0],temp2[1]])
find-all-groups-of-farmland
Python iterative bfs solution....
guneet100
0
15
find all groups of farmland
1,992
0.687
Medium
27,811
https://leetcode.com/problems/find-all-groups-of-farmland/discuss/2355631/Python3-or-O(rows*cols)-Runtime-solution-Using-BFS-%2B-Queue
class Solution: #Time-Complexity: O(rows*cols) #Space-Complexity: O(rows*cols + rows*cols + sqrt(rows^2 + cols^2)) -> #O(rows*cols + sqrt(rows^2 + cols^2)) #sqrt(rows^2 + cols^2) 1-d arrays, each with constant 4 elements1 def findFarmland(self, land: List[List[int]]) -> List[List[int]]: #lay out the dimension of our land grid input! rows, cols = len(land), len(land[0]) #visited hashset keeps track of already visited farmland positions so we don't #revisit that particular positions! for purposes of only running bfs #algorithm when needed! visited = set() #define our bfs helper function! #sr and sc parameters = start_row, start_column def bfs(sr, sc): nonlocal visited, rows, cols, land #initialize empty queue! q = collections.deque() q.append([sr, sc]) visited.add((sr, sc)) bottom_right = [sr, sc] four_directions = [[1, 0], [-1, 0], [0, 1], [0, -1]] #run bfs algo! while q: #current element's row and column positions respectively! cr, cc = q.popleft() #we have to process current element! if(cr > bottom_right[0] or cc > bottom_right[1]): bottom_right = [cr, cc] #then, we have to check four adjacent positions! for direction in four_directions: row_change, col_change = direction #check if neighboring position is in-bounds, is a farmaland, and #is not already visited! if(cr + row_change in range(rows) and cc + col_change in range(cols) and land[cr+row_change][cc+col_change] == 1 and (cr+row_change, cc+col_change) not in visited): q.append([cr+row_change, cc+col_change]) visited.add((cr+row_change, cc+col_change)) #once our queue is empty, we should have updated bottom_right position! farmland_description = [sr, sc] + bottom_right return farmland_description ans = [] for i in range(rows): for j in range(cols): if(land[i][j] == 1 and (i, j) not in visited): ans.append(bfs(i, j)) return ans
find-all-groups-of-farmland
Python3 | O(rows*cols) Runtime solution Using BFS + Queue
JOON1234
0
7
find all groups of farmland
1,992
0.687
Medium
27,812
https://leetcode.com/problems/find-all-groups-of-farmland/discuss/2165809/Simple-DFS-oror-Easy-to-Understand
class Solution: def isSafe(self, i,j,land): n = len(land) m = len(land[0]) if 0 <= i < n and 0 <= j < m: return True else: return False def dfs(self,i,j,land,bottom): if not self.isSafe(i,j,land) or land[i][j] != 1: return bottom[0] = max(bottom[0], i) bottom[1] = max(bottom[1], j) land[i][j] = 2 self.dfs(i,j-1,land,bottom) self.dfs(i,j+1,land,bottom) self.dfs(i-1,j,land,bottom) self.dfs(i+1,j,land,bottom) return def findFarmland(self, land: List[List[int]]) -> List[List[int]]: coordinateList = [] n = len(land) m = len(land[0]) for i in range(n): for j in range(m): if land[i][j] == 1: top = [i,j] bottom = [-1,-1] self.dfs(i,j,land,bottom) coordinate = top + bottom coordinateList.append(coordinate) return coordinateList
find-all-groups-of-farmland
Simple DFS || Easy to Understand
Vaibhav7860
0
47
find all groups of farmland
1,992
0.687
Medium
27,813
https://leetcode.com/problems/find-all-groups-of-farmland/discuss/1820321/WEEB-DOES-PYTHONC%2B%2B-BFS
class Solution: def findFarmland(self, land: List[List[int]]) -> List[List[int]]: row, col = len(land), len(land[0]) queue = deque([]) result = [] for x in range(row): for y in range(col): if land[x][y] == 1: queue.append((x,y)) bottomX, bottomY = self.bfs(row, col, queue, land) result.append([x,y,bottomX,bottomY]) return result def bfs(self, row, col, queue, land): visited = set() bottomX, bottomY = 0,0 while queue: x,y = queue.popleft() if (x,y) in visited: continue visited.add((x,y)) land[x][y] = "X" if x > bottomX or y > bottomY: bottomX, bottomY = x, y for nx, ny in [[x+1,y], [x-1,y], [x,y-1], [x,y+1]]: if 0<=nx<row and 0<=ny<col and land[nx][ny] != 0: if (nx,ny) not in visited: queue.append((nx,ny)) return bottomX, bottomY
find-all-groups-of-farmland
WEEB DOES PYTHON/C++ BFS
Skywalker5423
0
24
find all groups of farmland
1,992
0.687
Medium
27,814
https://leetcode.com/problems/find-all-groups-of-farmland/discuss/1705168/Python-O(n-*-m)
class Solution: def findFarmland(self, land: List[List[int]]) -> List[List[int]]: res = [] visited = set() n = len(land) m = len(land[0]) for i in range(n): for j in range(m): if land[i][j] == 1 and (i, j) not in visited: i_min, i_max, j_min, j_max = i, i, j, j while i_min >= 0 and land[i_min][j] == 1: i_min -= 1 i_min += 1 while j_min >= 0 and land[i][j_min] == 1: j_min -= 1 j_min += 1 while i_max < n and land[i_max][j] == 1: i_max += 1 i_max -= 1 while j_max < m and land[i][j_max] == 1: j_max += 1 j_max -= 1 res.append([i_min, j_min, i_max, j_max]) for k in range(i_min, i_max + 1): for l in range(j_min, j_max + 1): visited.add((k, l)) return res
find-all-groups-of-farmland
Python O(n * m)
doutib
0
50
find all groups of farmland
1,992
0.687
Medium
27,815
https://leetcode.com/problems/find-all-groups-of-farmland/discuss/1605102/Python3-Find-top-left-then-bottom-right-(iterative)
class Solution: def findFarmland(self, land: List[List[int]]) -> List[List[int]]: def isTopLeft(row, col): if land[row][col] == 0: return False if col > 0 and land[row][col - 1] == 1: return False return row <= 0 or land[row - 1][col] == 0 def getBottomRight(row, col): r, c = row, col while r < rows and land[r][col] == 1: r += 1 while c < cols and land[row][c] == 1: c += 1 return [r - 1, c - 1] rows, cols = len(land), len(land[0]) return [[row, col, *getBottomRight(row, col)] \ for row in range(rows) for col in range(cols) if isTopLeft(row, col)]
find-all-groups-of-farmland
Python3 - Find top-left then bottom-right (iterative)
mardlucca
0
39
find all groups of farmland
1,992
0.687
Medium
27,816
https://leetcode.com/problems/find-all-groups-of-farmland/discuss/1477579/Python3-Simple-Recursive-Solution
class Solution: def findFarmland(self, land: List[List[int]]) -> List[List[int]]: groups = [] seen = set() def dfs(i, j): current = (i, j) if (i >= len(land) or j >= len(land[0]) or land[i][j] == 0 or current in seen): return (-1, -1) seen.add(current) down = dfs(i + 1, j) right = dfs(i, j + 1) return max(down, right, current) for i, row in enumerate(land): for j, hectare in enumerate(row): if (hectare != 1 or (i, j) in seen): continue group = [i, j] bottom = dfs(i, j) group.extend(bottom) groups.append(group) return groups
find-all-groups-of-farmland
Python3 - Simple Recursive Solution โœ…
Bruception
0
72
find all groups of farmland
1,992
0.687
Medium
27,817
https://leetcode.com/problems/find-all-groups-of-farmland/discuss/1444551/Split-into-groups
class Solution: def findFarmland(self, land: List[List[int]]) -> List[List[int]]: ans = [] lands = set() for r, row in enumerate(land): for c, v in enumerate(row): if v: lands.add((r, c)) while lands: start = lands.pop() island = {start} row = {start} while row: new_row = set() for i, j in row: for tpl in [(i + 1, j), (i, j + 1), (i - 1, j), (i, j - 1)]: if tpl in lands: lands.remove(tpl) new_row.add(tpl) island.update(new_row) row = new_row ans.append(list(min(island)) + list(max(island))) return ans
find-all-groups-of-farmland
Split into groups
EvgenySH
0
29
find all groups of farmland
1,992
0.687
Medium
27,818
https://leetcode.com/problems/find-all-groups-of-farmland/discuss/1444226/Simple-oror-Easy-to-understand-oror-O(n2)
class Solution: def findFarmland(self, land: List[List[int]]) -> List[List[int]]: m=len(land) n=len(land[0]) def dfs(i,j,ei,ej): nonlocal ex,ey if i<0 or j<0 or i>=m or j>=n or land[i][j]==0: return ex=max(i,ei) ey=max(j,ej) land[i][j]=0 dfs(i+1,j,ex,ey) dfs(i,j+1,ex,ey) dfs(i,j-1,ex,ey) dfs(i-1,j,ex,ey) res=[] for x in range(m): for y in range(n): if land[x][y]==1: ex,ey = x,y dfs(x,y,ex,ey) res.append([x,y,ex,ey]) return res
find-all-groups-of-farmland
๐Ÿ Simple || Easy-to-understand || O(n^2) ๐Ÿ“Œ๐Ÿ“Œ
abhi9Rai
0
48
find all groups of farmland
1,992
0.687
Medium
27,819
https://leetcode.com/problems/the-number-of-good-subsets/discuss/1444318/Python3-dp
class Solution: def numberOfGoodSubsets(self, nums: List[int]) -> int: freq = [0] * 31 for x in nums: freq[x] += 1 masks = [0] * 31 for x in range(1, 31): if x == 1: masks[x] = 0b10 else: bits = 0 xx = x for k in (2, 3, 5, 7, 11, 13, 17, 19, 23, 29): while xx % k == 0: if (bits >> k) &amp; 1: break # repeated factors bits ^= 1 << k xx //= k else: continue break else: masks[x] = bits @cache def fn(x, m): """Return number of good subsets.""" if x == 31: return int(m > 2) ans = fn(x+1, m) if freq[x] and masks[x]: if x == 1: ans *= 2**freq[x] elif not m &amp; masks[x]: ans += freq[x] * fn(x+1, m | masks[x]) return ans % 1_000_000_007 return fn(1, 0)
the-number-of-good-subsets
[Python3] dp
ye15
2
203
the number of good subsets
1,994
0.344
Hard
27,820
https://leetcode.com/problems/the-number-of-good-subsets/discuss/1444676/Python-3-Bitmask-and-dp-(2080ms)
class Solution: def numberOfGoodSubsets(self, nums: List[int]) -> int: primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29] cands = {} for x in range(1, 31): orig = x mask = 0 for p in primes: if x % p: continue if p > x: break x //= p mask ^= (1 << p) if x == 1: cands[orig] = mask cnt = {k: v for k, v in Counter(nums).items() if k in cands} cnt_key = list(filter(lambda x: x> 1, sorted(cnt))) n = len(cnt_key) M = 10**9 + 7 @lru_cache(None) def dp(i, mask): if i == n: return mask > 0 ans = dp(i+1, mask) if mask &amp; cands[cnt_key[i]] == 0: ans += cnt[cnt_key[i]] * dp(i+1, mask ^ cands[cnt_key[i]]) return ans % M return (dp(0, 0) * pow(2, cnt.get(1, 0))) % M
the-number-of-good-subsets
[Python 3] Bitmask and dp (2080ms)
chestnut890123
0
75
the number of good subsets
1,994
0.344
Hard
27,821
https://leetcode.com/problems/count-special-quadruplets/discuss/1445362/Python-non-brute-force.-Time%3A-O(N2)-Space%3A-O(N2)
class Solution: def countQuadruplets(self, nums: List[int]) -> int: idx = defaultdict(list) for i in range(len(nums)-1): for j in range(i+1, len(nums)): idx[nums[j]-nums[i]].append(i) count = 0 for i in range(len(nums)-3): for j in range(i+1, len(nums)-2): count += sum(k > j for k in idx[nums[i]+nums[j]]) return count
count-special-quadruplets
Python, non-brute force. Time: O(N^2), Space: O(N^2)
blue_sky5
4
729
count special quadruplets
1,995
0.593
Easy
27,822
https://leetcode.com/problems/count-special-quadruplets/discuss/1446343/Python3-brute-force
class Solution: def countQuadruplets(self, nums: List[int]) -> int: ans = 0 freq = defaultdict(int) for i in range(len(nums)): for j in range(i+1, len(nums)): for k in range(j+1, len(nums)): ans += freq[nums[k] - nums[i] - nums[j]] freq[nums[i]] += 1 return ans
count-special-quadruplets
[Python3] brute-force
ye15
1
150
count special quadruplets
1,995
0.593
Easy
27,823
https://leetcode.com/problems/count-special-quadruplets/discuss/1446343/Python3-brute-force
class Solution: def countQuadruplets(self, nums: List[int]) -> int: ans = 0 freq = Counter() for i in range(len(nums)): for j in range(i+1, len(nums)): ans += freq[nums[j] - nums[i]] for ii in range(i): freq[nums[ii] + nums[i]] += 1 return ans
count-special-quadruplets
[Python3] brute-force
ye15
1
150
count special quadruplets
1,995
0.593
Easy
27,824
https://leetcode.com/problems/count-special-quadruplets/discuss/1445305/Python-brute-force-O(N4)
class Solution: def countQuadruplets(self, nums: List[int]) -> int: count = 0 for i in range(len(nums)-3): for j in range(i+1, len(nums)-2): for k in range(j+1, len(nums)-1): for l in range(k+1, len(nums)): count += nums[i] + nums[j] + nums[k] == nums[l] return count
count-special-quadruplets
Python, brute force O(N^4)
blue_sky5
1
99
count special quadruplets
1,995
0.593
Easy
27,825
https://leetcode.com/problems/count-special-quadruplets/discuss/2689209/Python-and-Golang
class Solution: def countQuadruplets(self, nums: List[int]) -> int: quadruplet_count = 0 for a, b, c, d in itertools.combinations(nums, 4): if (a + b + c) == d: quadruplet_count += 1 return quadruplet_count
count-special-quadruplets
Python and Golang็ญ”ใˆ
namashin
0
19
count special quadruplets
1,995
0.593
Easy
27,826
https://leetcode.com/problems/count-special-quadruplets/discuss/2516254/Best-Python3-implementation-(Top-92.8)-oror-Clean-code
class Solution: def countQuadruplets(self, nums: List[int]) -> int: res = 0 l = len(nums) count = defaultdict(lambda: 0) count[nums[l-1] - nums[l-2]] = 1 for b in range(l - 3, 0, -1): for a in range(b - 1, -1, -1): res += count[nums[a] + nums[b]] for x in range(l - 1, b, -1): count[nums[x] - nums[b]] += 1 return res
count-special-quadruplets
โœ”๏ธ Best Python3 implementation (Top 92.8%) || Clean code
Kagoot
0
89
count special quadruplets
1,995
0.593
Easy
27,827
https://leetcode.com/problems/count-special-quadruplets/discuss/2506964/brute-force
class Solution: def countQuadruplets(self, nums: List[int]) -> int: # brute force # Time O(N^4) Space O(1) res = 0 n = len(nums) for i in range(n - 3): for j in range(i + 1, n - 2): for k in range(j + 1, n - 1): for l in range(k + 1, n): if nums[i] + nums[j] + nums[k] == nums[l]: res += 1 return res
count-special-quadruplets
brute force
andrewnerdimo
0
29
count special quadruplets
1,995
0.593
Easy
27,828
https://leetcode.com/problems/count-special-quadruplets/discuss/2272207/Python-Loop
class Solution: def countQuadruplets(self, nums: List[int]) -> int: count = 0 N = len(nums) for i in range(N): for j in range(i+1,N): for k in range(j+1,N): for l in range(k+1,N): if nums[i]+nums[j]+nums[k] == nums[l]: count+=1 return count
count-special-quadruplets
Python Loop
Abhi_009
0
109
count special quadruplets
1,995
0.593
Easy
27,829
https://leetcode.com/problems/count-special-quadruplets/discuss/2182005/Python-simple-solution
class Solution: def countQuadruplets(self, nums: List[int]) -> int: ans = 0 for a in range(len(nums)): for b in range(a+1,len(nums)): for c in range(b+1,len(nums)): for d in range(c+1,len(nums)): if nums[a]+nums[b]+nums[c]==nums[d]: ans += 1 return ans
count-special-quadruplets
Python simple solution
StikS32
0
105
count special quadruplets
1,995
0.593
Easy
27,830
https://leetcode.com/problems/count-special-quadruplets/discuss/2171684/Python-or-O(N**2)-solution-using-hashmap-or-neat-and-clean-solution
class Solution: def countQuadruplets(self, nums: List[int]) -> int: ''' using hashmap and calculating two sum and two diff i.e nums[a] + nums[b] + nums[c] = nums[d] rather we calculate it as nums[a] + nums[b] = nums[d] - nums[c] will reduce it Time complexity to n**2 ////// TC: O(N*N) ////// ''' d = {} count = 0 for i in range(len(nums)-1,0,-1): for j in range(i-1,-1,-1): Sum = nums[i] + nums[j] if Sum in d: count += d[Sum] for k in range(len(nums)-1,i,-1): diff = nums[k] - nums[i] d[diff] = 1 + d.get(diff,0) return count
count-special-quadruplets
Python | O(N**2) solution using hashmap | neat and clean solution
__Asrar
0
105
count special quadruplets
1,995
0.593
Easy
27,831
https://leetcode.com/problems/count-special-quadruplets/discuss/1929257/Python3-O(n**3)
class Solution: def countQuadruplets(self, nums: List[int]) -> int: ctr = 0 buckets = defaultdict(list) for idx, num in enumerate(nums): buckets[num].append(idx) for a in range(0, len(nums)-3): for b in range(a+1, len(nums)-2): for c in range(b+1, len(nums)-1): tot = nums[a] + nums[b] + nums[c] for d in buckets[tot]: if d > c: ctr += 1 return ctr
count-special-quadruplets
Python3 O(n**3)
pX0r
0
69
count special quadruplets
1,995
0.593
Easy
27,832
https://leetcode.com/problems/count-special-quadruplets/discuss/1813717/4-Lines-Python-Solution-oror-55-Faster-oror-Memory-less-than-85
class Solution: def countQuadruplets(self, nums: List[int]) -> int: ans = 0 for a,b,c,d in combinations(nums,4): if a+b+c==d: ans +=1 return ans
count-special-quadruplets
4-Lines Python Solution || 55% Faster || Memory less than 85%
Taha-C
0
187
count special quadruplets
1,995
0.593
Easy
27,833
https://leetcode.com/problems/count-special-quadruplets/discuss/1455430/Python-3-Simple-brute-force-solution
class Solution: def countQuadruplets(self, nums: List[int]) -> int: n = len(nums) ans = 0 for i in range(n - 3): for j in range(i + 1, n - 2): for k in range(j + 1, n - 1): for l in range(k + 1, n): if nums[l] == nums[i] + nums[j] + nums[k]: ans += 1 return ans
count-special-quadruplets
[Python 3] Simple brute force solution
terrencetang
0
195
count special quadruplets
1,995
0.593
Easy
27,834
https://leetcode.com/problems/count-special-quadruplets/discuss/1452611/PYTHON-SOLUTION-USING-DICTIONARY
class Solution: def countQuadruplets(self, nums: List[int]) -> int: dic = {} n = len(nums) ans = 0 for i in range(n-1,0,-1) : for j in range(i-1,-1,-1): summ = nums[i]+nums[j] # nums[a] + nums[b] = nums[d] - nums[c] if summ in dic : ans += dic[summ] for k in range(n-1,i,-1): diff = nums[k]-nums[i] # nums[d] - nums[c] if diff in dic : dic[diff] += 1 else : dic[diff] = 1 return ans
count-special-quadruplets
PYTHON SOLUTION USING DICTIONARY
rohitkhairnar
0
241
count special quadruplets
1,995
0.593
Easy
27,835
https://leetcode.com/problems/count-special-quadruplets/discuss/1445318/Python-non-brute-force.-Time%3A-O(N3)-Space%3A-O(N)
class Solution: def countQuadruplets(self, nums: List[int]) -> int: idx = defaultdict(list) for i, n in enumerate(nums): idx[n].append(i) count = 0 for i in range(len(nums)-3): for j in range(i+1, len(nums)-2): for k in range(j+1, len(nums)-1): s = nums[i] + nums[j] + nums[k] count += sum(l > k for l in idx[s]) return count
count-special-quadruplets
Python, non-brute force. Time: O(N^3), Space: O(N)
blue_sky5
0
107
count special quadruplets
1,995
0.593
Easy
27,836
https://leetcode.com/problems/the-number-of-weak-characters-in-the-game/discuss/1445198/Python-Sort
class Solution: def numberOfWeakCharacters(self, properties: List[List[int]]) -> int: properties.sort(key=lambda x: (-x[0],x[1])) ans = 0 curr_max = 0 for _, d in properties: if d < curr_max: ans += 1 else: curr_max = d return ans
the-number-of-weak-characters-in-the-game
Python - Sort
lokeshsenthilkumar
209
9,000
the number of weak characters in the game
1,996
0.44
Medium
27,837
https://leetcode.com/problems/the-number-of-weak-characters-in-the-game/discuss/1445198/Python-Sort
class Solution: def numberOfWeakCharacters(self, properties: List[List[int]]) -> int: properties.sort(key=lambda x: (x[0], -x[1])) stack = [] ans = 0 for a, d in properties: while stack and stack[-1] < d: stack.pop() ans += 1 stack.append(d) return ans
the-number-of-weak-characters-in-the-game
Python - Sort
lokeshsenthilkumar
209
9,000
the number of weak characters in the game
1,996
0.44
Medium
27,838
https://leetcode.com/problems/the-number-of-weak-characters-in-the-game/discuss/2551646/Easy-python-10-line-solution-TC%3A-O(nlogn)
class Solution: def numberOfWeakCharacters(self, properties: List[List[int]]) -> int: properties.sort(key=lambda x:(-x[0],x[1])) mxattack=properties[0][0] mxdefense=properties[0][1] count=0 for i in range(1,len(properties)): if properties[i][0]<mxattack and properties[i][1]<mxdefense: count+=1 else: mxattack=properties[i][0] mxdefense=properties[i][1] return count
the-number-of-weak-characters-in-the-game
Easy python 10 line solution TC: O(nlogn)
shubham_1307
17
2,500
the number of weak characters in the game
1,996
0.44
Medium
27,839
https://leetcode.com/problems/the-number-of-weak-characters-in-the-game/discuss/1470883/Asked-In-Google-Onsite-Interview
class Solution: def numberOfWeakCharacters(self, properties: List[List[int]]) -> int: properties.sort(key = lambda x : (-x[0],x[1])) ans = 0 curr_max = 0 for attack,defend in properties: if defend < curr_max: ans+=1 curr_max = max(curr_max, defend) return ans
the-number-of-weak-characters-in-the-game
Asked In Google Onsite Interview
Sanjaychandak95
16
1,400
the number of weak characters in the game
1,996
0.44
Medium
27,840
https://leetcode.com/problems/the-number-of-weak-characters-in-the-game/discuss/2559802/Python3-Runtime%3A-1969-ms-faster-than-99.62-or-Memory%3A-65.7-MB-less-than-98.32
class Solution: def numberOfWeakCharacters(self, properties: List[List[int]]) -> int: properties.sort(key=lambda x:(-x[0],x[1])) mxattack=properties[0][0] mxdefense=properties[0][1] count=0 for i in range(1,len(properties)): if properties[i][0]<mxattack and properties[i][1]<mxdefense: count+=1 else: mxattack=properties[i][0] mxdefense=properties[i][1] return count
the-number-of-weak-characters-in-the-game
[Python3] Runtime: 1969 ms, faster than 99.62% | Memory: 65.7 MB, less than 98.32%
anubhabishere
3
64
the number of weak characters in the game
1,996
0.44
Medium
27,841
https://leetcode.com/problems/the-number-of-weak-characters-in-the-game/discuss/1445279/Python3-8-line-simple-solution-O(nlogn)
class Solution(): def numberOfWeakCharacters(self, p): p.sort(key = lambda x: (-x[0], x[1])) count = maxdef = 0 for i in p: count += 1 if maxdef > i[1] else 0 maxdef = max(maxdef, i[1]) return count
the-number-of-weak-characters-in-the-game
Python3 8-line simple solution O(nlogn)
ScoutBoi
3
177
the number of weak characters in the game
1,996
0.44
Medium
27,842
https://leetcode.com/problems/the-number-of-weak-characters-in-the-game/discuss/2553082/Python-Elegant-and-Short-or-Sorting-or-Itertools.groupby
class Solution: """ Time: O(n*log(n)) Memory: O(n) """ def numberOfWeakCharacters(self, properties: List[List[int]]) -> int: properties.sort(reverse=True) max_defence = weak = 0 for _, group in groupby(properties, key=lambda x: x[0]): defences = [d for _, d in group] weak += sum(d < max_defence for d in defences) max_defence = max(max_defence, max(defences)) return weak
the-number-of-weak-characters-in-the-game
Python Elegant & Short | Sorting | Itertools.groupby
Kyrylo-Ktl
2
65
the number of weak characters in the game
1,996
0.44
Medium
27,843
https://leetcode.com/problems/the-number-of-weak-characters-in-the-game/discuss/2553447/O(n)-or-Linear-Time-or-Bucket-Sort-orexplained-or-python-or-python3
class Solution: def numberOfWeakCharacters(self, properties: List[List[int]]) -> int: # first sort the array in descending order on the basis of attack # then increase count for every defense less than the max defense # time- O(nlogn) properties.sort(key = lambda x : (-x[0], x[1])) # print(properties) max_def = 0 count = 0 for _, d in properties: if d < max_def: count += 1 max_def = max(max_def, d) return count
the-number-of-weak-characters-in-the-game
O(n) | Linear Time | Bucket Sort |explained | python | python3
shodan11
1
48
the number of weak characters in the game
1,996
0.44
Medium
27,844
https://leetcode.com/problems/the-number-of-weak-characters-in-the-game/discuss/2551957/Python3-Solution-or-Sorting-or-O(nlogn)
class Solution: def numberOfWeakCharacters(self, A): A.sort(key = cmp_to_key(lambda a, b: a[1] - b[1] if a[0] == b[0] else b[0] - a[0])) ans, cdef = 0, 0 for atk, dfn in A: if cdef > dfn: ans += 1 else: cdef = dfn return ans
the-number-of-weak-characters-in-the-game
โœ” Python3 Solution | Sorting | O(nlogn)
satyam2001
1
84
the number of weak characters in the game
1,996
0.44
Medium
27,845
https://leetcode.com/problems/the-number-of-weak-characters-in-the-game/discuss/2551764/EASY-PYTHON3-SOLUTION-O(NlogN)
class Solution: def numberOfWeakCharacters(self, properties: List[List[int]]) -> int: p = sorted(properties, key=lambda x: (-x[0], x[1])) a, d, res = p[0][0], p[0][1], 0 for i, j in p[1:]: if i < a and j < d: res += 1 else: a, d = i, j return res
the-number-of-weak-characters-in-the-game
โœ…โœ”๐Ÿ”ฅ EASY PYTHON3 SOLUTION ๐Ÿ”ฅโœ…โœ”O(NlogN)
rajukommula
1
107
the number of weak characters in the game
1,996
0.44
Medium
27,846
https://leetcode.com/problems/the-number-of-weak-characters-in-the-game/discuss/1448232/Python-3-Heap-solution
class Solution: def numberOfWeakCharacters(self, properties: List[List[int]]) -> int: properties.sort() stack = [] n = len(properties) for i in range(n): heappush(stack, (-properties[i][1], i)) ans = 0 for i in range(n): a, d = properties[i] while stack and properties[stack[0][1]][0] <= a: heappop(stack) if stack and -stack[0][0] > d: ans += 1 return ans
the-number-of-weak-characters-in-the-game
[Python 3] Heap solution
chestnut890123
1
144
the number of weak characters in the game
1,996
0.44
Medium
27,847
https://leetcode.com/problems/the-number-of-weak-characters-in-the-game/discuss/1446329/Python3-greedy
class Solution: def numberOfWeakCharacters(self, properties: List[List[int]]) -> int: ans = prefix = 0 for _, d in sorted(properties, key=lambda x: (-x[0], x[1])): if d < prefix: ans += 1 prefix = max(prefix, d) return ans
the-number-of-weak-characters-in-the-game
[Python3] greedy
ye15
1
83
the number of weak characters in the game
1,996
0.44
Medium
27,848
https://leetcode.com/problems/the-number-of-weak-characters-in-the-game/discuss/2823773/Python-easy-intuition
class Solution: def numberOfWeakCharacters(self, properties: List[List[int]]) -> int: properties.sort(key= lambda x: (-1*x[0], x[1])) #print(properties) max_now = properties[0][1] num_weak = 0 for _property in properties[1:]: if _property[1] < max_now: #print(_property, max_now) num_weak += 1 else: max_now = _property[1] return num_weak
the-number-of-weak-characters-in-the-game
Python easy intuition
rapunzell
0
4
the number of weak characters in the game
1,996
0.44
Medium
27,849
https://leetcode.com/problems/the-number-of-weak-characters-in-the-game/discuss/2665756/Simple-solution-in-python
class Solution: def numberOfWeakCharacters(self, properties: List[List[int]]) -> int: c=0 #doing negative for all first values for i in properties: i[0]=-i[0] properties.sort() #doing back positive for i in properties: i[0]=-i[0] temp=0 for i in range(len(properties)): if temp > properties[i][1]: c+=1 else: temp=properties[i][1] return c
the-number-of-weak-characters-in-the-game
Simple solution in python
harshmishra0014
0
7
the number of weak characters in the game
1,996
0.44
Medium
27,850
https://leetcode.com/problems/the-number-of-weak-characters-in-the-game/discuss/2561037/Python-faster-then-95-solution-easy-to-read-and-understand
class Solution: def numberOfWeakCharacters(self, properties: List[List[int]]) -> int: stack = [] count = 0 properties.sort(key = lambda x:(x[0],-x[1])) for i in range(len(properties)): while stack and (stack[-1][0] < properties[i][0] and stack[-1][1] < properties[i][1]): count += 1 stack.pop() stack.append(properties[i]) return count
the-number-of-weak-characters-in-the-game
Python faster then 95% solution, easy to read and understand
mrPython
0
31
the number of weak characters in the game
1,996
0.44
Medium
27,851
https://leetcode.com/problems/the-number-of-weak-characters-in-the-game/discuss/2554667/Python-For-Memory-vs-Python-for-Time
class Solution: def numberOfWeakCharacters(self, p: List[List[int]]) -> int: weakCharacters = 0 maxDefense = 0 p.sort(key = lambda x: (-x[0], x[1])) for _, defense in p: if defense < maxDefense: weakCharacters += 1 else: maxDefense = defense return weakCharacters
the-number-of-weak-characters-in-the-game
Python For Memory vs Python for Time ๐Ÿ”ฅ
Khacker
0
28
the number of weak characters in the game
1,996
0.44
Medium
27,852
https://leetcode.com/problems/the-number-of-weak-characters-in-the-game/discuss/2554667/Python-For-Memory-vs-Python-for-Time
class Solution: def numberOfWeakCharacters(self, properties: List[List[int]]) -> int: #method1: sort properties.sort(key = lambda x: (-x[0], x[1])) ans = 0 curr_max = 0 for _, d in properties: if d < curr_max: ans += 1 else: curr_max = d return ans
the-number-of-weak-characters-in-the-game
Python For Memory vs Python for Time ๐Ÿ”ฅ
Khacker
0
28
the number of weak characters in the game
1,996
0.44
Medium
27,853
https://leetcode.com/problems/the-number-of-weak-characters-in-the-game/discuss/2554466/python-or-O(nlogn)-approach-easy-to-understand
class Solution: def numberOfWeakCharacters(self, p: List[List[int]]) -> int: p.sort() print(p) strong2=0 strong=p[-1] r=0 for i in range(len(p)-2,-1,-1): if strong[0]>p[i][0] and strong[1]>p[i][1]: r+=1 elif (strong[0]==p[i][0] and strong[1]>p[i][1]) and strong2!=0: if strong2[0]>p[i][0] and strong2[1]>p[i][1]: r+=1 elif strong[1]<p[i][1]: if strong[0]>p[i][0]: strong2=strong strong=p[i] return r
the-number-of-weak-characters-in-the-game
python | O(nlogn) approach easy to understand
anshul_thakur69
0
32
the number of weak characters in the game
1,996
0.44
Medium
27,854
https://leetcode.com/problems/the-number-of-weak-characters-in-the-game/discuss/2554378/Runtime%3A-5167-ms-faster-than-5.04-of-Python3Memory-Usage%3A-66.8-MB-less-than-89.75-of-Python3
class Solution: def numberOfWeakCharacters(self, properties: List[List[int]]) -> int: properties.sort(key=lambda x:(x[0] , -x[1])) ans=0 maxdef=0 i=len(properties)-1 while i!=0: if maxdef>properties[i][1]: ans+=1 if maxdef<properties[i][1]: maxdef=properties[i][1] i-=1 if maxdef>properties[i][1]: ans+=1 return ans
the-number-of-weak-characters-in-the-game
Runtime: 5167 ms, faster than 5.04% of Python3;Memory Usage: 66.8 MB, less than 89.75% of Python3
DG-Problemsolver
0
11
the number of weak characters in the game
1,996
0.44
Medium
27,855
https://leetcode.com/problems/the-number-of-weak-characters-in-the-game/discuss/2554265/Python-Single-sort-nLog(n)-runtime-constant-space-deque-solution-w-comments
class Solution: def numberOfWeakCharacters(self, properties: List[List[int]]) -> int: # First we sort the list ascending by attack properties.sort(key=lambda x: x[0]) # Init our answer to 0 answer = 0 # We create a new deque which will hold at most two variables: # right now it is defaulted to hold the defense value of the highest # attack value item in the list x2 q = collections.deque([properties[-1][1], properties[-1][1]]) # Iterating through the list from end to start for i in range(len(properties)-1, -1, -1): # destructure both atk and def from the list item atk, defe = properties[i] # It is impossible to be weak if you have the highest attack value # in the list of elements, so we just set the q elements to the highest # def value in the set of elements with the highest attack value if atk == properties[-1][0]: q[0] = max(q[0], defe) q[1] = q[0] continue # This conditional triggers when we reach a new attack value # We remove the current highest defense value and re-append # the second value to maintain our deque size of 2, you'll see why in a second if atk != properties[i+1][0]: q.popleft() q.append(q[0]) # If the defense is lower than our current max, we add to our weak vals if defe < q[0]: answer += 1 # If it's greater, we don't want to modify q[0] because if the next element has the # same attack as the current, and less defense than the current but more defense than # the previous elements with higher attack, we'd incorrectly mark it weak. To illustrate this: # [ [2,10], [3,5], [3,6], [10,4], [10,2] ] # If we simply just kept track of the highest defense we've seen, the [3,5] would be marked # weak because 5<6. Instead, the 5 should be compared to the 4 because [3,5] and [3,6] share the same attack # So the Queue would look something like this with each pass: # [2,2] -> [4,4] -> [4,6] -> [4,6] ->[6,10]...and so on # we only compare the current defense to the max defense of elements with a greater attack, so using the # queue this way lets us achieve that. elif defe > q[0]: q[1] = max(q[1], defe) return answer
the-number-of-weak-characters-in-the-game
[Python] Single sort, nLog(n) runtime, constant space, deque solution w/ comments
bugsymika
0
12
the number of weak characters in the game
1,996
0.44
Medium
27,856
https://leetcode.com/problems/the-number-of-weak-characters-in-the-game/discuss/2554178/NO-CUSTOM-SORT-FUNCTIONS-or-Python-or-Easy-or-No-custom-sort
class Solution: def numberOfWeakCharacters(self, properties: List[List[int]]) -> int: properties.sort() properties.reverse() m = -sys.maxsize res = 0 rowm = -sys.maxsize currrow = -1 for i in properties: if i[1] < m and i[0] == currrow: res += 1 elif i[0] != currrow: m = max(m, rowm) currrow = i[0] if i[1] < m: res += 1 rowm = max(i[1], rowm) return res
the-number-of-weak-characters-in-the-game
NO CUSTOM SORT FUNCTIONS | Python | Easy | No custom sort
suzy_fan
0
31
the number of weak characters in the game
1,996
0.44
Medium
27,857
https://leetcode.com/problems/the-number-of-weak-characters-in-the-game/discuss/2554074/Modified-sort-solution-very-quick-Python3
class Solution: def numberOfWeakCharacters(self, properties: List[List[int]]) -> int: # Establish a dictionary so we can group together # Characters with the same attack defenses = defaultdict(list) # Create Variables to hold solution and current max result, current_max = 0, 0 # Place values into dictionary in descending order for attack, defense in sorted(properties, reverse=True): defenses[attack] += [defense] # The dictionary is now stored with largest attacks first # This means that as we go down the dictionary, we will # be guaranteed that the new attack group has a smaller # attack than the former and only have to compare defenses for grouping in defenses.values(): # Sort defenses in ascending order. The reason will become # apparent soon grouping.sort() for defense in grouping: # If the current defense is smaller than our max, we know # the character is weak if defense < current_max: result += 1 # If the current defense is larger than the max (or equal), then # we know all entries in this list will be larger since the list # is in ascending order. As such, we can set the current max # to the max value in this list, then break out of the inner loop else: current_max = grouping[-1] break # Finally, return the solution return result
the-number-of-weak-characters-in-the-game
Modified sort solution, very quick [Python3]
DyHorowitz
0
7
the number of weak characters in the game
1,996
0.44
Medium
27,858
https://leetcode.com/problems/the-number-of-weak-characters-in-the-game/discuss/2553375/The-Number-of-Weak-Characters-in-the-Game-python-solution
class Solution: def numberOfWeakCharacters(self, properties: List[List[int]]) -> int: # we are using lamda here, just because we want a sorted list based on decending attack and assending defence # after sorting the process is very easy we only have to consider the defence p = sorted(properties, key=lambda x:(-x[0], x[1])) max_d=0 weak_counter =0 for a,d in p: # here a and b represents the attack and defence of each sublist # and we are increasing the weak_counter by checking only defence if max_d>d: weak_counter+=1 max_d =max(max_d,d) return weak_counter
the-number-of-weak-characters-in-the-game
The Number of Weak Characters in the Game - python solution
priyam_jsx
0
11
the number of weak characters in the game
1,996
0.44
Medium
27,859
https://leetcode.com/problems/the-number-of-weak-characters-in-the-game/discuss/2553370/python3-sort-binary-search-short
class Solution: def numberOfWeakCharacters(self, properties: List[List[int]]) -> int: properties = sorted(properties, key=lambda x: (x[0],-x[1])) stack = [] ans = 0 for _, i in properties: index = bisect.bisect_right(stack, -i) if index < len(stack): ans += len(stack) - index stack = stack[:index] stack.append(-i) return ans
the-number-of-weak-characters-in-the-game
python3, sort, binary search, short
pjy953
0
12
the number of weak characters in the game
1,996
0.44
Medium
27,860
https://leetcode.com/problems/the-number-of-weak-characters-in-the-game/discuss/2553084/Python-Simple-Python-Solution-Using-Sorting
class Solution: def numberOfWeakCharacters(self, properties: List[List[int]]) -> int: properties = sorted(properties,key=lambda l:l[1], reverse=True) properties = sorted(properties,key=lambda l:l[0]) result = 0 length = len(properties) current_max_value = properties[length - 1][1] length = length - 2 while length > -1: if properties[length][1] < current_max_value: result = result + 1 else: current_max_value = properties[length][1] length = length - 1 return result
the-number-of-weak-characters-in-the-game
[ Python ] โœ…โœ… Simple Python Solution Using Sorting ๐ŸฅณโœŒ๐Ÿ‘
ASHOK_KUMAR_MEGHVANSHI
0
43
the number of weak characters in the game
1,996
0.44
Medium
27,861
https://leetcode.com/problems/the-number-of-weak-characters-in-the-game/discuss/2552897/Russian-Doll-Solution
class Solution: def numberOfWeakCharacters(self, properties: List[List[int]]) -> int: properties.sort(key=lambda x: (-x[0], x[1])) russian_dolls = [] res = 0 for _, defense in properties: idx = bisect.bisect_left(russian_dolls, -defense) if idx == len(russian_dolls): russian_dolls.append(-defense) if idx != 0: res += 1 russian_dolls[idx] = -defense return res
the-number-of-weak-characters-in-the-game
Russian Doll Solution
atiq1589
0
26
the number of weak characters in the game
1,996
0.44
Medium
27,862
https://leetcode.com/problems/the-number-of-weak-characters-in-the-game/discuss/2552511/Python-3-Solution-Faster-then-94-10-line-sol.
class Solution: def numberOfWeakCharacters(self, properties: List[List[int]]) -> int: properties.sort(key=lambda x:(-x[0],x[1])) #check the x[0] if they are same then check the x[1] mxattack=properties[0][0] mxdefense=properties[0][1] count=0 for i in range(1,len(properties)): if properties[i][0]<mxattack and properties[i][1]<mxdefense: count+=1 else: mxattack=properties[i][0] mxdefense=properties[i][1] return count
the-number-of-weak-characters-in-the-game
Python 3 Solution Faster then 94% 10 line sol.
pranjalmishra334
0
37
the number of weak characters in the game
1,996
0.44
Medium
27,863
https://leetcode.com/problems/the-number-of-weak-characters-in-the-game/discuss/2552108/Python-Solution
class Solution: def numberOfWeakCharacters(self, properties: List[List[int]]) -> int: p = sorted(properties, key=lambda x: (-x[0], x[1])) a, d, res = p[0][0], p[0][1], 0 for i, j in p[1:]: if i < a and j < d: res += 1 else: a, d = i, j return res
the-number-of-weak-characters-in-the-game
Python Solution
creativerahuly
0
28
the number of weak characters in the game
1,996
0.44
Medium
27,864
https://leetcode.com/problems/the-number-of-weak-characters-in-the-game/discuss/2552071/O(N-log-N)-solution
class Solution: def numberOfWeakCharacters(self, properties: List[List[int]]) -> int: n = len(properties) count = 0 properties.sort(key = lambda x: (x[0], -x[1])) defense = properties[n - 1][1] for i in range(n - 2, -1, -1): if properties[i][1] < defense: count += 1 else: defense = properties[i][1] return count
the-number-of-weak-characters-in-the-game
O(N log N) solution
mansoorafzal
0
21
the number of weak characters in the game
1,996
0.44
Medium
27,865
https://leetcode.com/problems/the-number-of-weak-characters-in-the-game/discuss/2552038/97.47-faster-code-using-indexing-and-sort-in-Python
class Solution: def numberOfWeakCharacters(self, properties: List[List[int]]) -> int: # sorting order (decending attack) and (assecnding defense). properties.sort(key = lambda x: (-x[0], x[1])) st = properties[0] # start element res = 0 for i in range(1, len(properties)): if st[0] > properties[i][0] and st[1] > properties[i][1]: res += 1 else: # if any property is greater than start element change it. st = properties[i] return res
the-number-of-weak-characters-in-the-game
97.47 % faster code using indexing and sort in Python
ankurbhambri
0
36
the number of weak characters in the game
1,996
0.44
Medium
27,866
https://leetcode.com/problems/the-number-of-weak-characters-in-the-game/discuss/2551952/Python-Solution-or-Brute-force-greater-Optimized-using-Monotonic-Stack
class Solution: def numberOfWeakCharacters(self, properties: List[List[int]]) -> int: n=len(properties) count=0 # Brute Force # for i in range(n): # for j in range(n): # if properties[i][0]<properties[j][0] and properties[i][1]<properties[j][1]: # count+=1 # break # return count # Optimised using Monotonic Stack properties.sort(key=lambda x:x[0]) j=0 arr=[[properties[0][1]]] curr=properties[0][0] for i in range(1, n): if properties[i][0]==curr: arr[j].append(properties[i][1]) else: j+=1 curr=properties[i][0] arr.append([properties[i][1]]) print(arr) count=0 stack=[] for sub_arr in arr: for i in range(len(sub_arr)): while len(stack) and stack[-1]<sub_arr[i]: stack.pop() count+=1 for ele in sorted(sub_arr, reverse=True): stack.append(ele) return count
the-number-of-weak-characters-in-the-game
Python Solution | Brute force --> Optimized using Monotonic Stack
Siddharth_singh
0
41
the number of weak characters in the game
1,996
0.44
Medium
27,867
https://leetcode.com/problems/the-number-of-weak-characters-in-the-game/discuss/2179552/Custom-Sorting
class Solution: def numberOfWeakCharacters(self, properties: List[List[int]]) -> int: properties = sorted(properties, key = lambda x: [-x[0], x[1]]) weakCharacters = 0 maxD = 0 for attack, defense in properties: if maxD > defense: weakCharacters += 1 maxD = max(maxD, defense) return weakCharacters
the-number-of-weak-characters-in-the-game
Custom Sorting
Vaibhav7860
0
83
the number of weak characters in the game
1,996
0.44
Medium
27,868
https://leetcode.com/problems/the-number-of-weak-characters-in-the-game/discuss/1947752/Python-3-Stack-Beat-89
class Solution: def numberOfWeakCharacters(self, properties: List[List[int]]) -> int: if not properties: return 0 properties.sort(key = lambda x: (x[0], -x[1])) stack = [] size = len(properties) for i in range(size): defen = properties[i][-1] if not stack: stack.append(defen) else: while stack and defen > stack[-1]: stack.pop() stack.append(defen) return size - len(stack)
the-number-of-weak-characters-in-the-game
Python 3 Stack, Beat 89%
JDIJason
0
109
the number of weak characters in the game
1,996
0.44
Medium
27,869
https://leetcode.com/problems/first-day-where-you-have-been-in-all-the-rooms/discuss/1446619/Python3-dp
class Solution: def firstDayBeenInAllRooms(self, nextVisit: List[int]) -> int: odd = [0] even = [1] for i in range(1, len(nextVisit)): odd.append((even[-1] + 1) % 1_000_000_007) even.append((2*odd[-1] - odd[nextVisit[i]] + 1) % 1_000_000_007) return odd[-1]
first-day-where-you-have-been-in-all-the-rooms
[Python3] dp
ye15
3
139
first day where you have been in all the rooms
1,997
0.367
Medium
27,870
https://leetcode.com/problems/first-day-where-you-have-been-in-all-the-rooms/discuss/1498361/Python-3-or-DP-or-Explanation
class Solution: def firstDayBeenInAllRooms(self, nextVisit: List[int]) -> int: n = len(nextVisit) dp = [0] * n mod = int(1e9+7) for i in range(n-1): # dp[i]: moves need to visited `i` # dp[i] - dp[nextVisit[i]] + 1: odd visit at i, then back to nextVisited[i] (+1), then move back to i (dp[i] - dp[nextVisit[i]]) for even visit # dp[i] + 1: even visit at i, then from i to i+1 dp[i+1] = (dp[i] - dp[nextVisit[i]] + 1 + dp[i] + 1) % mod return dp[n-1]
first-day-where-you-have-been-in-all-the-rooms
Python 3 | DP | Explanation
idontknoooo
1
207
first day where you have been in all the rooms
1,997
0.367
Medium
27,871
https://leetcode.com/problems/first-day-where-you-have-been-in-all-the-rooms/discuss/1445559/Greedy-oror-4-lines-oror-Weill-Explained-oror-93-faster
class Solution: def firstDayBeenInAllRooms(self, nextVisit: List[int]) -> int: MOD = 10**9+7 n =len(nextVisit) dp=[0]*n for i in range(n-1): dp[i+1] += (2*dp[i] - dp[nextVisit[i]] + 2)%MOD return dp[-1]
first-day-where-you-have-been-in-all-the-rooms
๐Ÿ“Œ๐Ÿ“Œ Greedy || 4 lines || Weill-Explained || 93% faster ๐Ÿ
abhi9Rai
1
102
first day where you have been in all the rooms
1,997
0.367
Medium
27,872
https://leetcode.com/problems/first-day-where-you-have-been-in-all-the-rooms/discuss/2814450/Python-(Simple-Dynamic-Programming)
class Solution: def firstDayBeenInAllRooms(self, nextVisit): n, mod = len(nextVisit), 10**9 + 7 dp = [0]*n for i in range(1,n): dp[i] = (dp[i-1] + (dp[i-1] - dp[nextVisit[i-1]] + 1) + 1)%mod return dp[-1]
first-day-where-you-have-been-in-all-the-rooms
Python (Simple Dynamic Programming)
rnotappl
0
2
first day where you have been in all the rooms
1,997
0.367
Medium
27,873
https://leetcode.com/problems/first-day-where-you-have-been-in-all-the-rooms/discuss/2765071/Python-or-Two-Solutions
class Solution: def firstDayBeenInAllRooms2(self, next_visit: List[int]) -> int: p = 10**9 + 7 n = len(next_visit) dp = [0]*n for i in range(1,n): dp[i] = (2 * dp[i-1] - dp[next_visit[i-1]] + 2) % p return dp[-1] def firstDayBeenInAllRooms(self, next_visit: List[int]) -> int: p = 10**9 + 7 n = len (next_visit) not_visited = set(range(n)) visits = [0] * n last_day = [float('-inf')] * n def simulate (room, day): not_visited.discard(room) while not_visited: visits[room] += 1 last_day[room] = day if visits[room] &amp; 1: # This room has been visited an odd number of times. day = (2*day - last_day[next_visit[room]] + 1) % p # This room has been visited an even number of times. day += 1 room = (room + 1) % n not_visited.discard(room) return day return simulate (0, 0) % p
first-day-where-you-have-been-in-all-the-rooms
Python | Two Solutions
on_danse_encore_on_rit_encore
0
3
first day where you have been in all the rooms
1,997
0.367
Medium
27,874
https://leetcode.com/problems/reverse-prefix-of-word/discuss/1472737/Easy-Python-Solution-(28ms)-or-Faster-than-93
class Solution: def reversePrefix(self, word: str, ch: str) -> str: try: ix = word.index(ch) return word[:ix+1][::-1] + word[ix+1:] except ValueError: return word
reverse-prefix-of-word
Easy Python Solution (28ms) | Faster than 93%
the_sky_high
6
506
reverse prefix of word
2,000
0.778
Easy
27,875
https://leetcode.com/problems/reverse-prefix-of-word/discuss/1719240/Python-3-(25ms)-or-One-Line-Solution-or-Faster-than-95-or-Easy-to-Understand
class Solution: def reversePrefix(self, word: str, ch: str) -> str: if ch not in word: return word return (''.join(reversed(word[:(word.index(ch)+1)]))+word[(word.index(ch))+1:])
reverse-prefix-of-word
Python 3 (25ms) | One Line Solution | Faster than 95% | Easy to Understand
MrShobhit
4
159
reverse prefix of word
2,000
0.778
Easy
27,876
https://leetcode.com/problems/reverse-prefix-of-word/discuss/1552323/Faster-then-75.91-Reverse-Prefix-of-Word
class Solution: def reversePrefix(self, word: str, ch: str) -> str: a='' if ch not in word: return word x,c=0,0 for i in range(len(word)): #print(word[i]) if word[i]==ch: x=c #print(x) a+=word[i] break else: c+=1 a+=word[i] a=a[::-1] #print(a) for i in range(x+1,len(word)): a+=word[i] #print(a) return a
reverse-prefix-of-word
Faster then 75.91% Reverse Prefix of Word
sumitgupta31
2
88
reverse prefix of word
2,000
0.778
Easy
27,877
https://leetcode.com/problems/reverse-prefix-of-word/discuss/2642919/Python-ororO(N)
class Solution: def reversePrefix(self, word: str, ch: str) -> str: count=0 n=len(word) for i in range(n): if word[i]==ch: count=i break ans1,ans2=word[:count+1],word[count+1:] ans=ans1[::-1] return ans+ans2
reverse-prefix-of-word
[Python ||O(N)]
Sneh713
1
58
reverse prefix of word
2,000
0.778
Easy
27,878
https://leetcode.com/problems/reverse-prefix-of-word/discuss/2266468/Python3-Runtime%3A-37ms-78.98-oror-Memory%3A-13.8mb-65.61
class Solution: # Runtime: 37ms 78.98% || Memory: 13.8mb 65.61% def reversePrefix(self, string: str, letter: str) -> str: newString = list(string) for idx, val in enumerate(newString): if val == letter: newString[:idx+1] = newString[:idx+1][::-1] return ''.join(newString) return ''.join(newString)
reverse-prefix-of-word
Python3 Runtime: 37ms 78.98% || Memory: 13.8mb 65.61%
arshergon
1
38
reverse prefix of word
2,000
0.778
Easy
27,879
https://leetcode.com/problems/reverse-prefix-of-word/discuss/1510237/1-liner-in-Python-3.8%2B
class Solution: def reversePrefix(self, word: str, ch: str) -> str: return word[i::-1] + word[(i + 1):] if (i := word.find(ch)) != -1 else word
reverse-prefix-of-word
1 liner in Python 3.8+
mousun224
1
66
reverse prefix of word
2,000
0.778
Easy
27,880
https://leetcode.com/problems/reverse-prefix-of-word/discuss/2850856/easy-python-solution-and-faster-than-98.9
class Solution: def reversePrefix(self, word: str, ch: str) -> str: l = 0 r = len(word) c="" if ch not in word: return word while l<r: if word[l]==ch: c+=word[:l+1][::-1] break l+=1 c+=word[l+1:] return c
reverse-prefix-of-word
easy python solution and faster than 98.9
IronmanX
0
1
reverse prefix of word
2,000
0.778
Easy
27,881
https://leetcode.com/problems/reverse-prefix-of-word/discuss/2844936/Simple-Python-Solution
class Solution: def reversePrefix(self, word: str, ch: str) -> str: if ch not in word: return word for i in range(len(word)): if ch == word[i]: ind = i break return word[:ind+1][::-1] + word[ind+1:]
reverse-prefix-of-word
Simple Python Solution
danishs
0
2
reverse prefix of word
2,000
0.778
Easy
27,882
https://leetcode.com/problems/reverse-prefix-of-word/discuss/2839970/EASIEST-AND-SIMPLEST-SOLUTION-IN-PYTHON
class Solution: def reversePrefix(self, word: str, ch: str) -> str: m=word.find(ch) s=word[:m+1] l=word[m+1:] r=s[::-1] o=r+l return o
reverse-prefix-of-word
EASIEST AND SIMPLEST SOLUTION IN PYTHON
Nischay_2003
0
1
reverse prefix of word
2,000
0.778
Easy
27,883
https://leetcode.com/problems/reverse-prefix-of-word/discuss/2821403/PYTHON-SIMPLE-SOLUTION-with-just-2-lines
class Solution: def reversePrefix(self, word: str, ch: str) -> str: if ch in word: sl = word.index(ch) return word[0:sl+1][::-1]+word[sl+1:] else: return word
reverse-prefix-of-word
PYTHON SIMPLE SOLUTION with just 2 lines
ameenusyed09
0
2
reverse prefix of word
2,000
0.778
Easy
27,884
https://leetcode.com/problems/reverse-prefix-of-word/discuss/2818794/Simple-and-Fast-Python-Solution
class Solution: def reversePrefix(self, word: str, ch: str) -> str: if ch in word: return word[0: word.index(ch) + 1][::-1] + word[word.index(ch) + 1: len(word)] else: return word
reverse-prefix-of-word
Simple and Fast Python Solution
PranavBhatt
0
1
reverse prefix of word
2,000
0.778
Easy
27,885
https://leetcode.com/problems/reverse-prefix-of-word/discuss/2818711/Single-line-code-in-Python
class Solution: def reversePrefix(self, word: str, ch: str) -> str: return word[:word.index(ch)+1][::-1] + word[word.index(ch)+1:] if ch in word else word
reverse-prefix-of-word
Single line code in Python
DNST
0
1
reverse prefix of word
2,000
0.778
Easy
27,886
https://leetcode.com/problems/reverse-prefix-of-word/discuss/2799924/Easy-understanding-python-code-beats-98.53(T.C.)
class Solution: def reversePrefix(self, word: str, ch: str) -> str: if ch not in word: return word else: count = word.count(ch) str_list = word.split(ch) empty_string = ch for i in range(len(str_list[0])-1,-1,-1): empty_string += str_list[0][i] # str_list[0] = empty_string for i in range(1,len(str_list)): empty_string+=str_list[i] if empty_string.count(ch)==count: break else: empty_string+=ch return empty_string
reverse-prefix-of-word
Easy understanding python code beats 98.53%(T.C.)
Aayush3014
0
1
reverse prefix of word
2,000
0.778
Easy
27,887
https://leetcode.com/problems/reverse-prefix-of-word/discuss/2782937/Python-solution-93-fast
class Solution: def reversePrefix(self, word: str, ch: str) -> str: ch_indexes = [] for i in range(len(word)): if word[i] == ch: ch_indexes.append(i) char = min(ch_indexes, default=0) to_be_reversed = word[0:char+1] return to_be_reversed[::-1] + word[char+1:]
reverse-prefix-of-word
Python solution 93% fast
samanehghafouri
0
2
reverse prefix of word
2,000
0.778
Easy
27,888
https://leetcode.com/problems/reverse-prefix-of-word/discuss/2629436/Reverse-Prefix-of-Word-oror-Python-Solution-oror-EASY
class Solution: def reversePrefix(self, word: str, ch: str) -> str: st=[] i=0 if ch not in word: return word while i!=word.index(ch)+1: st.append(word[i]) i+=1 s=''.join(st) s=s[::-1] #print(s) index=word.index(ch)+1 word=s+word[index:] return word
reverse-prefix-of-word
Reverse Prefix of Word || Python Solution || EASY
shagun_pandey
0
4
reverse prefix of word
2,000
0.778
Easy
27,889
https://leetcode.com/problems/reverse-prefix-of-word/discuss/2625088/easy-solution-one-liner
class Solution: def reversePrefix(self, word: str, ch: str) -> str: return word[:word.index(ch)+1][::-1]+word[word.index(ch)+1:] if ch in word else word
reverse-prefix-of-word
easy solution one liner
lin11116459
0
6
reverse prefix of word
2,000
0.778
Easy
27,890
https://leetcode.com/problems/reverse-prefix-of-word/discuss/2589113/Python3-oror-Best-Solution
class Solution: def reversePrefix(self, word: str, ch: str) -> str: i = 0 while i <len(word): if word[i]==ch: break i+=1 if i ==len(word): return word return word[i::-1]+word[i+1:]
reverse-prefix-of-word
Python3 || Best Solution
shacid
0
10
reverse prefix of word
2,000
0.778
Easy
27,891
https://leetcode.com/problems/reverse-prefix-of-word/discuss/2539815/using-index
class Solution: def reversePrefix(self, word: str, ch: str) -> str: # locate the ch (if ch in word) # if not return word # otherwise find the first occurence (using index()) # having that index flip the string using slicing [::-1] # only slice from 0 to that index add the remaining string to the end # Time O(N) space: O(1) if ch not in word: return word i = word.index(ch) word = word[:i + 1][::-1] + word[i + 1:] return word
reverse-prefix-of-word
using index
andrewnerdimo
0
8
reverse prefix of word
2,000
0.778
Easy
27,892
https://leetcode.com/problems/reverse-prefix-of-word/discuss/2489456/Simple-python-solution
class Solution: def reversePrefix(self, word: str, ch: str) -> str: if ch in word: index = word.index(ch) else: return word prefix = word[:index+1] return prefix[::-1] + word[index+1:]
reverse-prefix-of-word
Simple python solution
aruj900
0
14
reverse prefix of word
2,000
0.778
Easy
27,893
https://leetcode.com/problems/reverse-prefix-of-word/discuss/2464398/Reverse-Prefix-of-Word
class Solution: def reversePrefix(self, word: str, ch: str) -> str: if ch not in word: return word x = "" for i in range(len(word)) : if word[i] != ch: x+=word[i] else: x+=word[i] break return x[::-1]+word[i+1:]
reverse-prefix-of-word
Reverse Prefix of Word
dhananjayaduttmishra
0
4
reverse prefix of word
2,000
0.778
Easy
27,894
https://leetcode.com/problems/reverse-prefix-of-word/discuss/2411079/Simple-python-code-with-explanation
class Solution: def reversePrefix(self, word: str, ch: str) -> str: #if ch is not in word if ch not in word: #just return word return word #find the index of ch in word i = word.index(ch) #by indexing and contatination we can get the result return word[i::-1] + word[i+1:]
reverse-prefix-of-word
Simple python code with explanation
thomanani
0
20
reverse prefix of word
2,000
0.778
Easy
27,895
https://leetcode.com/problems/reverse-prefix-of-word/discuss/2266407/simple-modular-python-solution
class Solution: def create_word(self, word_list) : ans = '' for i in reversed(range(len(word_list))) : ans += word_list[i] return ans def reversePrefix(self, word: str, ch: str) -> str: char_list = [i for i in word] for i in range(len(word)) : if word[i] == ch : first_part = char_list[:i+1] break else : return word ans = self.create_word(first_part) + word[i+1:] return ans
reverse-prefix-of-word
simple modular python solution
sghorai
0
15
reverse prefix of word
2,000
0.778
Easy
27,896
https://leetcode.com/problems/reverse-prefix-of-word/discuss/2185053/Super-simple-python-solution-for-beginners-(Less-than-97.75-memory-usage)
class Solution: def reversePrefix(self, word: str, ch: str) -> str: if ch not in word: return word pre = word[:word.index(ch)+1][::-1] return ''.join(pre + word[word.index(ch)+1:])
reverse-prefix-of-word
Super simple python solution for beginners (Less than 97.75 % memory usage)
pro6igy
0
25
reverse prefix of word
2,000
0.778
Easy
27,897
https://leetcode.com/problems/reverse-prefix-of-word/discuss/2059611/Python3-88-faster-with-explanation
class Solution: def reversePrefix(self, word: str, ch: str) -> str: newS, counter = '', 0 for letter in word: if letter == ch: newS += letter newS = newS[::-1] + word[counter + 1:] break else: newS += letter counter += 1 return newS
reverse-prefix-of-word
Python3, 88% faster with explanation
cvelazquez322
0
54
reverse prefix of word
2,000
0.778
Easy
27,898
https://leetcode.com/problems/reverse-prefix-of-word/discuss/2031420/Python-solutuin
class Solution: def reversePrefix(self, word: str, ch: str) -> str: if ch not in word: return word return word[0:word.index(ch)+1][::-1] + word[word.index(ch)+1:]
reverse-prefix-of-word
Python solutuin
StikS32
0
39
reverse prefix of word
2,000
0.778
Easy
27,899