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/island-perimeter/discuss/2095967/Python-Solution | class Solution:
def islandPerimeter(self, grid: List[List[int]]) -> int:
ln, area = len(grid), 0
for i in range(len(grid)):
row = grid[i]
prev_row, after_row = -1, -1
if i > 0:
prev_row = i - 1
if i < ln - 1:
a... | island-perimeter | Python Solution | Hejita | 0 | 113 | island perimeter | 463 | 0.695 | Easy | 8,300 |
https://leetcode.com/problems/island-perimeter/discuss/1965866/easy-commented-python-code | class Solution:
def islandPerimeter(self, grid: List[List[int]]) -> int:
count = 0
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] == 1:
# check left
if j-1 >= 0:
if grid[i][j-1] == 0:
... | island-perimeter | easy commented python code | dakash682 | 0 | 64 | island perimeter | 463 | 0.695 | Easy | 8,301 |
https://leetcode.com/problems/island-perimeter/discuss/1899088/Simplest-Python-Solution-or-O(n*m) | class Solution:
def islandPerimeter(self, grid: List[List[int]]) -> int:
# Base case checking
if(len(grid[0]) == 0 or len(grid) == 0): return 0
perimeter = 0 # initializing variable to store perimeter of an Island
for i in range(len(grid)):
for j in range(len(grid[i])):
#chec... | island-perimeter | Simplest Python Solution | O(n*m) | parthpatel9414 | 0 | 37 | island perimeter | 463 | 0.695 | Easy | 8,302 |
https://leetcode.com/problems/island-perimeter/discuss/1890453/Easy-Iteration-Method-Python | class Solution:
def islandPerimeter(self, grid: List[List[int]]) -> int:
row,col = len(grid),len(grid[0])
directions = [(1,0),(-1,0),(0,1),(0,-1)]
perimeter = 0
for r in range(row):
for c in range(col):
adjacent_land = 0
if grid[r]... | island-perimeter | Easy Iteration Method Python | gamitejpratapsingh998 | 0 | 34 | island perimeter | 463 | 0.695 | Easy | 8,303 |
https://leetcode.com/problems/island-perimeter/discuss/1836405/Python-DFS-faster-than-70.-Easy-and-explained-with-comments | class Solution:
def islandPerimeter(self, grid: List[List[int]]) -> int:
#iterate from top and check where first piece of land can be found
def findfirst():
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] == 1:
... | island-perimeter | Python DFS faster than 70%. Easy and explained with comments | dc_devesh7 | 0 | 106 | island perimeter | 463 | 0.695 | Easy | 8,304 |
https://leetcode.com/problems/island-perimeter/discuss/1719784/Easy-python-solution | class Solution:
def islandPerimeter(self, grid: List[List[int]]) -> int:
self.grid = grid
self.peri = 0
# find the first land in grid
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] == 1:
self.find_peri(i,j)
ret... | island-perimeter | Easy python solution | skrrtttt | 0 | 137 | island perimeter | 463 | 0.695 | Easy | 8,305 |
https://leetcode.com/problems/island-perimeter/discuss/1511069/Python-simple-row-wise-traversal.-Time-O(m*n)-Space%3A-O(1) | class Solution:
def islandPerimeter(self, grid: List[List[int]]) -> int:
perimeter = 0
m = len(grid)
n = len(grid[0])
for r in range(m):
for c in range(n):
if grid[r][c]:
perimeter += r == 0 or grid[r-1][c] == 0
... | island-perimeter | Python, simple row-wise traversal. Time O(m*n), Space: O(1) | blue_sky5 | 0 | 58 | island perimeter | 463 | 0.695 | Easy | 8,306 |
https://leetcode.com/problems/island-perimeter/discuss/1503571/Easy-to-follow-python-solution | class Solution:
def islandPerimeter(self, grid: List[List[int]]) -> int:
total = 0
for row_index, row in enumerate(grid):
for cord_index, cord in enumerate(row):
counter = 4
if cord == 0:
pass
... | island-perimeter | Easy to follow python solution | flameaway | 0 | 32 | island perimeter | 463 | 0.695 | Easy | 8,307 |
https://leetcode.com/problems/island-perimeter/discuss/1260522/Python-Soln | class Solution:
def islandPerimeter(self, grid: List[List[int]]) -> int:
result=0
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] == 1:
val=4-self.check(i,j,grid)
result+=val
return result
def chec... | island-perimeter | Python Soln | Poobalan1210 | 0 | 94 | island perimeter | 463 | 0.695 | Easy | 8,308 |
https://leetcode.com/problems/island-perimeter/discuss/842896/Every-step-Explain-Easley | class Solution(object):
def islandPerimeter(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
def f(r,c):
if 0<=r<len(grid) and 0<=c<len(grid[0]):
return 1
return 0
p= 0
for r, row in enu... | island-perimeter | Every step Explain Easley | paul_dream | 0 | 61 | island perimeter | 463 | 0.695 | Easy | 8,309 |
https://leetcode.com/problems/island-perimeter/discuss/712152/Easy-to-understand-80-speed | class Solution:
def islandPerimeter(self, grid: List[List[int]]) -> int:
grid= [[0]*(len(grid[0])+2)] + [[0]+item+[0] for item in grid] + [[0]*(len(grid[0])+2)]
edge_sum = 0
for i in range(1, len(grid)-1,1):
for j in range(1, len(grid[0])-1,1):
if grid[i][j] == 1... | island-perimeter | Easy to understand, 80% speed | mhymhy123 | 0 | 68 | island perimeter | 463 | 0.695 | Easy | 8,310 |
https://leetcode.com/problems/island-perimeter/discuss/464563/Python3-simple-solution-faster-than-75.34 | class Solution:
def islandPerimeter(self, grid: List[List[int]]) -> int:
total = 0
m,n = len(grid),len(grid[0])
for i in range(m):
for j in range(n):
if grid[i][j] == 1:
total += 4
if 0<=i-1<m and grid[i-1][j] == 1:
total -= 1
if 0<=i+1<m and grid[i+1][j] == 1:
total -= 1
i... | island-perimeter | Python3 simple solution, faster than 75.34% | jb07 | 0 | 94 | island perimeter | 463 | 0.695 | Easy | 8,311 |
https://leetcode.com/problems/island-perimeter/discuss/450142/Python(76.70100)-really-stupid-method-LOL | class Solution:
def islandPerimeter(self, grid: List[List[int]]) -> int:
t = 0
for vertical_position in range(len(grid)):
for horizontal_position in range(len(grid[0])):
if grid[vertical_position][horizontal_position] == 0:
continue # calculate based o... | island-perimeter | Python(76.70%/100%) really stupid method LOL | SilverCHN | 0 | 92 | island perimeter | 463 | 0.695 | Easy | 8,312 |
https://leetcode.com/problems/island-perimeter/discuss/1851768/5-Lines-Python-Solution-oror-80-Faster-oror-Memory-less-than-95 | class Solution:
def islandPerimeter(self, G: List[List[int]]) -> int:
ans=0
for i in range(len(G)):
for j in range(len(G[0])):
if G[i][j]: ans+=4-2*( (i>0 and G[i-1][j]) + (j>0 and G[i][j-1]) )
return ans | island-perimeter | 5-Lines Python Solution || 80% Faster || Memory less than 95% | Taha-C | -1 | 86 | island perimeter | 463 | 0.695 | Easy | 8,313 |
https://leetcode.com/problems/island-perimeter/discuss/1851768/5-Lines-Python-Solution-oror-80-Faster-oror-Memory-less-than-95 | class Solution:
def islandPerimeter(self, G: List[List[int]]) -> int:
return sum(2*G[i][j]*(2-(i>0 and G[i-1][j])-(j>0 and G[i][j-1])) for i,j in product(range(len(G)), range(len(G[0])))) | island-perimeter | 5-Lines Python Solution || 80% Faster || Memory less than 95% | Taha-C | -1 | 86 | island perimeter | 463 | 0.695 | Easy | 8,314 |
https://leetcode.com/problems/island-perimeter/discuss/1385316/Python3-99.88-95-memory | class Solution:
def islandPerimeter(self, grid: List[List[int]]) -> int:
p = 0
for i in range(len(grid)):
for j in range(len(grid[i])):
if grid[i][j]:
p += 4 - (i and grid[i-1][j])*2 - (j and grid[i][j - 1])*2
r... | island-perimeter | Python3 99.88% 95% memory | whitehatbuds | -1 | 166 | island perimeter | 463 | 0.695 | Easy | 8,315 |
https://leetcode.com/problems/can-i-win/discuss/850051/Python3-top-down-dp | class Solution:
def canIWin(self, maxChoosableInteger: int, desiredTotal: int) -> bool:
if desiredTotal == 0: return True # edge case 1
if maxChoosableInteger * (maxChoosableInteger+1)//2 < desiredTotal: return False # edge case 2
@lru_cache(None)
def fn(mask, total):
... | can-i-win | [Python3] top-down dp | ye15 | 3 | 423 | can i win | 464 | 0.298 | Medium | 8,316 |
https://leetcode.com/problems/can-i-win/discuss/850051/Python3-top-down-dp | class Solution:
def canIWin(self, maxChoosableInteger: int, desiredTotal: int) -> bool:
return desiredTotal == 0 or desiredTotal % (maxChoosableInteger + 1) | can-i-win | [Python3] top-down dp | ye15 | 3 | 423 | can i win | 464 | 0.298 | Medium | 8,317 |
https://leetcode.com/problems/can-i-win/discuss/2826565/Top-down-memopython-simple-solution | class Solution:
def canIWin(self, maxChoosableInteger: int, desiredTotal: int) -> bool:
# 1,2,3,4,5 -> player 1
# 2,3,4,5 -> player 2, choose any of them, cannot win
# Then 1 win
candidate = [i for i in range(1, maxChoosableInteger + 1)]
if sum(candidate) < desiredTotal:
... | can-i-win | Top-down memo/python simple solution | Lara_Craft | 0 | 3 | can i win | 464 | 0.298 | Medium | 8,318 |
https://leetcode.com/problems/can-i-win/discuss/2483316/Best-Python3-implementation-(Top-98.9)-oror-Very-simple | class Solution:
def canIWin(self, maxChoosableInteger: int, desiredTotal: int) -> bool:
remainder = [i+1 for i in range(maxChoosableInteger)] # numbers
@cache
def can_win(total, remainder):
if total >= desiredTotal:
return False # total is already exceed the desir... | can-i-win | ✔️ Best Python3 implementation (Top 98.9%) || Very simple | Kagoot | 0 | 77 | can i win | 464 | 0.298 | Medium | 8,319 |
https://leetcode.com/problems/can-i-win/discuss/1884074/Pythin-Fastest-LRU-Cache | class Solution:
def canIWin(self, maxChoosableInteger: int, desiredTotal: int) -> bool:
@lru_cache(maxsize=None)
def can_win(choices, remainder):
if choices[-1] >= remainder: return True
for index in range(len(choices)):
if not can_win(choices[:index] + choi... | can-i-win | Pythin Fastest LRU Cache | totoslg | 0 | 123 | can i win | 464 | 0.298 | Medium | 8,320 |
https://leetcode.com/problems/count-the-repetitions/discuss/2521184/Python3-repeating-patterns | class Solution:
def getMaxRepetitions(self, s1: str, n1: int, s2: str, n2: int) -> int:
cnt = idx = 0
count = []
index = []
for i in range(n1):
for ch in s1:
if ch == s2[idx]:
idx += 1
if idx == len(s2):
... | count-the-repetitions | [Python3] repeating patterns | ye15 | 0 | 22 | count the repetitions | 466 | 0.293 | Hard | 8,321 |
https://leetcode.com/problems/unique-substrings-in-wraparound-string/discuss/1705570/Python3-DP-O(N)-time-O(1)-space | class Solution:
def findSubstringInWraproundString(self, p: str) -> int:
consecutive = 1
# stores the maximum length of a substring ending at a character
maxSubstr = defaultdict(int)
maxSubstr[p[0]] = 1
ans = 0
for x in range(1, len(p)):
... | unique-substrings-in-wraparound-string | Python3 DP O(N) time O(1) space | srihariv | 1 | 92 | unique substrings in wraparound string | 467 | 0.383 | Medium | 8,322 |
https://leetcode.com/problems/unique-substrings-in-wraparound-string/discuss/850138/Python3-two-linear-implementations | class Solution:
def findSubstringInWraproundString(self, p: str) -> int:
ans = cnt = 0
seen = {} # longest string ending at char
for i in range(len(p)):
if 0 < i and (ord(p[i]) - ord(p[i-1])) % 26 != 1: cnt = 0 # reset counter
cnt += 1
if cnt > seen.get... | unique-substrings-in-wraparound-string | [Python3] two linear implementations | ye15 | 1 | 160 | unique substrings in wraparound string | 467 | 0.383 | Medium | 8,323 |
https://leetcode.com/problems/unique-substrings-in-wraparound-string/discuss/850138/Python3-two-linear-implementations | class Solution:
def findSubstringInWraproundString(self, p: str) -> int:
cnt = 0
seen = {} # longest string ending at char
for i in range(len(p)):
if 0 < i and (ord(p[i]) - ord(p[i-1])) % 26 != 1: cnt = 0 # reset counter
cnt += 1
seen[p[i]] = max(seen.g... | unique-substrings-in-wraparound-string | [Python3] two linear implementations | ye15 | 1 | 160 | unique substrings in wraparound string | 467 | 0.383 | Medium | 8,324 |
https://leetcode.com/problems/unique-substrings-in-wraparound-string/discuss/554176/O(n)-solution-easy-to-understand | class Solution:
def findSubstringInWraproundString(self, p: str) -> int:
dp=[0 for i in range(26)]
if p=="":
return 0
count=1
pre=ord(p[0])-ord('a')
dp[pre]=1
for i in p[1:]:
cur=ord(i)-ord('a')
if (pre+1)%26==cur:
c... | unique-substrings-in-wraparound-string | O(n) solution easy to understand | anudeepknpakp | 0 | 270 | unique substrings in wraparound string | 467 | 0.383 | Medium | 8,325 |
https://leetcode.com/problems/validate-ip-address/discuss/2440773/Python-or-Easiest-solution-Faster-than-99-or-easy-if-and-else | class Solution:
def validIPAddress(self, query: str) -> str:
dot = query.count(".")
colon = query.count(":")
if colon == 0 and dot == 3:
arr = [i for i in query.split(".")]
print(arr)
flag = True
for i in arr:
if i.isdigit() and int(i) <= 255:
x = int(i)
if str(x) != i:
flag = Fal... | validate-ip-address | Python | Easiest solution Faster than 99% | easy if and else | sami2002 | 0 | 134 | validate ip address | 468 | 0.266 | Medium | 8,326 |
https://leetcode.com/problems/validate-ip-address/discuss/2123680/Python-Easy-Understanding-or-Optimal-Solution | class Solution:
def validIPAddress(self, queryIP: str) -> str:
letterHashSet = ('0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f','A','B','C','D','E','F')
ipv4 = queryIP.split('.')
ipv6 = queryIP.split(':')
if len(ipv4) == 1:
if len(ipv6) !... | validate-ip-address | [Python] Easy Understanding | Optimal Solution | jamil117 | 0 | 121 | validate ip address | 468 | 0.266 | Medium | 8,327 |
https://leetcode.com/problems/validate-ip-address/discuss/1847616/Python-Simple-and-Easy-to-understand-approach | class Solution:
def validIPAddress(self, queryIP: str) -> str:
def check_valid_IP4(ip_string):
ip_string=ip_string.split(".")
if(len(ip_string)!=4):
print(ip_string)
return False
valid=True
for i in ip_string:
... | validate-ip-address | Python Simple and Easy to understand approach | bhawesh_bhashkar | 0 | 61 | validate ip address | 468 | 0.266 | Medium | 8,328 |
https://leetcode.com/problems/validate-ip-address/discuss/1735144/Easy-or-Modular-or-Python3-or-O(n)-or-24ms-Faster-than-98 | class Solution:
def validIPAddress(self, queryIP: str) -> str:
# IPv4 checks
def ipv4_is_inrange(addr):
return addr.isdigit() and int(addr)>=0 and int(addr)<=255
def ipv4_no_leading_zeros(addr):
return addr.isdigit() and ((len(addr) > 1 and ... | validate-ip-address | Easy | Modular | Python3 | O(n) | 24ms Faster than 98% | SN009006 | 0 | 114 | validate ip address | 468 | 0.266 | Medium | 8,329 |
https://leetcode.com/problems/validate-ip-address/discuss/690014/PythonPython3-Hard-not-so-understandable-solution-to-Validate-IP-Address | class Solution:
def validIPAddress(self, ip):
ip_dot = ip.split('.')
if len(ip_dot)>1:
if len(ip_dot) == 4:
for x in ip_dot:
if len(x)>1 and x[0] == '0':
return "Neither"
if not x.isnumeric() or int(x)>255:
... | validate-ip-address | [Python/Python3] Hard not so understandable solution to Validate IP Address | newborncoder | 0 | 125 | validate ip address | 468 | 0.266 | Medium | 8,330 |
https://leetcode.com/problems/validate-ip-address/discuss/514425/Python3-simple-solution-faster-than-99.75 | class Solution:
def validate_ipv4(self,IP:str)->str:
for x in IP.split("."):
if len(x)==0 or len(x)>3: return "Neither"
if not x.isdigit() or not 0<=int(x)<=255 or (x[0]=="0" and len(x)!=1): return "Neither"
return "IPv4"
def validate_ipv6(self,IP:str)->str:
... | validate-ip-address | Python3 simple solution faster than 99.75% | jb07 | 0 | 95 | validate ip address | 468 | 0.266 | Medium | 8,331 |
https://leetcode.com/problems/concatenated-words/discuss/2189673/Python3-TRIE-WITH-RECURSION-(-)-Explained | class Solution:
def findAllConcatenatedWordsInADict(self, words: List[str]) -> List[str]:
ddic = lambda: defaultdict(ddic)
trie = ddic()
for word in words:
cur = trie
for char in word:
cur = cur[char]
cur['end'] = True
... | concatenated-words | ✔️ [Python3] TRIE WITH RECURSION ᕕ( ᐛ )ᕗ, Explained | artod | 4 | 100 | concatenated words | 472 | 0.458 | Hard | 8,332 |
https://leetcode.com/problems/concatenated-words/discuss/435078/Python-DP-Simple-Solution-with-3-Lines | class Solution:
def findAllConcatenatedWordsInADict(self, words: List[str]) -> List[str]:
s = set(words)
memo = {}
def isConcatenatedWord(w):
if w in memo: return memo[w]
for i in range(1, len(w)):
if w[:i] not in s: continue
... | concatenated-words | Python DP Simple Solution with 3 Lines | thseong | 4 | 428 | concatenated words | 472 | 0.458 | Hard | 8,333 |
https://leetcode.com/problems/concatenated-words/discuss/435078/Python-DP-Simple-Solution-with-3-Lines | class Solution:
def findAllConcatenatedWordsInADict(self, words: List[str]) -> List[str]:
s, m = set(words), {}
dp = lambda w: m[w] if w in m else any(w[:i] in s and (w[i:] in s or dp(w[i:])) for i in range(1, len(w)))
return filter(dp, words) | concatenated-words | Python DP Simple Solution with 3 Lines | thseong | 4 | 428 | concatenated words | 472 | 0.458 | Hard | 8,334 |
https://leetcode.com/problems/concatenated-words/discuss/1463933/Python3-hash | class Solution:
def findAllConcatenatedWordsInADict(self, words: List[str]) -> List[str]:
seen = set(words)
@cache
def fn(word):
"""Return True if input is a concatenated word."""
for i in range(1, len(word)):
prefix = word[:i]
... | concatenated-words | [Python3] hash | ye15 | 3 | 212 | concatenated words | 472 | 0.458 | Hard | 8,335 |
https://leetcode.com/problems/concatenated-words/discuss/1204520/Python-top-down-dp-solution-faster-than-96 | class Solution:
def findAllConcatenatedWordsInADict(self, words: List[str]) -> List[str]:
wordSet = set(words)
res = []
# for each word, remove it from the set and call dp and add it back for next iteration
for word in words:
wordSet.remove(word)
if self.dp(wo... | concatenated-words | Python top down dp solution, faster than 96% | lanaYoung | 1 | 322 | concatenated words | 472 | 0.458 | Hard | 8,336 |
https://leetcode.com/problems/concatenated-words/discuss/2764054/Python-trie-%2B-DFS-with-a-HashSet-for-improvement. | class Solution:
def findAllConcatenatedWordsInADict(self, words: List[str]) -> List[str]:
trie = dict()
mem = set(words)
for w in words:
cur = trie
for c in w:
if c not in cur:
cur[c] = dict()
cur = cur[c]
... | concatenated-words | Python, trie + DFS, with a HashSet for improvement. | yiming999 | 0 | 9 | concatenated words | 472 | 0.458 | Hard | 8,337 |
https://leetcode.com/problems/concatenated-words/discuss/2564440/Python-DFS-Backtrack | class Solution:
def findAllConcatenatedWordsInADict(self, words: List[str]) -> List[str]:
wordSet = set(words)
res = set()
def dfs(s):
if not s:
return True
for i in range(len(s)):
if s[:i + 1] in wordSet:
if dfs(s[i + 1:]):
return True
return False
for word in word... | concatenated-words | Python DFS / Backtrack | shubhamnishad25 | 0 | 61 | concatenated words | 472 | 0.458 | Hard | 8,338 |
https://leetcode.com/problems/concatenated-words/discuss/2238955/python-solution-or-sort-%2B-dfs | class Solution:
def findAllConcatenatedWordsInADict(self, words: List[str]) -> List[str]:
def dfs(word):
if word == "":
return True
for i in range(1,len(word)+1):
if word[:i] in vis:
if dfs(word[i:]):
... | concatenated-words | python solution | sort + dfs | hardernharder | 0 | 117 | concatenated words | 472 | 0.458 | Hard | 8,339 |
https://leetcode.com/problems/concatenated-words/discuss/2228648/Dynamic-Programming-Approach-oror-Memoization | class Solution:
def goodWord(self, word, wordSet):
dpMap = {}
if word in dpMap:
return dpMap[word]
dpMap[word] = False
for i in range(1, len(word)):
prefix = word[:i]
suffix = word[i:]
if (prefix ... | concatenated-words | Dynamic Programming Approach || Memoization | Vaibhav7860 | 0 | 164 | concatenated words | 472 | 0.458 | Hard | 8,340 |
https://leetcode.com/problems/concatenated-words/discuss/1883437/Python-or-DFS-and-Memoization | class Solution:
def findAllConcatenatedWordsInADict(self, words: List[str]) -> List[str]:
wordset = set(words)
@lru_cache(None)
def dfs(word):
for i in range(1, len(word)):
prefix = word[:i]
suffix = word[i:]
... | concatenated-words | Python | DFS & Memoization | rbhandu | 0 | 228 | concatenated words | 472 | 0.458 | Hard | 8,341 |
https://leetcode.com/problems/concatenated-words/discuss/1797494/Python3-Trie-%2B-DFS-OOP | class Solution:
def findAllConcatenatedWordsInADict(self, words: List[str]) -> List[str]:
class Trie:
def __init__(self):
self.root = {'leaf': False, 'child': {}}
def add(self, word):
cur = self.root
for i, c in enumerate(word)... | concatenated-words | Python3 Trie + DFS OOP | metacriteria | 0 | 155 | concatenated words | 472 | 0.458 | Hard | 8,342 |
https://leetcode.com/problems/concatenated-words/discuss/1396466/Short-and-Simple-recursive-solution | class Solution:
def findAllConcatenatedWordsInADict(self, words: List[str]) -> List[str]:
wordset = set(words)
@cache
def f(word,i):
if i >= len(word):
return True
j = i+1
while j <= len(word):
if word[i:j]... | concatenated-words | Short and Simple recursive solution | worker-bee | 0 | 260 | concatenated words | 472 | 0.458 | Hard | 8,343 |
https://leetcode.com/problems/matchsticks-to-square/discuss/2270373/Python-3DP-%2B-Bitmask | class Solution:
def makesquare(self, arr: List[int]) -> bool:
# no way to make the square if total length not divisble by 4
if sum(arr) % 4:
return False
# target side length
side = sum(arr) // 4
@lru_cache(None)
def dp(k, mask, s):
# finish all f... | matchsticks-to-square | [Python 3]DP + Bitmask | chestnut890123 | 6 | 662 | matchsticks to square | 473 | 0.404 | Medium | 8,344 |
https://leetcode.com/problems/matchsticks-to-square/discuss/2270603/Cleanest-Python3-code-with-explanation-Generalized-partitioning-into-k-buckets | class Solution:
def makesquare(self, matchsticks: List[int]) -> bool:
# There should be at least 4 matchsticks.
if len(matchsticks) < 4:
return False
# Sum of matchstick lengths should be divisble by four.
side_length, remainder = divmod(sum(matchsticks), 4)
... | matchsticks-to-square | Cleanest Python3 code with explanation / Generalized partitioning into k-buckets | code-art | 2 | 335 | matchsticks to square | 473 | 0.404 | Medium | 8,345 |
https://leetcode.com/problems/matchsticks-to-square/discuss/2368362/python-or-using-Backtracking-or-Faster-than-99 | class Solution:
def makesquare(self, matchsticks: List[int]) -> bool:
target,m=divmod(sum(matchsticks),4)
if m:return False
targetLst=[0]*4
length=len(matchsticks)
matchsticks.sort(reverse=True)
def bt(i):
if i==length:
return len(set(targe... | matchsticks-to-square | python | using Backtracking | Faster than 99% | solityde | 1 | 104 | matchsticks to square | 473 | 0.404 | Medium | 8,346 |
https://leetcode.com/problems/matchsticks-to-square/discuss/2034695/Python-Backtracking | class Solution:
def makesquare(self, matchsticks: List[int]) -> bool:
sides = [0]*4
if sum(matchsticks)%4!=0:
return False
s = sum(matchsticks)//4
matchsticks.sort(reverse=True)
def helper(i):
if i == len(matchsticks... | matchsticks-to-square | Python Backtracking | Brillianttyagi | 1 | 193 | matchsticks to square | 473 | 0.404 | Medium | 8,347 |
https://leetcode.com/problems/matchsticks-to-square/discuss/1511414/Python-simple-backtracking-solution-(Easy-to-understand) | class Solution:
def makesquare(self, nums: List[int]) -> bool:
k = 4
s = sum(nums)
if s % k != 0:
return False
target = s // k
n = len(nums)
def dfs(m):
stack = [(m, 0, {m}, nums[m])]
... | matchsticks-to-square | Python simple backtracking solution (Easy to understand) | byuns9334 | 1 | 312 | matchsticks to square | 473 | 0.404 | Medium | 8,348 |
https://leetcode.com/problems/matchsticks-to-square/discuss/2804881/God-Bless-this-mess | class Solution:
def makesquare(self, matchsticks: List[int]) -> bool:
totalSum = 0
for i in matchsticks:
totalSum += i
memo ={}
possible_side = totalSum // 4
if possible_side * 4 != totalSum:
return False
matchsticks.sort(reverse=Tr... | matchsticks-to-square | God Bless this mess | RaulS0s4 | 0 | 1 | matchsticks to square | 473 | 0.404 | Medium | 8,349 |
https://leetcode.com/problems/matchsticks-to-square/discuss/2274224/bitmask-dp-python3-solution | class Solution:
def makesquare(self, matchsticks: List[int]) -> bool:
matchsticks=sorted(matchsticks)
tot=sum(matchsticks)
if tot%4!=0 or len(matchsticks)<4 or matchsticks[-1]>tot/4:
return False
l=len(matchsticks)
length=tot//4
size = 1<<l
subset ... | matchsticks-to-square | bitmask dp python3 solution | appleface | 0 | 4 | matchsticks to square | 473 | 0.404 | Medium | 8,350 |
https://leetcode.com/problems/matchsticks-to-square/discuss/2271901/Python3-solution-with-DFS-and-memoization-(with-comments-in-the-code) | class Solution:
def makesquare(self, matchsticks: List[int]) -> bool:
all_sum = sum(matchsticks)
if all_sum % 4 != 0:
return False
side_size = all_sum // 4
n = len(matchsticks)
sides = [0] * 4
sm = sorted(matchsticks, reverse=True)
memo = set()... | matchsticks-to-square | Python3 solution with DFS and memoization (with comments in the code) | mplpl | 0 | 31 | matchsticks to square | 473 | 0.404 | Medium | 8,351 |
https://leetcode.com/problems/matchsticks-to-square/discuss/2271207/Clean-Python-with-Backtracking-and-Memoization-(No-need-for-bitmask) | class Solution:
def makesquare(self, matchsticks: List[int]) -> bool:
circumference = sum(matchsticks)
sidewidth = circumference // 4
# rectangle requires all sides to have equal length
if circumference % 4 != 0:
return False
# speeds it up in pr... | matchsticks-to-square | Clean Python with Backtracking and Memoization (No need for bitmask) | boris17 | 0 | 77 | matchsticks to square | 473 | 0.404 | Medium | 8,352 |
https://leetcode.com/problems/matchsticks-to-square/discuss/2270992/Backtracking-Solution-oror-Clean-Code-oror-Easy-to-Understand | class Solution:
def backtrack(self, i, matchsticks, side, sideLen):
if i == len(matchsticks):
return True
for j in range(4):
if side[j] + matchsticks[i] <= sideLen:
side[j] += matchsticks[i]
if self.backtrack(i + 1, matchsticks, side, ... | matchsticks-to-square | Backtracking Solution || Clean Code || Easy to Understand | Vaibhav7860 | 0 | 54 | matchsticks to square | 473 | 0.404 | Medium | 8,353 |
https://leetcode.com/problems/matchsticks-to-square/discuss/2270424/Recursively-approach | class Solution:
def makesquare(self, matchsticks: List[int]) -> bool:
stick_length_sum = sum(matchsticks)
side_length, extra_remain = divmod(stick_length_sum, 4)
if extra_remain > 0:
# Corner case1: Sum of all stick length can't be dividable by 4
return False
... | matchsticks-to-square | Recursively approach | puremonkey2001 | 0 | 14 | matchsticks to square | 473 | 0.404 | Medium | 8,354 |
https://leetcode.com/problems/matchsticks-to-square/discuss/1728519/Python-using-backtracking-%2B-memoization | class Solution:
def makesquare(self,matchsticks):
if(len(matchsticks)<4):
return False
s = 0
n = 0
s = s//4
vis = []
for i in matchsticks:
s = s + i
n = n + 1
vis.append('0')
if(s%4):
return False
s = s//4
matchsticks.sort(reverse = True)
if(matchsticks[0] > s):
return False
h =... | matchsticks-to-square | Python using backtracking + memoization | jagdishpawar8105 | 0 | 114 | matchsticks to square | 473 | 0.404 | Medium | 8,355 |
https://leetcode.com/problems/matchsticks-to-square/discuss/1584414/Python3-backtracking-easy | class Solution:
def makesquare(self, matchsticks: List[int]) -> bool:
target = sum(matchsticks)
if target % 4 != 0:
return False
target = target / 4
size = [0] * 4
matchsticks.sort(reverse = True)
def backtrack(i):
... | matchsticks-to-square | Python3 - backtracking easy | Shubham_Muramkar | 0 | 192 | matchsticks to square | 473 | 0.404 | Medium | 8,356 |
https://leetcode.com/problems/matchsticks-to-square/discuss/1275155/Python3-2-approaches-backtracking-and-dp | class Solution:
def makesquare(self, matchsticks: List[int]) -> bool:
q, r = divmod(sum(matchsticks), 4)
if len(matchsticks) < 4 or r: return False
def fn(k):
"""Return True if it is possible to make a square."""
if k == len(matchsticks): return True
... | matchsticks-to-square | [Python3] 2 approaches - backtracking & dp | ye15 | 0 | 77 | matchsticks to square | 473 | 0.404 | Medium | 8,357 |
https://leetcode.com/problems/matchsticks-to-square/discuss/1275155/Python3-2-approaches-backtracking-and-dp | class Solution:
def makesquare(self, matchsticks: List[int]) -> bool:
q, r = divmod(sum(matchsticks), 4)
if len(matchsticks) < 4 or r: return False
@cache
def fn(mask, x):
"""Return True if it is possible to make a square."""
if not mask: return True... | matchsticks-to-square | [Python3] 2 approaches - backtracking & dp | ye15 | 0 | 77 | matchsticks to square | 473 | 0.404 | Medium | 8,358 |
https://leetcode.com/problems/matchsticks-to-square/discuss/1274059/python3-Sort-Backtracking-solution-for-reference. | class Solution:
def makesquare(self, matchsticks) -> bool:
total_circumference = sum(matchsticks)
side = total_circumference/4
if int(side) != side:
return False
matchsticks.sort()
paths = [0]*4
h = {}
if matchsticks[-1] > side:
... | matchsticks-to-square | [python3] Sort, Backtracking solution for reference. | vadhri_venkat | 0 | 86 | matchsticks to square | 473 | 0.404 | Medium | 8,359 |
https://leetcode.com/problems/ones-and-zeroes/discuss/2065208/Python-Easy-DP-2-approaches | class Solution:
def findMaxForm(self, strs: List[str], m: int, n: int) -> int:
counter=[[s.count("0"), s.count("1")] for s in strs]
@cache
def dp(i,j,idx):
if i<0 or j<0:
return -math.inf
if idx==len(strs):
return ... | ones-and-zeroes | Python Easy DP 2 approaches | constantine786 | 71 | 4,300 | ones and zeroes | 474 | 0.467 | Medium | 8,360 |
https://leetcode.com/problems/ones-and-zeroes/discuss/2065208/Python-Easy-DP-2-approaches | class Solution:
def findMaxForm(self, strs: List[str], m: int, n: int) -> int:
dp = [[0] * (n+1) for _ in range(m+1)]
counter=[[s.count("0"), s.count("1")] for s in strs]
for zeroes, ones in counter:
for i in range(m, zeroes-1, -1):
for j in r... | ones-and-zeroes | Python Easy DP 2 approaches | constantine786 | 71 | 4,300 | ones and zeroes | 474 | 0.467 | Medium | 8,361 |
https://leetcode.com/problems/ones-and-zeroes/discuss/2067137/Python-or-Easy-DP | class Solution:
def findMaxForm(self, strs: List[str], m: int, n: int) -> int:
dp = [[0 for i in range(m+1)] for i in range(n+1)]
for s in strs:
ones = s.count("1")
zeros = s.count("0")
for i in range(n,ones-1,-1):
fo... | ones-and-zeroes | Python | Easy DP | LittleMonster23 | 6 | 416 | ones and zeroes | 474 | 0.467 | Medium | 8,362 |
https://leetcode.com/problems/ones-and-zeroes/discuss/1847518/python-3-oror-recursive-dynamic-programming | class Solution:
def findMaxForm(self, strs: List[str], m: int, n: int) -> int:
strs = [collections.Counter(s) for s in strs]
dp = {}
def helper(i, m, n):
if i == len(strs):
return 0
x = (i, m, n)
if x in dp:
... | ones-and-zeroes | python 3 || recursive dynamic programming | dereky4 | 2 | 184 | ones and zeroes | 474 | 0.467 | Medium | 8,363 |
https://leetcode.com/problems/ones-and-zeroes/discuss/2838022/Python3-Solution-or-Knapsack-or-DP | class Solution:
def findMaxForm(self, S, M, N):
dp = [[0] * (M + 1) for _ in range(N + 1)]
for s in S:
x, y = s.count('1'), s.count('0')
for i in range(N - x, -1, -1):
for j in range(M - y, -1, -1):
dp[i + x][j + y] = max(dp[i + x][j + y], ... | ones-and-zeroes | ✔ Python3 Solution | Knapsack | DP | satyam2001 | 1 | 19 | ones and zeroes | 474 | 0.467 | Medium | 8,364 |
https://leetcode.com/problems/ones-and-zeroes/discuss/2066242/Python-oror-Cache-oror-DP-oror-No-TLE | class Solution:
def findMaxForm(self, arr: List[str], m: int, n: int) -> int:
@cache
# cache used for the program to be executed faster
# if not used may give time limit exceeded
def solve(i,m,n):
if m<0 or n<0:
return -math.inf
if (i>=len(arr... | ones-and-zeroes | Python || Cache || DP || No TLE | karan_8082 | 1 | 84 | ones and zeroes | 474 | 0.467 | Medium | 8,365 |
https://leetcode.com/problems/ones-and-zeroes/discuss/1956260/Python-easy-to-read-and-understand-or-knapsack | class Solution:
def solve(self, strs, index, m, n):
if index < 0:
return 0
if m < 0 or n < 0:
return 0
zeros, ones = strs[index].count("0"), strs[index].count("1")
if zeros <= m and ones <= n:
return max(1 + self.solve(strs, index - 1, m - zeros, n... | ones-and-zeroes | Python easy to read and understand | knapsack | sanial2001 | 1 | 156 | ones and zeroes | 474 | 0.467 | Medium | 8,366 |
https://leetcode.com/problems/ones-and-zeroes/discuss/1956260/Python-easy-to-read-and-understand-or-knapsack | class Solution:
def solve(self, strs, index, m, n):
if index < 0:
return 0
if m < 0 or n < 0:
return 0
if (index, m, n) in self.d:
return self.d[(index, m, n)]
zeros, ones = strs[index].count("0"), strs[index].count("1")
if zeros <= m and o... | ones-and-zeroes | Python easy to read and understand | knapsack | sanial2001 | 1 | 156 | ones and zeroes | 474 | 0.467 | Medium | 8,367 |
https://leetcode.com/problems/ones-and-zeroes/discuss/2797552/Python-(Simple-Dynamic-Programming) | class Solution:
def findMaxForm(self, strs, m, n):
dp = [[0]*(n+1) for _ in range(m+1)]
ans = [(i.count("0"),i.count("1")) for i in strs]
for zeroes,ones in ans:
for j in range(m,-1,-1):
for k in range(n,-1,-1):
if j - zeroes >= 0 and k - one... | ones-and-zeroes | Python (Simple Dynamic Programming) | rnotappl | 0 | 3 | ones and zeroes | 474 | 0.467 | Medium | 8,368 |
https://leetcode.com/problems/ones-and-zeroes/discuss/2670917/Python-recursion%2Bmemoization-easy-solution | class Solution:
def findMaxForm(self, A: List[str], m: int, n: int) -> int:
dp={}
def solve(A,i,m,n):
if i==0:
return 0
if (i,m,n) in dp:
return dp[(i,m,n)]
x = A[i-1]
temp1 = 0
if x.count("0")<=m and x.coun... | ones-and-zeroes | Python recursion+memoization easy solution | Akash_chavan | 0 | 12 | ones and zeroes | 474 | 0.467 | Medium | 8,369 |
https://leetcode.com/problems/ones-and-zeroes/discuss/2666642/Python-Solution-or-Knapsack-DP-reduced-memory | class Solution:
def findMaxForm(self, strs: List[str], m: int, n: int) -> int:
ones = [s.count('1') for s in strs]
zeros = [s.count('0') for s in strs]
dp1 = [[0 for _ in range(n+1)] for _ in range(m+1)]
dp2 = [[0 for _ in range(n+1)] for _ in range(m+1)]
for i in range(m+1... | ones-and-zeroes | Python Solution | Knapsack DP reduced memory | on_danse_encore_on_rit_encore | 0 | 8 | ones and zeroes | 474 | 0.467 | Medium | 8,370 |
https://leetcode.com/problems/ones-and-zeroes/discuss/2602251/python3-DP | class Solution:
def findMaxForm(self, strs: List[str], m: int, n: int) -> int:
cache={}
mp={}
# mp is precomputed count of 1 and 0 in strs[i]
for i in range(len(strs)):
mp[i]=(strs[i].count('0'),strs[i].count('1'))
def dp(i,m_till_now,n_till_now):
... | ones-and-zeroes | python3 DP | ketansomvanshi007 | 0 | 44 | ones and zeroes | 474 | 0.467 | Medium | 8,371 |
https://leetcode.com/problems/ones-and-zeroes/discuss/2068222/Python-numpy-Faster-and-tidy-DP-code-using-numpy-array | class Solution:
def findMaxForm(self, strs: List[str], m: int, n: int) -> int:
import numpy as np
a = np.zeros([m+1, n+1], dtype=np.int16)
for st in strs:
ms, ns = st.count('0'), st.count('1')
a[ms:, ns:] = np.maximum(a[ms:, ns:], a[:-ms if ms>0 else None, :-ns if ns>... | ones-and-zeroes | [Python numpy] Faster and tidy DP code using numpy array | zzjjbb | 0 | 8 | ones and zeroes | 474 | 0.467 | Medium | 8,372 |
https://leetcode.com/problems/ones-and-zeroes/discuss/2066249/Python-or-DP | class Solution:
def findMaxForm(self, st: List[str], m: int, n: int) -> int:
d = []
n1 =len(st)
for val in st:
d.append([val.count("0"),val.count("1")])
t = [[[0 for i in range(n+1)]for j in range(m+1)]for k in range(n1+1)]
for i in range(n1+1):
... | ones-and-zeroes | Python | DP | Shivamk09 | 0 | 57 | ones and zeroes | 474 | 0.467 | Medium | 8,373 |
https://leetcode.com/problems/ones-and-zeroes/discuss/2066095/Python3-Solution-with-using-dp | class Solution:
def findMaxForm(self, strs: List[str], m: int, n: int) -> int:
dp = [[0 for _ in range(n + 1)] for _ in range(m + 1)]
for _str in strs:
zeros_cnt = _str.count('0')
ones_cnt = len(_str) - zeros_cnt
for i in range(m, zeros_cnt -... | ones-and-zeroes | [Python3] Solution with using dp | maosipov11 | 0 | 22 | ones and zeroes | 474 | 0.467 | Medium | 8,374 |
https://leetcode.com/problems/ones-and-zeroes/discuss/2065979/java-python-dp | class Solution:
def findMaxForm(self, strs: List[str], m: int, n: int) -> int:
dp = []
for i in range(101): dp.append([0]*101)
for s in strs :
ziros, ones = 0, 0
for i in range(len(s)):
if s[i] == '0' : ziros += 1
ones = len(s) - ziros
for i in range ... | ones-and-zeroes | java, python - dp | ZX007java | 0 | 37 | ones and zeroes | 474 | 0.467 | Medium | 8,375 |
https://leetcode.com/problems/ones-and-zeroes/discuss/2065800/Python3-Simple-DP-Solution-(Top-Down) | class Solution:
def findMaxForm(self, strs: List[str], m: int, n: int) -> int:
counter = [[s.count("0"), s.count("1")] for s in strs]
@lru_cache(None)
def dp(m: int, n: int, idx: int) -> int:
# base case
if m < 0 or n < 0:
return float('-inf')
... | ones-and-zeroes | ✅ [Python3] Simple DP Solution (Top-Down) | JawadNoor | 0 | 28 | ones and zeroes | 474 | 0.467 | Medium | 8,376 |
https://leetcode.com/problems/ones-and-zeroes/discuss/2065776/Python3-oror-Top-Down-Dynamic-Programming-oror-Easy | class Solution:
def findMaxForm(self, strs: List[str], m: int, n: int) -> int:
count = {}
for str in strs:
count[str] = [str.count("0"), str.count("1")]
@lru_cache(None)
def dp(index, m, n):
if index == len(strs):
return 0
... | ones-and-zeroes | Python3 || Top-Down Dynamic Programming || Easy | suhrid | 0 | 56 | ones and zeroes | 474 | 0.467 | Medium | 8,377 |
https://leetcode.com/problems/ones-and-zeroes/discuss/2065558/Python-Simple-3D-dp | class Solution:
def findMaxForm(self, strs: List[str], m: int, n: int) -> int:
N = len(strs)
zeros = [0]*N
ones = [0]*N
dp = {}
for i in range(N):
zeros[i] = strs[i].count('0')
ones[i] = strs[i].count('1')
def solve(index,z,o):
if i... | ones-and-zeroes | Python Simple 3D dp | Kakashi_97 | 0 | 76 | ones and zeroes | 474 | 0.467 | Medium | 8,378 |
https://leetcode.com/problems/ones-and-zeroes/discuss/851319/Python3-knapsack-problem-solved-via-dp | class Solution:
def findMaxForm(self, strs: List[str], m: int, n: int) -> int:
@lru_cache(None)
def fn(i, m, n):
"""Return maximum number of strings."""
if i == len(strs): return 0
nn = len(strs[i]) - (mm := strs[i].count("0"))
return max(1 +... | ones-and-zeroes | [Python3] knapsack problem solved via dp | ye15 | 0 | 204 | ones and zeroes | 474 | 0.467 | Medium | 8,379 |
https://leetcode.com/problems/ones-and-zeroes/discuss/688471/Python-Knapsack-DP-9-lines-7472-ms | class Solution:
def findMaxForm(self, strs: List[str], m: int, n: int) -> int:
dp = [[0 for j in range(n+1)] for i in range(m+1)]
# using defaultdict runs out of time.
for s in strs:
cnt = collections.Counter(s)
for j in range(m-cnt["0"], -1, -1):
for k in r... | ones-and-zeroes | [Python] Knapsack DP 9 lines 7472 ms | readonly_true | 0 | 208 | ones and zeroes | 474 | 0.467 | Medium | 8,380 |
https://leetcode.com/problems/ones-and-zeroes/discuss/590163/Python-Recursive-Solution-Easy-to-Understand | class Solution:
def findMaxForm(self, strs: List[str], m: int, n: int) -> int:
def recursive():
def func(i, m, n):
if i >= length:
return 0
# If it is already in memory, return the result
if (i, m, n) in mem:
re... | ones-and-zeroes | [Python] Recursive Solution Easy to Understand | ixez | 0 | 275 | ones and zeroes | 474 | 0.467 | Medium | 8,381 |
https://leetcode.com/problems/ones-and-zeroes/discuss/495532/Python3-recursive-solution | class Solution:
def findMaxForm(self, strs: List[str], m: int, n: int) -> int:
arr = sorted([(len(i), sum([1 for j in i if j == '0'])) for i in strs])
arr = [(i[1], i[0]-i[1], i[0]) for i in arr] # N0, N1, len
ptr = 0
larr = len(arr)
print(larr)
memo = {}
... | ones-and-zeroes | Python3 recursive solution | asdfghjbenny | 0 | 202 | ones and zeroes | 474 | 0.467 | Medium | 8,382 |
https://leetcode.com/problems/heaters/discuss/2711430/python-99.84-speed-O(1)-memory | class Solution:
def findRadius(self, houses: List[int], heaters: List[int]) -> int:
houses.sort()
heaters.sort()
if len(heaters) == 1:
return max(abs(houses[0] - heaters[0]), abs(houses[-1] - heaters[0]))
m_value = -1
f, s, ind_heat = heaters[0], heaters[1], 2
... | heaters | python 99.84% speed O(1) memory | Yaro1 | 2 | 234 | heaters | 475 | 0.361 | Medium | 8,383 |
https://leetcode.com/problems/heaters/discuss/1933263/Python-easy-understanding-greedy-solution. | class Solution:
def findRadius(self, houses: List[int], heaters: List[int]) -> int:
houses.sort()
heaters.sort()
res = 0
heater = 0
for h in houses:
while heater + 1 < len(heaters) and heaters[heater + 1] == heaters[heater]: # Avoid dupli... | heaters | Python easy-understanding greedy solution. | byroncharly3 | 2 | 170 | heaters | 475 | 0.361 | Medium | 8,384 |
https://leetcode.com/problems/heaters/discuss/1813779/Binary-Search-Python | class Solution:
def findRadius(self, houses: List[int], heaters: List[int]) -> int:
heaters.sort() # so that we can use binary search
result = float("-inf")
for house in houses:
distanceToNearestHeater = self.bs(house, heaters)
result = max(result, distanceToN... | heaters | Binary Search - Python | adwaithks | 2 | 232 | heaters | 475 | 0.361 | Medium | 8,385 |
https://leetcode.com/problems/heaters/discuss/1636852/Python3-greedy | class Solution:
def findRadius(self, houses: List[int], heaters: List[int]) -> int:
heaters.sort()
ans = k = 0
for x in sorted(houses):
while k < len(heaters) and heaters[k] < x: k += 1
cand = inf
if k < len(heaters): cand = min(cand, heaters[k] - x)
... | heaters | [Python3] greedy | ye15 | 2 | 63 | heaters | 475 | 0.361 | Medium | 8,386 |
https://leetcode.com/problems/heaters/discuss/2513745/Python-Greedy-O(nlogn)-runtime-and-O(1)-extra-space | class Solution:
def findRadius(self, houses: List[int], heaters: List[int]) -> int:
houses.sort()
heaters.sort()
max_r = 0
heater = 0
for i,house in enumerate(houses):
# Greedy: check if the next heater will shorter the radius compared to the cur... | heaters | [Python] - Greedy - O(nlogn) runtime and O(1) extra space | micktoying | 1 | 76 | heaters | 475 | 0.361 | Medium | 8,387 |
https://leetcode.com/problems/heaters/discuss/380196/Solution-in-Python-3-(three-lines) | class Solution:
def findRadius(self, h: List[int], t: List[int]) -> int:
LT, M, _, _ = len(t)-1, [0,0], h.sort(), t.sort()
for i in h: M = (lambda x: [max(M[0],min(abs(i-t[x-1]),abs(i-t[x]))),x])(bisect.bisect(t,i,M[1],LT))
return M[0]
- Junaid Mansuri
(LeetCode ID)@hotmail.com | heaters | Solution in Python 3 (three lines) | junaidmansuri | 1 | 695 | heaters | 475 | 0.361 | Medium | 8,388 |
https://leetcode.com/problems/heaters/discuss/2708947/Sort-both-and-use-two-pointers | class Solution:
def findRadius(self, houses: List[int], heaters: List[int]) -> int:
heaters.sort()
houses.sort()
m = len(heaters)
radius = float("-inf")
i = 0
for house in houses:
while i < m and heaters[i] <= house:
i += 1
left... | heaters | Sort both and use two pointers | abbus | 0 | 10 | heaters | 475 | 0.361 | Medium | 8,389 |
https://leetcode.com/problems/heaters/discuss/2629822/Python3-short-chean-code-and-faster-than-96.68 | class Solution:
def findRadius(self, houses: List[int], heaters: List[int]) -> int:
houses.sort()
heaters.sort()
mrad=0 #Initiate the max radius with a value 0
i=0 #Currently we are looking at the ith heater, serve as a heater pointer
l=len(heaters)-2 #Check how many heaters ... | heaters | Python3, short, chean code and faster than 96.68% | atmosphere77777 | 0 | 17 | heaters | 475 | 0.361 | Medium | 8,390 |
https://leetcode.com/problems/heaters/discuss/2629822/Python3-short-chean-code-and-faster-than-96.68 | class Solution:
def findRadius(self, houses: List[int], heaters: List[int]) -> int:
houses.sort()
heaters.sort()
mrad=0
i=0
l=len(heaters)-2
for ele in houses:
while i<=l and (abs(ele-heaters[i])>=abs(ele-heaters[i+1])):
i+=1
else:
... | heaters | Python3, short, chean code and faster than 96.68% | atmosphere77777 | 0 | 17 | heaters | 475 | 0.361 | Medium | 8,391 |
https://leetcode.com/problems/heaters/discuss/2615798/Python-solution-w-comments | class Solution:
def findRadius(self, houses: List[int], heaters: List[int]) -> int:
minRad = 0
# sort heaters so we can do binary search on it
heaters.sort()
# loop through each house, and perform binary search to find closest heater
for house in houses:
l, r = 0, len(heaters) - 1
dist = float('inf')... | heaters | Python solution w/ comments | Mark5013 | 0 | 18 | heaters | 475 | 0.361 | Medium | 8,392 |
https://leetcode.com/problems/heaters/discuss/2124950/HexPython-Binary-Search | class Solution:
def findRadius(self, houses: List[int], heaters: List[int]) -> int:
houses.sort()
heaters.sort()
l, r = 0, max(houses[-1], heaters[-1])
while l <= r:
mid = l + (r-l)//2
if self.canHeat(mid, heaters, houses):
r = mid-1
... | heaters | 【Hex】Python - Binary Search | HexuanWeng | 0 | 43 | heaters | 475 | 0.361 | Medium | 8,393 |
https://leetcode.com/problems/heaters/discuss/2110460/python-3-oror-two-pointer-solution-oror-O(nlogn) | class Solution:
def findRadius(self, houses: List[int], heaters: List[int]) -> int:
houses.sort()
heaters.sort()
heaters.append(math.inf)
radius = 0
i = 0
for house in houses:
while abs(house - heaters[i + 1]) <= abs(house - heaters[i]):
... | heaters | python 3 || two pointer solution || O(nlogn) | dereky4 | 0 | 150 | heaters | 475 | 0.361 | Medium | 8,394 |
https://leetcode.com/problems/heaters/discuss/2038009/Python-binary-search-O(n-*-log-n) | class Solution:
def findRadius(self, houses: List[int], heaters: List[int]) -> int:
heaters.sort()
radius = 0
for house in houses:
rad = self.get_min_dis(house, heaters)
radius = max(radius, rad)
return radius
# binary search
d... | heaters | Python binary search O(n * log n) | styode | 0 | 152 | heaters | 475 | 0.361 | Medium | 8,395 |
https://leetcode.com/problems/heaters/discuss/2038004/Python-two-pointer-O(n*logn) | class Solution:
def findRadius(self, houses: List[int], heaters: List[int]) -> int:
# time O(n*log n) -> python library sort
houses.sort()
heaters.sort()
n, m = len(houses), len(heaters)
i, j = 0, 0
heat_radius = 0
while i < n and j < m:
... | heaters | Python two pointer O(n*logn) | styode | 0 | 81 | heaters | 475 | 0.361 | Medium | 8,396 |
https://leetcode.com/problems/heaters/discuss/1684679/python-foolish-binary-search-w-explanation | class Solution:
def findRadius(self, houses: List[int], heaters: List[int]) -> int:
houses.sort()
heaters.sort()
total, size = len(houses), len(heaters)
#dummy solution to check if heater with radius r, to cover all houses
def valid_radius(r):
house_offset = 0
... | heaters | python foolish binary search w explanation | 752937603 | 0 | 59 | heaters | 475 | 0.361 | Medium | 8,397 |
https://leetcode.com/problems/number-complement/discuss/488055/Python-O(-lg-n-)-sol.-by-XOR-masking.-85%2B-With-explanation | class Solution:
def findComplement(self, num: int) -> int:
bit_mask = 2**num.bit_length() -1
return ( num ^ bit_mask ) | number-complement | Python O( lg n ) sol. by XOR masking. 85%+ [ With explanation ] | brianchiang_tw | 17 | 1,100 | number complement | 476 | 0.672 | Easy | 8,398 |
https://leetcode.com/problems/number-complement/discuss/1649436/Python3-BITWISE-OPERATORS-**-Explained | class Solution:
def findComplement(self, num: int) -> int:
res, n = 0, 0
while num:
if not num & 1:
res += 2**n
num >>= 1
n += 1
return res | number-complement | ✔️ [Python3] BITWISE OPERATORS •͡˘㇁•͡˘, Explained | artod | 7 | 545 | number complement | 476 | 0.672 | Easy | 8,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.