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/house-robber/discuss/2821702/DYNAMIC-PROGRAMMING-oror-FASTEST-oror-BEATS-99-SUBMISSIONS-oror-EASIEST | class Solution:
def rob(self, nums: List[int]) -> int:
r1,r2=0,0
for i in nums:
t=max(r1+i,r2)
r1=r2
r2=t
return r2 | house-robber | DYNAMIC PROGRAMMING || FASTEST || BEATS 99% SUBMISSIONS || EASIEST | Pritz10 | 0 | 7 | house robber | 198 | 0.488 | Medium | 3,200 |
https://leetcode.com/problems/house-robber/discuss/2814165/Fully-Optimized-Code-oror-Python-oror-Easy-to-Understand | class Solution(object):
def rob(self, nums):
prev = 0
prev2 = 0
for i in range(len(nums)):
#Pick the number
take = nums[i]
if i > 1: take += prev2
#Not pick the number
notTake = prev
curr = max(take,notTake)
prev2 = prev
prev = curr
return prev | house-robber | Fully Optimized Code💯 || Python || Easy to Understand✅ | __avinash_007 | 0 | 5 | house robber | 198 | 0.488 | Medium | 3,201 |
https://leetcode.com/problems/house-robber/discuss/2791948/Backtracking-%2B-DP | class Solution:
def rob(self, nums: List[int]) -> int:
n = len(nums)
dp = {}
def dfs(index, steal):
if (index, steal) in dp:
return dp[(index, steal)]
if index == n:
return 0
result = 0
if steal:
result = max (result, nums[index]+dfs(index+1, not steal))
result = max(result, dfs(index+1, steal))
else:
result = max(result, dfs(index+1, not steal))
dp[(index, steal)] = result
return result
answer = dfs(0, True)
return answer | house-robber | Backtracking + DP | ayhamhashesh | 0 | 2 | house robber | 198 | 0.488 | Medium | 3,202 |
https://leetcode.com/problems/house-robber/discuss/2780327/Simple-and-Clear-O(N)-Method | class Solution:
def rob(self, nums: List[int]) -> int:
if len(nums) <= 2:
return max(nums)
dp = [0 for _ in range(len(nums))]
dp[0] = nums[0]
dp[1] = nums[1]
prev_max = -inf
for i in range(2, len(nums)):
prev_max = max(prev_max, dp[i-2])
dp[i] = max(dp[i], dp[i-1], prev_max+nums[i])
return dp[-1] | house-robber | Simple and Clear O(N) Method | SnoopyLovesCoding | 0 | 3 | house robber | 198 | 0.488 | Medium | 3,203 |
https://leetcode.com/problems/house-robber/discuss/2764118/House-Robber-Python-solution | class Solution:
def rob(self, nums: List[int]) -> int:
rob1, rob2 = 0,0
for i in nums:
ans = max (rob1 + i , rob2)
rob1,rob2 = rob2,ans
return rob2 | house-robber | House Robber Python solution | Sujit773 | 0 | 1 | house robber | 198 | 0.488 | Medium | 3,204 |
https://leetcode.com/problems/house-robber/discuss/2730842/Python-Bottom-up | class Solution:
def rob(self, nums: List[int]) -> int:
n = len(nums)
dp = [0]*n
dp[0] = nums[0]
for i in range(1 , n):
take = nums[i]
if i > 1:
take += dp[i-2]
notTake = dp[i-1]
dp[i] = max(take , notTake)
return dp[n-1] | house-robber | Python Bottom - up | rajitkumarchauhan99 | 0 | 7 | house robber | 198 | 0.488 | Medium | 3,205 |
https://leetcode.com/problems/house-robber/discuss/2730327/Python-or-DP-or-Top-Down-or-Bottom-Up-or-3-Approaches | class Solution:
def rob(self, nums: List[int]) -> int:
def bottom_up():
'''
Bottom up 1d solution
dp[i]: maximum amount of money you can rob up till house[i]
Time: O(N) => 1 iteration
Space: O(N) => dp array
'''
dp = [0] * len(nums)
dp[0] = nums[0]
dp[1] = max(nums[1], nums[0])
for i in range(2, len(nums)):
dp[i] = max(dp[i - 1], nums[i] + dp[i - 2])
return dp[len(nums) - 1]
def top_down():
'''
Top-Down Recursion + Memoization
Time: O(N) => at most N recursive calls due to caching
Space: O(N) => max size of cache
'''
cache = {0: nums[0], 1: max(nums[1], nums[0])}
def dp(i):
if i in cache:
return cache[i]
cache[i] = max(dp(i - 1), dp(i - 2) + nums[i])
return cache[i]
return dp(len(nums) - 1)
def constant_space_bottom_up():
'''
Bottom-up approach with variables
Time: O(N) => 1 iteration
Space: O(1) => only using two variables
'''
rob1, rob2 = 0, 0
for num in nums:
rob1, rob2 = rob2, max(rob1 + num, rob2)
return rob2
if len(nums) < 2:
return nums[0]
return constant_space_bottom_up() | house-robber | Python | DP | Top-Down | Bottom-Up | 3 Approaches | seangohck | 0 | 8 | house robber | 198 | 0.488 | Medium | 3,206 |
https://leetcode.com/problems/house-robber/discuss/2706053/Python-recursion-DP-beats-97 | class Solution:
def rob(self, arr: List[int]) -> int:
d = [-1] * len(arr)
def dp(cur):
if d[cur] != -1:
return d[cur]
if cur >= len(arr) - 2:
d[cur] = arr[cur]
elif cur < len(arr) - 3:
d[cur] = arr[cur] + max(dp(cur + 2), dp(cur + 3))
elif cur < len(arr) - 2:
d[cur] = arr[cur] + dp(cur + 2)
return d[cur]
for i in range(len(arr)):
dp(i)
return max(d) | house-robber | Python recursion DP beats 97% | JSTM2022 | 0 | 3 | house robber | 198 | 0.488 | Medium | 3,207 |
https://leetcode.com/problems/house-robber/discuss/2694612/Binary-recursion-on-Python | class Solution:
def rob(self, nums: List[int]) -> int:
n = len(nums)
if n == 0:
return 0
if n <= 2:
return max(nums)
if n == 3:
return max(nums[0] + nums[2], nums[1])
middle = n // 2
left_with_middle = self.rob(nums[:middle - 1])
right_with_middle = self.rob(nums[middle + 2:])
left_without_middle = self.rob(nums[:middle])
right_without_middle = self.rob(nums[middle + 1:])
return max(nums[middle] + left_with_middle + right_with_middle, left_without_middle + right_without_middle) | house-robber | Binary recursion on Python | vadim_vadim | 0 | 5 | house robber | 198 | 0.488 | Medium | 3,208 |
https://leetcode.com/problems/house-robber/discuss/2675550/Python-oror-DP-solution | class Solution:
def rob(self, nums: List[int]) -> int:
dp= [0] * len(nums)
if len(nums) == 1:
return nums[0]
for i in range(len(nums)):
dp[i] = max(dp[i-2]+nums[i],dp[i-1])
return max(dp) | house-robber | Python || DP solution | sinjan_singh | 0 | 8 | house robber | 198 | 0.488 | Medium | 3,209 |
https://leetcode.com/problems/binary-tree-right-side-view/discuss/2266055/C%2B%2B-oror-PYTHON-oror-EXPLAINED-oror | class Solution:
def rightSideView(self, root: Optional[TreeNode]) -> List[int]:
def solve(root, lvl):
if root:
if len(res)==lvl:
res.append(root.val)
solve(root.right, lvl + 1)
solve(root.left, lvl + 1)
return
res = []
solve(root,0)
return res | binary-tree-right-side-view | ✔️ C++ || PYTHON || EXPLAINED || ; ] | karan_8082 | 80 | 4,400 | binary tree right side view | 199 | 0.612 | Medium | 3,210 |
https://leetcode.com/problems/binary-tree-right-side-view/discuss/2265611/Python3-oror-dfs-recursion-10-lines-oror-TM%3A-98-70 | class Solution:
# The plan here is to dfs the tree, right-first
# (opposite of the usual left-first method), and
# keeping track of the tree levels as we proceed. The
# first node we visit on each level is the right-side view
# node. We know it's the first because the level will be
# one greater than the length of the current answer list.
def rightSideView(self, root: TreeNode) -> list[int]:
ans =[]
def dfs(node =root,level=1):
if not node: return
if len(ans) < level:
ans.append(node.val)
dfs(node.right,level+1) # <--- right first
dfs(node.left ,level+1) # <--- then left
return
dfs()
return ans | binary-tree-right-side-view | Python3 || dfs, recursion, 10 lines || T/M: 98%/ 70% | warrenruud | 7 | 563 | binary tree right side view | 199 | 0.612 | Medium | 3,211 |
https://leetcode.com/problems/binary-tree-right-side-view/discuss/327960/Python-solution-with-no-additional-space-and-96.61-faster | class Solution:
def rightSideView(self, root: TreeNode) -> List[int]:
res, max_level = [], -1
def traverse_tree(node, level):
nonlocal res, max_level
if not node:
return
if max_level < level:
res.append(node.val)
max_level = level
traverse_tree(node.right, level + 1)
traverse_tree(node.left, level + 1)
traverse_tree(root, 0)
return res | binary-tree-right-side-view | Python solution with no additional space and 96.61% faster | cyrilbeschi | 5 | 400 | binary tree right side view | 199 | 0.612 | Medium | 3,212 |
https://leetcode.com/problems/binary-tree-right-side-view/discuss/2680849/python-3-simple-BFS-solution | class Solution:
def rightSideView(self, root: Optional[TreeNode]) -> List[int]:
ans = []
if not root: return ans
q = [root]
while q:
lv = []
ans.append(q[-1].val)
for node in q:
if node.left: lv.append(node.left)
if node.right: lv.append(node.right)
q = lv
return ans | binary-tree-right-side-view | python 3 simple BFS solution | yfwong | 3 | 318 | binary tree right side view | 199 | 0.612 | Medium | 3,213 |
https://leetcode.com/problems/binary-tree-right-side-view/discuss/2094856/Python3-O(N)-Time-Easy-to-Understand-Solution-with-Comments | class Solution:
def rightSideView(self, root: Optional[TreeNode]) -> List[int]:
res = []
if not root: return res
q = collections.deque()
q.append(root)
while q:
res.append(q[-1].val) # the top element of q is the right-most
n = len(q) # popping all elements of a level at a time
for i in range(n): # first n nodes of q are nodes of current level
node = q.popleft()
if node.left: q.append(node.left)
if node.right: q.append(node.right)
return res
# Instead of using array as a queue we should use collections.deque()
# as pop() 0'th element from deque is of O(1) time.
# Time: O(N)
# Space: O(N) | binary-tree-right-side-view | [Python3] O(N) Time Easy to Understand Solution with Comments | samirpaul1 | 3 | 122 | binary tree right side view | 199 | 0.612 | Medium | 3,214 |
https://leetcode.com/problems/binary-tree-right-side-view/discuss/1052999/Python.-Cool-and-easy-solution.-O(n). | class Solution:
def rightSideView(self, root: TreeNode) -> List[int]:
Heights = {}
def sol(root: TreeNode, height: int):
if not root:
return
sol( root.right, height + 1)
if height not in Heights:
Heights[height] = root.val
sol( root.left, height + 1)
sol(root, 0)
return [Heights[index] for index in range(len(Heights.keys()))] | binary-tree-right-side-view | Python. Cool & easy solution. O(n). | m-d-f | 3 | 185 | binary tree right side view | 199 | 0.612 | Medium | 3,215 |
https://leetcode.com/problems/binary-tree-right-side-view/discuss/454028/Python-3-Four-liner-Memory-usage-less-than-100 | class Solution:
def rightSideView(self, root: TreeNode) -> List[int]:
levels = [[root]]
while any(levels[-1]):
levels.append([x for node in levels[-1] for x in [node.left, node.right] if x])
return [level[-1].val for level in levels[:-1]] | binary-tree-right-side-view | Python 3 - Four liner - Memory usage less than 100% | mmbhatk | 3 | 454 | binary tree right side view | 199 | 0.612 | Medium | 3,216 |
https://leetcode.com/problems/binary-tree-right-side-view/discuss/1123139/Python-BFS-100-Space-95-Time | class Solution:
def rightSideView(self, root: TreeNode) -> List[int]:
if not root:
return
ans = []
q = [root]
subq = []
while q:
element = q.pop(0)
if element.left:
subq.append(element.left)
if element.right:
subq.append(element.right)
if not q:
ans.append(element.val)
q = subq
subq = []
return ans | binary-tree-right-side-view | Python BFS 100% Space, 95% Time | rooky1905 | 2 | 203 | binary tree right side view | 199 | 0.612 | Medium | 3,217 |
https://leetcode.com/problems/binary-tree-right-side-view/discuss/2266545/python3-or-easy-or-explained-or-dictionary-approach | class Solution:
def rightSideView(self, root: Optional[TreeNode]) -> List[int]:
if not root:
return [] # if root is None
self.d = {} # used to store right most element of each level
self.trav(root, 0) # function calling
ans = [self.d[i] for i in range(max(self.d)+1)] # preparing the answer in proper order
return ans # return the answer
def trav(self, root, l):
if root:
self.d[l]=root.val # updating the value with right most element.
self.trav(root.left, l+1) # left traversal
self.trav(root.right, l+1) # right traversal | binary-tree-right-side-view | python3 | easy | explained | dictionary approach | H-R-S | 1 | 35 | binary tree right side view | 199 | 0.612 | Medium | 3,218 |
https://leetcode.com/problems/binary-tree-right-side-view/discuss/2265795/C%2B%2B-and-Python3-Easy-Solution-using-level-order-traversal | class Solution:
def rightSideView(self, root: Optional[TreeNode]) -> List[int]:
ans = list()
if not root: return []
q = [root]
while q:
for i in range(len(q)):
node = q.pop(0)
if node.left: q.append(node.left)
if node.right: q.append(node.right)
else:
ans.append(node.val)
return ans | binary-tree-right-side-view | C++ & Python3 Easy Solution using level order traversal | Akash3502 | 1 | 53 | binary tree right side view | 199 | 0.612 | Medium | 3,219 |
https://leetcode.com/problems/binary-tree-right-side-view/discuss/2265779/Python3-solution-using-preorder-traversal | class Solution:
def rightSideView(self, root: TreeNode) -> List[int]:
result = []
def get_result(root,level):
if not root:
return
if level==len(result):
result.append(root.val)
get_result(root.right,level+1)
get_result(root.left,level+1)
get_result(root,0)
return result | binary-tree-right-side-view | 📌 Python3 solution using preorder traversal | Dark_wolf_jss | 1 | 5 | binary tree right side view | 199 | 0.612 | Medium | 3,220 |
https://leetcode.com/problems/binary-tree-right-side-view/discuss/2265581/Python-BFS-solution | class Solution:
def rightSideView(self, root: Optional[TreeNode]) -> List[int]:
if root is None:
return None
queue = deque()
queue.append(root)
res = []
while queue:
temp = []
for _ in range(len(queue)):
node = queue.popleft()
temp.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
res.append(temp)
ans = []
for lst in res:
ans.append(lst[-1])
return ans | binary-tree-right-side-view | Python BFS solution | PythonicLava | 1 | 156 | binary tree right side view | 199 | 0.612 | Medium | 3,221 |
https://leetcode.com/problems/binary-tree-right-side-view/discuss/1597806/Python-space-complexity-O(n)-time-complexity-O(n) | class Solution:
def rightSideView(self, root: Optional[TreeNode]) -> List[int]:
res = {}
if not root: return res
def dfs(node,level):
if level not in res:
res[level] = node.val
if node.right:
dfs(node.right,level+1)
if node.left:
dfs(node.left,level+1)
dfs(root,0)
return res.values() | binary-tree-right-side-view | Python, space complexity O(n), time complexity O(n) | sineman | 1 | 139 | binary tree right side view | 199 | 0.612 | Medium | 3,222 |
https://leetcode.com/problems/binary-tree-right-side-view/discuss/1473833/Python-Clean-BFS-and-DFS | class Solution:
def rightSideView(self, root: Optional[TreeNode]) -> List[int]:
queue, view = deque([(root, 0)]), []
while queue:
node, level = queue.popleft()
if not node:
continue
if level >= len(view):
view.append(node.val)
queue.append((node.right, level+1))
queue.append((node.left, level+1))
return view | binary-tree-right-side-view | [Python] Clean BFS & DFS | soma28 | 1 | 148 | binary tree right side view | 199 | 0.612 | Medium | 3,223 |
https://leetcode.com/problems/binary-tree-right-side-view/discuss/1473833/Python-Clean-BFS-and-DFS | class Solution:
def rightSideView(self, root: Optional[TreeNode]) -> List[int]:
queue, view = deque([(root, 0)]), []
while queue:
node, level = queue.pop()
if not node:
continue
if level >= len(view):
view.append(node.val)
queue.append((node.left, level+1))
queue.append((node.right, level+1))
return view | binary-tree-right-side-view | [Python] Clean BFS & DFS | soma28 | 1 | 148 | binary tree right side view | 199 | 0.612 | Medium | 3,224 |
https://leetcode.com/problems/binary-tree-right-side-view/discuss/1414651/Row-by-row-89-speed | class Solution:
def rightSideView(self, root: Optional[TreeNode]) -> List[int]:
if not root:
return []
row = [root]
values = []
while row:
values.append(row[-1].val)
new_row = []
for node in row:
if node.left:
new_row.append(node.left)
if node.right:
new_row.append(node.right)
row = new_row
return values | binary-tree-right-side-view | Row by row, 89% speed | EvgenySH | 1 | 100 | binary tree right side view | 199 | 0.612 | Medium | 3,225 |
https://leetcode.com/problems/binary-tree-right-side-view/discuss/863385/Python3-Array-Filling-and-BFS-O(n)-Space-and-Time | class Solution:
# Array filling - O(n) space and time
def helper(self, node: TreeNode, height: int, res: List[int]):
if not node:
return
res[height] = node.val
self.helper(node.left, height + 1, res)
self.helper(node.right, height + 1, res)
def recursive_array_filling(self, root):
def get_depth(root):
if not root: return -1
return max(get_depth(root.right), get_depth(root.left)) + 1
height = get_depth(root)
res = [0] * (height + 1)
self.helper(root, 0, res)
return res
# BFS Level order - O(n) space and time
def bfs(self, root):
if not root: return []
queue = deque([root])
res = []
while queue:
res.append(queue[-1].val)
for _ in range(len(queue)):
cur = queue.popleft()
if cur.left:
queue.append(cur.left)
if cur.right:
queue.append(cur.right)
return res
def rightSideView(self, root: TreeNode) -> List[int]:
# return self.recursive_array_filling(root)
return self.bfs(root) | binary-tree-right-side-view | [Python3] Array Filling and BFS - O(n) Space & Time | nachiketsd | 1 | 106 | binary tree right side view | 199 | 0.612 | Medium | 3,226 |
https://leetcode.com/problems/binary-tree-right-side-view/discuss/2844165/python3-oror-Easy-way | class Solution:
def rightSideView(self, root: Optional[TreeNode]) -> List[int]:
res =[]
def risidview(root, level):
if not root:
return res
if len(res) < level:
res.append(root.val)
l = root.left
r = root.right
risidview(r, level+1)
risidview(l, level+1)
risidview( root,1)
return res | binary-tree-right-side-view | python3 || Easy way | dsai | 0 | 1 | binary tree right side view | 199 | 0.612 | Medium | 3,227 |
https://leetcode.com/problems/binary-tree-right-side-view/discuss/2775267/Python3-or-Simple-Explanation-or-Beats-96.20-or-32-ms-or-Recursion-or-DFS-or-O(n) | class Solution:
def rightSideView(self, root: Optional[TreeNode]) -> List[int]:
def recursive(node: TreeNode, depth: Optional[int] = 0) -> None:
if len(right_side_values) > depth:
right_side_values[depth] = node.val
else:
right_side_values.append(node.val)
depth += 1
if node.left: recursive(node.left, depth)
if node.right: recursive(node.right, depth)
right_side_values = []
if root: recursive(root)
return right_side_values | binary-tree-right-side-view | Python3 | Simple Explanation | Beats 96.20% | 32 ms | Recursion | DFS | O(n) | thomwebb | 0 | 2 | binary tree right side view | 199 | 0.612 | Medium | 3,228 |
https://leetcode.com/problems/binary-tree-right-side-view/discuss/2726411/Python3-simple-and-fast-Sol. | class Solution:
def rightSideView(self, root: Optional[TreeNode]) -> List[int]:
if root is None:
return []
q=deque([root])
ans=[]
while q:
l=len(q)
ans.append(q[-1].val)
for i in range(l):
node=q.popleft()
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
return ans | binary-tree-right-side-view | Python3 simple and fast Sol. | pranjalmishra334 | 0 | 4 | binary tree right side view | 199 | 0.612 | Medium | 3,229 |
https://leetcode.com/problems/binary-tree-right-side-view/discuss/2483923/BFS-Python-solution-98-faster.-Use-a-level-flag-to-store-nodule's-depth | class Solution:
def rightSideView(self, root: Optional[TreeNode]) -> List[int]:
if root is None:
return None
level = 0
queue = [[root,level]]
output = []
cur_level = 0
while len(queue)>0:
node,level = queue.pop(0)
cur_level = level
if len(queue)==0:
output.append(node.val)
elif queue[0][1] != cur_level:
output.append(node.val)
else:
pass
if node.left is not None:
queue.append([node.left, cur_level+1])
if node.right is not None:
queue.append([node.right, cur_level+1])
return output | binary-tree-right-side-view | BFS Python solution 98% faster. Use a level flag to store nodule's depth | Arana | 0 | 38 | binary tree right side view | 199 | 0.612 | Medium | 3,230 |
https://leetcode.com/problems/binary-tree-right-side-view/discuss/2407531/Using-level-order-traversal-Runtime%3A-34-ms-faster-than-92.88-of-Python3 | class Solution:
def rightSideView(self, root: Optional[TreeNode]) -> List[int]:
if not root:
return None
queue = [root]
res = []
next_level = []
while queue:
node = queue.pop(0)
if node.left:
next_level.append(node.left)
if node.right:
next_level.append(node.right)
if not queue:
res.append(node.val)
queue = next_level
next_level = []
return res | binary-tree-right-side-view | Using level order traversal - Runtime: 34 ms, faster than 92.88% of Python3 | krithika117 | 0 | 30 | binary tree right side view | 199 | 0.612 | Medium | 3,231 |
https://leetcode.com/problems/binary-tree-right-side-view/discuss/2283631/Fast-and-extremely-simple-solution | class Solution:
def rightSideView(self, root: Optional[TreeNode]) -> List[int]:
def recur(root,depth):
nonlocal valueDepth
if not root:
return None
if depth>=valueDepth:
res.append(root.val)
valueDepth+=1
recur(root.right,depth+1)
recur(root.left,depth+1)
res=[]
valueDepth=0
recur(root,0)
return res | binary-tree-right-side-view | Fast and extremely simple solution | HaoChenNus | 0 | 23 | binary tree right side view | 199 | 0.612 | Medium | 3,232 |
https://leetcode.com/problems/binary-tree-right-side-view/discuss/2282881/Python-Easy-to-understand-DFS-solution | class Solution:
def rightSideView(self, root: Optional[TreeNode]) -> List[int]:
if not root:
return []
level_value_map = {}
def helper(node, level):
if not node:
return
if level not in level_value_map:
level_value_map[level] = node.val
helper(node.right, level+1)
helper(node.left, level+1)
helper(root, 1)
return level_value_map.values() | binary-tree-right-side-view | [Python] Easy to understand DFS solution | julenn | 0 | 21 | binary tree right side view | 199 | 0.612 | Medium | 3,233 |
https://leetcode.com/problems/binary-tree-right-side-view/discuss/2270119/Simple-solution | class Solution:
def rightSideView(self, root: TreeNode):
rightside = {}
self.seeTree(root, rightside, 1)
numbers = [value for value in rightside.values()]
return numbers
def seeTree(self, root: TreeNode, rightside: dict, nodo: int):
if root == None:
return
if root.val != None:
rightside[nodo] = root.val
self.seeTree(root.left, rightside, nodo + 1)
self.seeTree(root.right, rightside, nodo + 1)
return | binary-tree-right-side-view | Simple solution | jivanbasurtom | 0 | 3 | binary tree right side view | 199 | 0.612 | Medium | 3,234 |
https://leetcode.com/problems/number-of-islands/discuss/863366/Python-3-or-DFS-BFS-Union-Find-All-3-methods-or-Explanation | class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
if not grid: return 0
m, n = len(grid), len(grid[0])
ans = 0
def dfs(i, j):
grid[i][j] = '2'
for di, dj in (0, 1), (0, -1), (1, 0), (-1, 0):
ii, jj = i+di, j+dj
if 0 <= ii < m and 0 <= jj < n and grid[ii][jj] == '1':
dfs(ii, jj)
for i in range(m):
for j in range(n):
if grid[i][j] == '1':
dfs(i, j)
ans += 1
return ans | number-of-islands | Python 3 | DFS, BFS, Union Find, All 3 methods | Explanation | idontknoooo | 50 | 5,200 | number of islands | 200 | 0.564 | Medium | 3,235 |
https://leetcode.com/problems/number-of-islands/discuss/863366/Python-3-or-DFS-BFS-Union-Find-All-3-methods-or-Explanation | class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
if not grid: return 0
m, n = len(grid), len(grid[0])
ans = 0
for i in range(m):
for j in range(n):
if grid[i][j] == '1':
q = collections.deque([(i, j)])
grid[i][j] = '2'
while q:
x, y = q.popleft()
for dx, dy in (0, 1), (0, -1), (1, 0), (-1, 0):
xx, yy = x+dx, y+dy
if 0 <= xx < m and 0 <= yy < n and grid[xx][yy] == '1':
q.append((xx, yy))
grid[xx][yy] = '2'
ans += 1
return ans | number-of-islands | Python 3 | DFS, BFS, Union Find, All 3 methods | Explanation | idontknoooo | 50 | 5,200 | number of islands | 200 | 0.564 | Medium | 3,236 |
https://leetcode.com/problems/number-of-islands/discuss/863366/Python-3-or-DFS-BFS-Union-Find-All-3-methods-or-Explanation | class UF:
def __init__(self, n):
self.p = [i for i in range(n)]
self.n = n
self.size = n
def union(self, i, j):
pi, pj = self.find(i), self.find(j)
if pi != pj:
self.size -= 1
self.p[pj] = pi
def find(self, i):
if i != self.p[i]:
self.p[i] = self.find(self.p[i])
return self.p[i]
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
if not grid:
return 0
m, n = len(grid), len(grid[0])
d = dict()
idx = 0
for i in range(m):
for j in range(n):
if grid[i][j] == '1':
d[i, j] = idx
idx += 1
uf = UF(idx)
for i in range(m):
for j in range(n):
if grid[i][j] == '1':
if i > 0 and grid[i-1][j] == '1':
uf.union(d[i-1, j], d[i, j])
if j > 0 and grid[i][j-1] == '1':
uf.union(d[i, j-1], d[i, j])
return uf.size | number-of-islands | Python 3 | DFS, BFS, Union Find, All 3 methods | Explanation | idontknoooo | 50 | 5,200 | number of islands | 200 | 0.564 | Medium | 3,237 |
https://leetcode.com/problems/number-of-islands/discuss/479692/Intuitive-Disjoint-Set-Union-Find-in-JavaPython3 | class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
if grid == None or len(grid) == 0: return 0
r, c = len(grid), len(grid[0])
dsu = DSU(r * c)
# union an island with its adjacent islands
for i in range(r):
for j in range(c):
if int(grid[i][j]) == 1:
# add this island first
dsu.numIsl += 1
# union 4 adjacent islands if exist
if i - 1 >= 0 and int(grid[i - 1][j]) == 1:
dsu.union((i - 1) * c + j, i * c + j)
if i + 1 < r and int(grid[i + 1][j]) == 1:
dsu.union(i * c + j, (i + 1) * c + j)
if j - 1 >= 0 and int(grid[i][j - 1]) == 1:
dsu.union(i * c + (j - 1), i * c + j)
if j + 1 < c and int(grid[i][j + 1]) == 1:
dsu.union(i * c + j, i * c + (j + 1))
return dsu.numIsl
class DSU:
def __init__(self, num):
self.numIsl = 0
self.par = list(range(num))
self.rnk = [0] * num
def find(self, x):
if self.par[x] != x:
self.par[x] = self.find(self.par[x])
return self.par[x]
def union(self, x, y):
xr, yr = self.find(x), self.find(y)
if xr == yr:
return
elif self.rnk[xr] < self.rnk[yr]:
self.par[xr] = yr
elif self.rnk[xr] > self.rnk[yr]:
self.par[yr] = xr
else:
self.par[yr] = xr
self.rnk[xr] += 1
self.numIsl -= 1 | number-of-islands | Intuitive Disjoint Set Union Find in [Java/Python3] | BryanBoCao | 7 | 1,200 | number of islands | 200 | 0.564 | Medium | 3,238 |
https://leetcode.com/problems/number-of-islands/discuss/1446732/Flood-Fill-approach.-(733). | class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
count = 0
R, C = len(grid), len(grid[0])
def dfs(r, c):
grid[r][c] = '0'
if r-1 >= 0 and grid[r-1][c] == '1':
dfs(r-1, c)
if r+1 < R and grid[r+1][c] == '1':
dfs(r+1, c)
if c+1 < C and grid[r][c+1] == '1':
dfs(r, c+1)
if c-1 >= 0 and grid[r][c-1] == '1':
dfs(r, c-1)
for row in range(0, len(grid)):
for col in range(0, len(grid[0])):
if grid[row][col] == '1':
count += 1
dfs(row, col)
return count
# first we find the 1 valued element using two for loops and then we update their values to 0 so
# that when we backtrack (like r-1) then it will not keep on running and when values of all of it's connected
# elements become 0, we come out of the dfs(). This keeps on happening as the 2 for loops continue finding the '1' valued element. | number-of-islands | Flood Fill approach. (733). | AmrinderKaur1 | 5 | 273 | number of islands | 200 | 0.564 | Medium | 3,239 |
https://leetcode.com/problems/number-of-islands/discuss/673201/Python3-union-find-(better-than-83) | class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
if len(grid) == 0:
return 0
uf = {}
N = len(grid)
M = len(grid[0])
for i in range(N):
for j in range(M):
if grid[i][j] == '1':
uf[(i,j)] = (i,j)
for i in range(N):
for j in range(M):
if grid[i][j] == '0':
continue
if i+1<N and grid[i+1][j] == '1':
union(uf, (i,j), (i+1,j))
if j+1<M and grid[i][j+1] == '1':
union(uf, (i,j), (i,j+1))
count = 0
for k, v in uf.items():
if v == k:
count += 1
return count
def union(uf, a, b) -> None:
uf[root(uf, b)] = root(uf, a)
def root(uf, x) -> str:
r = x
while r != uf[r]:
r = uf[r]
return r | number-of-islands | Python3 union find (better than 83%) | sird0d0 | 4 | 294 | number of islands | 200 | 0.564 | Medium | 3,240 |
https://leetcode.com/problems/number-of-islands/discuss/2336379/Iterative-solution-using-Stack-Python | class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
# m = len(grid)
# n = len(grid[0])
# def mark(r, c):
# if r < 0 or c < 0 or r > m-1 or c > n-1 or grid[r][c] != '1' :
# return
# grid[r][c] = '2'
# mark(r + 1, c)
# mark(r - 1, c)
# mark(r, c + 1)
# mark(r, c - 1)
# res = 0
# for i in range(m):
# for j in range(n):
# if grid[i][j] == '1':
# res += 1
# mark(i, j)
# return res
m = len(grid)
n = len(grid[0])
def mark(r, c):
stack = [(r, c)]
while stack:
r, c = stack.pop()
if r + 1 < m and grid[r + 1][c] == '1' and (r + 1, c) not in stack:
stack.append((r + 1, c))
if r - 1 >= 0 and grid[r - 1][c] == '1' and (r - 1, c) not in stack:
stack.append((r - 1, c))
if c + 1 < n and grid[r][c + 1] == '1' and (r, c + 1) not in stack:
stack.append((r, c + 1))
if c - 1 >= 0 and grid[r][c - 1] == '1' and (r, c - 1) not in stack:
stack.append((r, c - 1))
grid[r][c] = 2
res = 0
for i in range(m):
for j in range(n):
if grid[i][j] == '1':
res += 1
mark(i, j)
return res | number-of-islands | Iterative solution using Stack Python | glebbs | 3 | 270 | number of islands | 200 | 0.564 | Medium | 3,241 |
https://leetcode.com/problems/number-of-islands/discuss/2160946/Python3-Very-Concise-AC-Solution-Both-DFS-BFS | class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
row = len(grid); col = len(grid[0])
res = 0
def dfs(i, j): # make surrounded '1' to '0'
if ( not 0 <= i < row) or (not 0 <= j < col) or (grid[i][j] == '0'): return
grid[i][j] = '0'
dfs(i-1, j)
dfs(i+1, j)
dfs(i, j-1)
dfs(i, j+1)
for i in range(row):
for j in range(col):
if grid[i][j] == '1':
res += 1
dfs(i, j)
return res | number-of-islands | [Python3] Very Concise AC Solution Both DFS, BFS | samirpaul1 | 3 | 287 | number of islands | 200 | 0.564 | Medium | 3,242 |
https://leetcode.com/problems/number-of-islands/discuss/2160946/Python3-Very-Concise-AC-Solution-Both-DFS-BFS | class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
row = len(grid); col = len(grid[0])
res = 0
def bfs(i, j):
q = collections.deque()
q.append((i, j))
while q:
r, c = q.popleft()
if ( not 0 <= r < row) or (not 0 <= c < col) or (grid[r][c] == '0'): continue
grid[r][c] = '0'
q.append((r-1, c))
q.append((r+1, c))
q.append((r, c-1))
q.append((r, c+1))
for i in range(row):
for j in range(col):
if grid[i][j] == '1':
res += 1
bfs(i, j)
return res | number-of-islands | [Python3] Very Concise AC Solution Both DFS, BFS | samirpaul1 | 3 | 287 | number of islands | 200 | 0.564 | Medium | 3,243 |
https://leetcode.com/problems/number-of-islands/discuss/1658537/Python-Simple-recursive-DFS-explained | class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
res = 0
row = len(grid)
col = len(grid[0])
visited = [[0 for x in range(col)] for y in range(row)]
def perm(i, j):
# check if we're on a land because if yes, we need
# to further visit the neighbors so as to "visit"
# the whole island, early return if it's not a land
if i < 0 or i >= row or j < 0 or j >= col or grid[i][j] == "0":
return
# mark the current cell as visisted
# if not visited, otherwise, just return
if visited[i][j]:
return
visited[i][j] = 1
# returning just for the sake of it, you can
# simply invoke the functions here since we're
# only concerned with visiting an island and keeping
# track of all the lands ("1")s for subsequent runs
return perm(i-1, j) or perm(i+1, j) or perm(i, j-1) or perm(i, j+1)
for x in range(row):
for y in range(col):
# process every cell which has a 1 recursively
# and since we're also marking the visited cells
# we can safely ignore them here
if grid[x][y] == "1" and not visited[x][y]:
perm(x, y)
res += 1
return res | number-of-islands | [Python] Simple recursive DFS explained | buccatini | 3 | 252 | number of islands | 200 | 0.564 | Medium | 3,244 |
https://leetcode.com/problems/number-of-islands/discuss/2737580/Number-of-Islands-using-BFS-faster-then-96 | class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
from collections import deque
n=len(grid)
m=len(grid[0])
visited=[[0 for j in range(m)]for i in range(n)]
c=0
l=[[-1,0],[1,0],[0,-1],[0,1]]
for i in range(n):
for j in range(m):
if visited[i][j]==0 and grid[i][j]=='1':
q=deque()
q.append((i,j))
c+=1
visited[i][j]=1
while q:
row,col=q.popleft()
for x,y in l:
nrow,ncol=row+x,col+y
if 0<=nrow<n and 0<=ncol<m and grid[nrow][ncol]=='1' and visited[nrow][ncol]==0:
visited[nrow][ncol]=1
q.append((nrow,ncol))
return c | number-of-islands | Number of Islands using BFS faster then 96% | ravinuthalavamsikrishna | 2 | 388 | number of islands | 200 | 0.564 | Medium | 3,245 |
https://leetcode.com/problems/number-of-islands/discuss/2498797/Python-Elegant-and-Short-or-99.90-faster | class Solution:
"""
Time: O(n*m)
Memory: O(n*m)
"""
LAND = '1'
WATER = '0'
def numIslands(self, grid: List[List[str]]) -> int:
n, m = len(grid), len(grid[0])
islands = 0
for row in range(n):
for col in range(m):
if grid[row][col] == self.LAND:
self._visit(row, col, grid)
islands += 1
return islands
@classmethod
def _visit(cls, row: int, col: int, grid: List[List[str]]):
n, m = len(grid), len(grid[0])
grid[row][col] = cls.WATER
if row > 0 and grid[row - 1][col] == cls.LAND:
cls._visit(row - 1, col, grid)
if row + 1 < n and grid[row + 1][col] == cls.LAND:
cls._visit(row + 1, col, grid)
if col > 0 and grid[row][col - 1] == cls.LAND:
cls._visit(row, col - 1, grid)
if col + 1< m and grid[row][col + 1] == cls.LAND:
cls._visit(row, col + 1, grid) | number-of-islands | Python Elegant & Short | 99.90% faster | Kyrylo-Ktl | 2 | 218 | number of islands | 200 | 0.564 | Medium | 3,246 |
https://leetcode.com/problems/number-of-islands/discuss/1292751/Be-careful-and-avoid-this-mistake! | class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
rows, cols = len(grid), len(grid[0]) if grid else 0
islands = 0
dirs = [(-1, 0), (0, 1), (1, 0), (0, -1)]
for row in range(rows):
for col in range(cols):
cell = grid[row][col]
if cell == '1':
islands += 1
self.bfs(grid, row, col, dirs, rows, cols)
return islands
def bfs(self, grid, x, y, dirs, rows, cols):
q = deque([(x, y)])
while q:
r, c = q.popleft()
grid[r][c] = '0'
for dx, dy in dirs:
if self.valid(r+dx, c+dy, rows, cols) and grid[r+dx][c+dy] == '1':
q.append((r+dx, c+dy))
def valid(self, r, c, rows, cols):
return r >= 0 and r < rows and c >= 0 and c < cols | number-of-islands | Be careful and avoid this mistake! | v21 | 2 | 260 | number of islands | 200 | 0.564 | Medium | 3,247 |
https://leetcode.com/problems/number-of-islands/discuss/1258779/Python-simple-13-lines-solution-easy-to-understand | class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
c=0
for i in range(len(grid)):
for j in range(len(grid[0])):
if(grid[i][j]=='1'):
c=c+1
grid=Solution.cut(grid,i,j)
return c
def cut(grid,i,j):
grid[i][j]='0'
if(i+1<len(grid) and grid[i+1][j]=='1'):grid=Solution.cut(grid,i+1,j)
if(j+1<len(grid[0]) and grid[i][j+1]=='1'):grid=Solution.cut(grid,i,j+1)
if(i-1>-1 and grid[i-1][j]=='1'):grid=Solution.cut(grid,i-1,j)
if(j-1>-1 and grid[i][j-1]=='1'):grid=Solution.cut(grid,i,j-1)
return grid | number-of-islands | Python simple 13 lines solution easy to understand | Rajashekar_Booreddy | 2 | 749 | number of islands | 200 | 0.564 | Medium | 3,248 |
https://leetcode.com/problems/number-of-islands/discuss/583740/Python-sol-by-DFS-traversal.-w-Comment | class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
self.h = len(grid)
if self.h == 0:
# Quick response for empty grid
return 0
self.w = len( grid[0] )
if self.h * self.w == 1:
# Quick response for 1x1 grid
return 1 if grid[0][0] == '1' else 0
# gourp index for island
self.group_index = 0
def dfs( grid, y, x):
if (y < 0) or (x < 0) or (y >= self.h) or (x >= self.w) or (grid[y][x] != '1'):
return
# mark current position as visited with group index
grid[y][x] = self.group_index
# visit 4 neighbors in DFS
dfs( grid, y+1, x)
dfs( grid, y-1, x)
dfs( grid, y, x+1)
dfs( grid, y, x-1)
# -----------------------------------------
for y in range( self.h ):
for x in range( self.w ):
# check each position in DFS
if grid[y][x] == '1':
self.group_index -= 1
dfs( grid, y, x)
return abs( self.group_index ) | number-of-islands | Python sol by DFS traversal. [w/ Comment] | brianchiang_tw | 2 | 659 | number of islands | 200 | 0.564 | Medium | 3,249 |
https://leetcode.com/problems/number-of-islands/discuss/583740/Python-sol-by-DFS-traversal.-w-Comment | class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
is_land = lambda i,j : grid[i][j] == "1"
h, w = len(grid), len(grid[0])
class DisjointSet():
def __init__(self):
self.parent = { (i, j): (i, j) for i in range(h) for j in range(w) if is_land(i, j)}
self.size = { (i, j): 1 for i in range(h) for j in range(w) if is_land(i, j)}
self.count_of_set = len(self.parent)
def find(self, coordinate):
if self.parent[coordinate] != coordinate:
self.parent[coordinate] = self.find( self.parent[coordinate] )
return self.parent[coordinate]
def union(self, coord_a, coord_b):
parent_of_a = self.find(coord_a)
parent_of_b = self.find(coord_b)
if parent_of_a != parent_of_b:
if self.size[parent_of_a] > self.size[parent_of_b]:
self.parent[parent_of_b] = parent_of_a
self.size[parent_of_a] += self.size[parent_of_b]
else:
self.parent[parent_of_a] = parent_of_b
self.size[parent_of_b] += self.size[parent_of_a]
self.count_of_set -= 1
def count(self):
return self.count_of_set
# -----------------------------------------------
groups = DisjointSet()
for i in range(h):
for j in range(w):
if is_land( i, j ):
if (i > 0) and is_land(i-1, j):
# current grid and left neighbor are lands, combine together
groups.union( (i, j), (i-1, j) )
if (j > 0) and is_land(i, j-1):
# current grid and top neighbor are lands, combine together
groups.union( (i, j), (i, j-1) )
# number of islands = number of groups
number_of_islands = groups.count()
return number_of_islands | number-of-islands | Python sol by DFS traversal. [w/ Comment] | brianchiang_tw | 2 | 659 | number of islands | 200 | 0.564 | Medium | 3,250 |
https://leetcode.com/problems/number-of-islands/discuss/2500891/Python-or-C%2B%2B-%3A-DFS-with-recursion | class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
m, n = len(grid), len(grid[0])
ans, count = 0, 0
visited = [[0] * n for i in range(m)]
def search(i, j):
if grid[i][j] == '1' and not visited[i][j]:
visited[i][j] = 1
if i < m - 1:
search(i + 1, j)
if j < n - 1:
search(i, j + 1)
if i > 0:
search(i - 1, j)
if j > 0:
search(i, j - 1)
if not visited[i][j]:
visited[i][j] = 1
for i in range(m):
for j in range(n):
if grid[i][j] == '1' and not visited[i][j]:
count += 1
search(i, j)
# print(i, j, count)
return count | number-of-islands | Python | C++ : DFS with recursion | joshua_mur | 1 | 19 | number of islands | 200 | 0.564 | Medium | 3,251 |
https://leetcode.com/problems/number-of-islands/discuss/2498192/python3-or-explained-with-comment-or-easy-understanding | class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
n, m = len(grid), len(grid[0])
visited = [[False for _ in range(m)] for _ in range(n)]
num_island = 0
for i in range(n):
for j in range(m):
if grid[i][j] == '1' and not visited[i][j]: # if island
num_island += 1
self.visit_island(grid, n, m, i, j, visited) # visit entire island
return num_island
def visit_island(self, grid, n, m, i, j, visited): # visit island (bfs)
queue = [(i, j)]
visited[i][j] = True
while queue:
i, j = queue.pop(0)
for x, y in self.adj(grid, n, m, i, j):
if not visited[x][y]:
visited[x][y] = True
queue.append((x, y))
return
def adj(self, grid, n, m, i, j): # to find the adjacent land
lst = [(i-1, j), (i+1, j), (i, j-1), (i, j+1)]
adjlist = []
for x, y in lst:
if x >= 0 and x < n and y >= 0 and y < m and grid[x][y]=='1':
adjlist.append((x, y))
return adjlist | number-of-islands | python3 | explained with comment | easy-understanding | H-R-S | 1 | 27 | number of islands | 200 | 0.564 | Medium | 3,252 |
https://leetcode.com/problems/number-of-islands/discuss/2378109/python3-or-with-comments | class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
count = 0
m = len(grid)
n = len(grid[0])
# here marking all the islands as false visited
visited = [[False for i in range(n)] for j in range(m)]
# This method will mark the island cell as visited as well as call all the neighbor
def neighbor(g,v,i,j):
if g[i][j] == "0" or v[i][j] == True:
return
v[i][j] = True
if j-1 >= 0:
neighbor(g,v,i,j-1)
if j+1 < n:
neighbor(g,v,i,j+1)
if i-1 >= 0:
neighbor(g,v,i-1,j)
if i+1 < m:
neighbor(g,v,i+1,j)
# Now just loop on all the cell if visited then continue else send it to
for i in range(m):
for j in range(n):
if grid[i][j] == "1" and visited[i][j] == False:
neighbor(grid,visited,i,j)
count += 1
return count | number-of-islands | python3 | with comments | jayeshmaheshwari555 | 1 | 125 | number of islands | 200 | 0.564 | Medium | 3,253 |
https://leetcode.com/problems/number-of-islands/discuss/2268125/Python-DFS-Solution-(Faster-than-95) | class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
m=len(grid)
n=len(grid[0])
self.directions=[(0,1),(0,-1),(1,0),(-1,0)]
res=0
for i in range(m):
for j in range(n):
if grid[i][j]=="1":
self.dfs(i,j,grid,m,n)
res+=1
return res
def dfs(self,i,j,matrix,m,n):
# mark visited
matrix[i][j]="#"
for dir in self.directions:
x,y=i+dir[0],j+dir[1]
if x<0 or y<0 or x>=m or y>=n or matrix[x][y]!="1":
continue
self.dfs(x,y,matrix,m,n) | number-of-islands | Python DFS Solution (Faster than 95%) | shatheesh | 1 | 166 | number of islands | 200 | 0.564 | Medium | 3,254 |
https://leetcode.com/problems/number-of-islands/discuss/2266815/Python3-Solution-with-using-dfs | class Solution:
def dfs(self, grid, i, j):
if i < 0 or i > len(grid) - 1 or j < 0 or j > len(grid[i]) - 1 or grid[i][j] == '0':
return
grid[i][j] = '0'
self.dfs(grid, i - 1, j)
self.dfs(grid, i, j - 1)
self.dfs(grid, i + 1, j)
self.dfs(grid, i, j + 1)
def numIslands(self, grid: List[List[str]]) -> int:
res = 0
for i in range(len(grid)):
for j in range(len(grid[i])):
if grid[i][j] == '1':
self.dfs(grid, i, j)
res += 1
return res | number-of-islands | [Python3] Solution with using dfs | maosipov11 | 1 | 45 | number of islands | 200 | 0.564 | Medium | 3,255 |
https://leetcode.com/problems/number-of-islands/discuss/2265786/Python3-DFS-solution | class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
visited = {}
rowLength = len(grid)
columnLength = len(grid[0])
def dfs(i,j):
if(i<0 or i>=rowLength or j<0 or j>=columnLength or (i,j) in visited):
return
if(grid[i][j] != "1"):
return
visited[(i,j)] = True
for x,y in [[-1,0],[1,0],[0,-1],[0,1]]:
dfs(i+x,j+y)
result = 0
for i in range(rowLength):
for j in range(columnLength):
if(grid[i][j] == "1" and (i,j) not in visited):
dfs(i,j)
result+=1
return result | number-of-islands | 📌 Python3 DFS solution | Dark_wolf_jss | 1 | 30 | number of islands | 200 | 0.564 | Medium | 3,256 |
https://leetcode.com/problems/number-of-islands/discuss/2184036/Python-DFSBFS-with-full-working-explanation | class Solution:
def numIslands(self, grid: List[List[str]]) -> int: # Time: O(n*n) and Space: O(n)
if not grid: return 0
rows, cols = len(grid), len(grid[0])
visit = set()
islands = 0
def bfs(r, c): # using bfs to search for adjacent 1's in a breadth first or row manner
q = collections.deque()
visit.add((r, c))
q.append((r, c))
while q: # while some values exist in queue
row, col = q.popleft() # pop from the start in FIFO manner, current location(i, j). For DFS just make it pop from popleft
directions = [[1, 0], [-1, 0], [0, 1], [0, -1]] # down=[1, 0], up=[-1, 0], right=[0, 1] and left=[0, -1]
for dr, dc in directions:
r, c = row + dr, col + dc # from current location we will check every side
# and if the new index lies in the matrix, and is 1 and not visited yet then
if r in range(rows) and c in range(cols) and grid[r][c] == '1' and (r, c) not in visit:
q.append((r, c)) # add the location in queue and mark it as visited
visit.add((r, c))
for r in range(rows):
for c in range(cols):
if grid[r][c] == '1' and (r, c) not in visit: # if the tile is not visited and is 1 call bfs
bfs(r, c)
islands += 1 # we add one island because every connected islands will be marked visited in the bfs
return islands | number-of-islands | Python DFS/BFS with full working explanation | DanishKhanbx | 1 | 152 | number of islands | 200 | 0.564 | Medium | 3,257 |
https://leetcode.com/problems/number-of-islands/discuss/1903920/Passing-most-cases.-But-off-by-1-for-one-case-on-submission | class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
X = len(grid)
Y = len(grid[0])
count = 0
seen = set()
def search(x,y):
if f'{x}{y}' in seen:
return False
el = grid[x][y]
if el == "0":
return False
seen.add(f'{x}{y}')
if x-1 >= 0: search(x-1, y)
if x+1 < X: search(x+1, y)
if y-1 >= 0: search(x, y-1)
if y+1 < Y: search(x, y+1)
return True
for x in range(X):
for y in range(Y):
if search(x,y):
count += 1
return count | number-of-islands | Passing most cases. But off by 1 for one case on submission | yathi | 1 | 45 | number of islands | 200 | 0.564 | Medium | 3,258 |
https://leetcode.com/problems/number-of-islands/discuss/1862578/python-dfs-solution-super-simple | class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
numOfIslands = 0
self.grid = grid
for r in range(len(grid)):
for c in range(len(grid[r])):
if grid[r][c] == "1":
numOfIslands+=1
self.callDFS(r,c)
return numOfIslands
def callDFS(self,r,c):
if (r < 0 or r >= len(self.grid) or c < 0 or c >= len(self.grid[0]) or self.grid[r][c] == '0'):
return
self.grid[r][c] = '0'
self.callDFS(r-1, c) # up
self.callDFS(r+1, c) # down
self.callDFS(r, c-1) # left
self.callDFS(r, c+1) # right
return | number-of-islands | python dfs solution super simple | karanbhandari | 1 | 129 | number of islands | 200 | 0.564 | Medium | 3,259 |
https://leetcode.com/problems/number-of-islands/discuss/1851696/Python-DFS | class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
num_islands = 0
num_rows, num_cols = len(grid), len(grid[0])
neighbor_directions = [(0,1), (0,-1), (1,0), (-1,0)]
def dfs(i, j):
if grid[i][j] == "1":
grid[i][j] = "-1"
for neighbor in neighbor_directions:
row_change, col_change = neighbor[0], neighbor[1]
new_i, new_j = i + row_change, j + col_change
if new_i in range(0, num_rows) and new_j in range(0, num_cols) and grid[new_i][new_j] == "1":
dfs(new_i, new_j)
for i in range(num_rows):
for j in range(num_cols):
if grid[i][j] == "1":
dfs(i, j)
num_islands += 1
return num_islands | number-of-islands | Python DFS | doubleimpostor | 1 | 112 | number of islands | 200 | 0.564 | Medium | 3,260 |
https://leetcode.com/problems/number-of-islands/discuss/1755076/Python-Easy-and-clean-DFS-solution | class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
m, n = len(grid), len(grid[0])
def dfs(x, y):
for i, j in [(1,0),(-1,0),(0,1),(0,-1)]:
if 0 <= x+i < m and 0 <= y+j < n and grid[x+i][y+j] == "1":
grid[x+i][y+j] = "0"
dfs(x+i, y+j)
ans = 0
for i in range(m):
for j in range(n):
if grid[i][j] == "1":
ans += 1
dfs(i, j)
return ans | number-of-islands | [Python] Easy and clean DFS solution | nomofika | 1 | 296 | number of islands | 200 | 0.564 | Medium | 3,261 |
https://leetcode.com/problems/number-of-islands/discuss/1737834/Python-(DFS)-Easy-In-Place-Solution-%2B-Explanation-Beats-96 | class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
# Convert to grid of ints from grid of strings
grid = [list( map(int,i) ) for i in grid]
counter = 0
# 1 = not visited 0 = visited
def dfs(i,j):
grid[i][j] = 0
if i > 0 and grid[i-1][j] == 1:
dfs(i-1,j)
if i < len(grid) - 1 and grid[i+1][j] == 1:
dfs(i+1,j)
if j < len(grid[0]) - 1 and grid[i][j+1] == 1:
dfs(i,j+1)
if j > 0 and grid[i][j-1] == 1:
dfs(i,j-1)
# Checks for all seperate sets of one's then calls dfs to mark visited on the connected ones
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] == 1:
counter+=1
dfs(i,j)
return counter | number-of-islands | Python (DFS) Easy In-Place Solution + Explanation Beats 96% | Meerxn | 1 | 306 | number of islands | 200 | 0.564 | Medium | 3,262 |
https://leetcode.com/problems/number-of-islands/discuss/1684705/Python3-easy-to-understand-with-explanation | class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
m = len(grid)
n = len(grid[0])
res = 0
def count(i, j, res):
if i < 0 or j < 0 or i >= m or j >= n: # Neglect out-of-range case.
return
if grid[i][j] == '1': # If this cell is an "undiscovered land",
grid[i][j] = res # we color it with 'res'.
count(i-1, j, res) # After that, we check adjacent cells.
count(i+1, j, res)
count(i, j-1, res)
count(i, j+1, res)
for i in range(m):
for j in range(n):
if grid[i][j] == '1': # Whenever we meet a "undiscovered land", we first increment res by 1,
res += 1 # and then color the whole island with 'res'
count(i,j,res)
return res | number-of-islands | Python3 easy to understand with explanation | byroncharly3 | 1 | 182 | number of islands | 200 | 0.564 | Medium | 3,263 |
https://leetcode.com/problems/number-of-islands/discuss/1628042/Python-DFS-faster-than-98 | class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
res = 0
def find_island(i,j):
grid[i][j] = '0'
#search up:
if i-1 >= 0 and grid[i-1][j] == '1':
find_island(i-1,j)
# down
if i+1 <= len(grid)-1 and grid[i+1][j] == '1':
find_island(i+1, j)
# left
if j-1 >= 0 and grid[i][j-1] == '1':
find_island(i, j-1)
#right
if j+1 <= len(grid[0])-1 and grid[i][j+1] == '1':
find_island(i, j+1)
for i in range(len(grid)):
for j in range(len(grid[i])):
if grid[i][j]=='1':
find_island(i,j)
res+=1
return res
``` | number-of-islands | Python DFS faster than 98% | jcm497 | 1 | 407 | number of islands | 200 | 0.564 | Medium | 3,264 |
https://leetcode.com/problems/number-of-islands/discuss/1613343/DFS-Python-fastest-or-Latest | class Solution:
def dfs(self,graph,i,j):
if i<0 or j<0 or i>=len(graph) or j>=len(graph[0]):
return
if graph[i][j]=="0":
return
graph[i][j]="0"
self.dfs(graph,i-1,j)
self.dfs(graph,i+1,j)
self.dfs(graph,i,j-1)
self.dfs(graph,i,j+1)
def numIslands(self, graph: List[List[str]]) -> int:
count = 0
for i in range(len(graph)):
for j in range(len(graph[0])):
if graph[i][j]=="1":
count+=1
self.dfs(graph,i,j)
return count | number-of-islands | DFS Python fastest | Latest | Brillianttyagi | 1 | 295 | number of islands | 200 | 0.564 | Medium | 3,265 |
https://leetcode.com/problems/number-of-islands/discuss/1607189/python-dfs | class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
m, n = len(grid), len(grid[0])
def dfs(grid, r, c):
if r < 0 or c < 0 or r > m - 1 or c > n - 1 or grid[r][c] == '0':
return
grid[r][c] = '0'
dfs(grid, r - 1, c)
dfs(grid, r + 1, c)
dfs(grid, r, c - 1)
dfs(grid, r, c + 1)
res = 0
for i in range(m):
for j in range(n):
if grid[i][j] == '1':
res += 1
dfs(grid, i, j)
return res | number-of-islands | python dfs | alextoqc | 1 | 117 | number of islands | 200 | 0.564 | Medium | 3,266 |
https://leetcode.com/problems/number-of-islands/discuss/1579494/Better-then-97-iterative-python | class Solution:
def deleteIsland(self, grid, x, y):
island_field = [] # array of fields I want to delete
island_field.append((x,y)) # adding first one
grid[y][x] = '0'
while len(island_field) != 0:
curr = island_field[0] # getting first eleemnt to delete
x,y = curr
if x-1>=0 and grid[y][x-1] == '1': #adding only if x and y in range and field is '1'
island_field.append( (x - 1, y)) #adding to "to delete" array
grid[y][x-1] = '0' # bc I dont want to add same field twice or more
if x+1<len(grid[y]) and grid[y][x+1] == '1':
island_field.append( (x + 1, y))
grid[y][x+1] = '0'
if y+1 < len(grid) and grid[y+1][x] == '1':
island_field.append( (x, y + 1))
grid[y+1][x] = '0'
if y - 1>=0 and grid[y-1][x] == '1':
island_field.append((x, y - 1))
grid[y-1][x] = '0'
island_field.pop(0) #deleting first element from "to delete" array
# same algoryth but recursion
'''if grid[y][x] == '1':
grid[y][x] = '0'
if x-1>=0:
self.deleteIsland(grid, x - 1, y)
if x+1<len(grid[y]):
self.deleteIsland(grid, x + 1, y)
if y+1 < len(grid):
self.deleteIsland(grid, x, y + 1)
if y - 1>=0:
self.deleteIsland(grid, x, y - 1)
else:
return'''
def numIslands(self, grid: List[List[str]]) -> int:
islands_counter = 0
for y in range(len(grid)):
for x in range(len(grid[y])):
if grid[y][x] == '1':
self.deleteIsland(grid, x, y)
islands_counter +=1
return islands_counter | number-of-islands | Better then 97% iterative python | Pladq | 1 | 359 | number of islands | 200 | 0.564 | Medium | 3,267 |
https://leetcode.com/problems/number-of-islands/discuss/1401860/Python-easy-to-understand-solution.-Mark-and-count. | class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
islandCount = 0
def creep(i, j, matrix):
# if already explored, then return
if matrix[i][j] == "0" or matrix[i][j] == "x" :
return
# mark 1 to x so it wont interfere again
if matrix[i][j] == "1":
matrix[i][j] = "x"
if i < len(matrix) - 1:
creep(i + 1, j, matrix)
if j < len(matrix[0]) - 1:
creep(i, j + 1, matrix)
if i > 0:
creep(i - 1, j, matrix)
if j > 0:
creep(i, j - 1, matrix)
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] == "1":
islandCount += 1
creep(i, j, grid)
return islandCount | number-of-islands | Python easy to understand solution. Mark and count. | vineeth_moturu | 1 | 197 | number of islands | 200 | 0.564 | Medium | 3,268 |
https://leetcode.com/problems/number-of-islands/discuss/1189760/Short-and-Simple-oror-93.6-faster-oror-Python-DFS-oror | class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
def dfs(i,j):
if i>=m or i<0 or j>=n or j<0 or grid[i][j]=="0":
return
grid[i][j]="0"
dfs(i+1,j)
dfs(i-1,j)
dfs(i,j+1)
dfs(i,j-1)
m=len(grid)
n=len(grid[0])
f=0
for i in range(m):
for j in range(n):
if grid[i][j]=="1":
f+=1
dfs(i,j)
return f | number-of-islands | Short and Simple || 93.6% faster || Python DFS || | abhi9Rai | 1 | 215 | number of islands | 200 | 0.564 | Medium | 3,269 |
https://leetcode.com/problems/number-of-islands/discuss/1134032/WEEB-DOES-PYTHON-BFS | class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
row, col = len(grid), len(grid[0])
queue = deque([])
count = 0
for x in range(row):
for y in range(col):
if grid[x][y] == "1":
count+=1
queue.append((x,y))
self.bfs(grid, row, col, queue)
return count
def bfs(self, grid, row, col, queue):
visited = set()
while queue:
x,y = queue.popleft()
grid[x][y] = "visited"
if (x,y) in visited: continue
visited.add((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 grid[nx][ny] == "1":
queue.append((nx,ny)) | number-of-islands | WEEB DOES PYTHON BFS | Skywalker5423 | 1 | 353 | number of islands | 200 | 0.564 | Medium | 3,270 |
https://leetcode.com/problems/number-of-islands/discuss/1103937/Python3-BFS-and-DFS(Recursion)-Solution | class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
'''
Breath-first Search:
'''
num_rows = len(grid)
num_cols = len(grid[0])
total_island = 0
for row in range(num_rows):
for col in range(num_cols):
if grid[row][col] == "1":
# Start doing Breath-first search:
total_island += 1
frontier = [(row, col)]
while frontier:
(x, y) = frontier.pop()
if x-1 >= 0 and grid[x-1][y] == "1":
grid[x-1][y] = "0"
frontier.append((x-1, y))
if x+1 < num_rows and grid[x+1][y] == "1":
grid[x+1][y] = "0"
frontier.append((x+1, y))
if y+1 < num_cols and grid[x][y+1] == "1":
grid[x][y+1] = "0"
frontier.append((x, y+1))
if y-1 >= 0 and grid[x][y-1] == "1":
grid[x][y-1] = "0"
frontier.append((x, y-1))
return total_island
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
'''
DFS - Recursion
'''
def numIslandsRec(grid: List[List[str]], nextLocation: tuple) -> List[List[str]]:
(x, y) = nextLocation
grid[x][y] = "0"
if x+1 < len(grid) and grid[x+1][y] == "1":
grid = numIslandsRec(grid, (x+1, y))
if x-1 >= 0 and grid[x-1][y] == "1":
grid = numIslandsRec(grid, (x-1, y))
if y+1 < len(grid[0]) and grid[x][y+1] == "1":
grid = numIslandsRec(grid, (x, y+1))
if y-1 >= 0 and grid[x][y-1] == "1":
grid = numIslandsRec(grid, (x, y-1))
return grid
num_rows = len(grid)
num_cols = len(grid[0])
total_nums = 0
for row in range(num_rows):
for col in range(num_cols):
if grid[row][col] == "1":
grid = numIslandsRec(grid, (row, col))
total_nums += 1
return total_nums | number-of-islands | Python3 BFS & DFS(Recursion) Solution | Keyuan_Huang | 1 | 184 | number of islands | 200 | 0.564 | Medium | 3,271 |
https://leetcode.com/problems/number-of-islands/discuss/584270/Python3-dfs | class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
if not grid: return 0
m, n = len(grid), len(grid[0])
def fn(i, j):
"""Flood fill cell with "0"."""
grid[i][j] = "0"
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 grid[ii][jj] == "1": fn(ii, jj)
ans = 0
for i in range(m):
for j in range(n):
if grid[i][j] == "1":
ans += 1
fn(i, j)
return ans | number-of-islands | [Python3] dfs | ye15 | 1 | 110 | number of islands | 200 | 0.564 | Medium | 3,272 |
https://leetcode.com/problems/number-of-islands/discuss/584270/Python3-dfs | class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
m, n = len(grid), len(grid[0])
ans = 0
for r in range(m):
for c in range(n):
if grid[r][c] == '1':
ans += 1
grid[r][c] = '0'
stack = [(r, c)]
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 grid[ii][jj] == '1':
grid[ii][jj] = '0'
stack.append((ii, jj))
return ans | number-of-islands | [Python3] dfs | ye15 | 1 | 110 | number of islands | 200 | 0.564 | Medium | 3,273 |
https://leetcode.com/problems/number-of-islands/discuss/452352/Python3-Simple-%2B-Fast-Implementation | class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
count = 0
for i in range(len(grid)):
for j in range(len(grid[i])):
if(grid[i][j] == "1"):
count += 1
self.callBFS(grid, i, j)
return count
def callBFS(self, grid: List[List[str]], x: int, y: int):
if(x < 0 or x >= len(grid) or y < 0 or y >= len(grid[x]) or grid[x][y] == "0"):
return
grid[x][y] = "0"
self.callBFS(grid, x+1, y)
self.callBFS(grid, x-1, y)
self.callBFS(grid, x, y+1)
self.callBFS(grid, x, y-1) | number-of-islands | Python3 Simple + Fast Implementation | iamyatin | 1 | 255 | number of islands | 200 | 0.564 | Medium | 3,274 |
https://leetcode.com/problems/number-of-islands/discuss/384878/Python-BFS-solution | class Solution:
def bfs(self, grid, queue):
while queue:
i, j = queue.pop(0)
for x in (-1, +1):
if i+x>=0 and i+x<len(grid) and grid[i+x][j] == '1':
grid[i+x][j] = '#'
queue.append((i+x, j))
if j+x>=0 and j+x<len(grid[i]) and grid[i][j+x] == '1':
grid[i][j+x] = '#'
queue.append((i, j+x))
def numIslands(self, grid: List[List[str]]) -> int:
queue, sol = [], 0
for i in range(len(grid)):
for j in range(len(grid[i])):
if grid[i][j] == '1':
grid[i][j] = '#'
queue.append((i,j))
self.bfs(grid, queue)
sol+=1
return sol | number-of-islands | Python BFS solution | ahisa | 1 | 536 | number of islands | 200 | 0.564 | Medium | 3,275 |
https://leetcode.com/problems/number-of-islands/discuss/337907/Python-solution-using-dictionary-and-stack | class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
d={}
res=0
for i in range(len(grid)):
for j in range(len(grid[i])):
if grid[i][j]=='1':d[(i,j)]=1
print(d)
while d:
l=list(d.keys())
stack=[l[0]]
del d[l[0]]
res+=1
while stack:
k=stack.pop()
if d.get((k[0]-1,k[1]),-1)==1:
del d[(k[0]-1,k[1])]
stack.append((k[0]-1,k[1]))
if d.get((k[0]+1,k[1]),-1)==1:
del d[(k[0]+1,k[1])]
stack.append((k[0]+1,k[1]))
if d.get((k[0],k[1]-1),-1)==1:
del d[(k[0],k[1]-1)]
stack.append((k[0],k[1]-1))
if d.get((k[0],k[1]+1),-1)==1:
del d[(k[0],k[1]+1)]
stack.append((k[0],k[1]+1))
return res | number-of-islands | Python solution using dictionary and stack | ketan35 | 1 | 183 | number of islands | 200 | 0.564 | Medium | 3,276 |
https://leetcode.com/problems/number-of-islands/discuss/292868/Python-DFS-solution | class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
num_islands = 0
for row in range(len(grid)):
for column in range(len(grid[0])):
if grid[row][column] == '1':
num_islands += 1
self.island_dfs(grid, row, column)
return num_islands
def island_dfs(self, grid, row, column):
min_row, max_row = 0, len(grid) - 1
min_column, max_column = 0, len(grid[0]) - 1
if (not min_row <= row <= max_row) or (not min_column <= column <= max_column):
return
elif grid[row][column] != '1':
return
else:
grid[row][column] = '0'
self.island_dfs(grid, row-1, column)
self.island_dfs(grid, row+1, column)
self.island_dfs(grid, row, column-1)
self.island_dfs(grid, row, column+1) | number-of-islands | Python DFS solution | AdyD | 1 | 574 | number of islands | 200 | 0.564 | Medium | 3,277 |
https://leetcode.com/problems/number-of-islands/discuss/2842030/Python-DFS-Solution | class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
X = len(grid[0]) - 1
Y = len(grid) - 1
cnt = 0
def explore_island(v):
x, y = v
if grid[y][x] == '1':
grid[y][x] = 'land'
if x + 1 <= X: explore_island((x + 1, y))
if y + 1 <= Y: explore_island((x, y + 1))
if x >= 1: explore_island((x - 1, y))
if y >= 1: explore_island((x, y - 1))
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] == '1':
explore_island((j, i))
cnt += 1
return cnt | number-of-islands | Python DFS Solution | LaggerKrd | 0 | 4 | number of islands | 200 | 0.564 | Medium | 3,278 |
https://leetcode.com/problems/number-of-islands/discuss/2835299/Easy-approachor-O(1)-space-or-Violent-imagination-or-Python3 | class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
def sink(x,y):
# index out of range so return
if x<0 or x>=len(grid) or y < 0 or y >=len(grid[0]):return
# no land to sink so return
if grid[x][y] == '0':return
# sink land
grid[x][y] = '0'
# repeat same on neighboring indices
for xNext,yNext in [(x,y-1),(x-1,y),(x,y+1),(x+1,y)]:
sink(xNext,yNext)
count = 0
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j]=="1":
count +=1 # see island
sink(i,j) # sink island
return count | number-of-islands | Easy approach| O(1) space | Violent imagination | Python3 | pardunmeplz | 0 | 4 | number of islands | 200 | 0.564 | Medium | 3,279 |
https://leetcode.com/problems/number-of-islands/discuss/2834271/Intuitive-Easy-To-Understand-PYTHON-Sol | class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
m = len(grid)
n = len(grid[0])
islands=0
def dfs(row, col):
if grid[row][col]=="0":
return
grid[row][col]="0"
for increment in (1,-1):
if 0<=row+increment<m:
dfs(row+increment, col)
if 0<=col+increment<n:
dfs(row, col+increment)
for row in range(m):
for col in range(n):
if grid[row][col] == "1":
islands+=1
dfs(row,col)
return islands | number-of-islands | Intuitive Easy To Understand PYTHON Sol | taabish_khan22 | 0 | 5 | number of islands | 200 | 0.564 | Medium | 3,280 |
https://leetcode.com/problems/number-of-islands/discuss/2827024/Number-of-Islands | class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
rows = len(grid)
cols = len(grid[0])
def isValid(i,j):
if i < 0 or j < 0 or i >= rows or j >= cols:
return False
else:
return True
def dfs(i,j):
if not isValid(i,j):
return
elif grid[i][j] != "1":
return
else:
#valid land
grid[i][j] = "-1"
dfs(i, j+1)
dfs(i, j-1)
dfs(i+1, j)
dfs(i-1, j)
res = 0
for i in range(rows):
for j in range(cols):
if grid[i][j] == "1":
res +=1
dfs(i,j)
return res | number-of-islands | Number of Islands | yashchells | 0 | 3 | number of islands | 200 | 0.564 | Medium | 3,281 |
https://leetcode.com/problems/number-of-islands/discuss/2823646/Easy-Python-BFS-Approach | class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
#BFS Approach
if not grid:
return 0
count = 0
r, c = len(grid), len(grid[0])
visited = [[False for _ in range(c)] for _ in range(r)]
queue = []
for i in range(r):
for j in range(c):
if grid[i][j] == "1" and not visited[i][j]:
count += 1
visited[i][j]=True
queue.append((i,j))
while len(queue)!=0:
x,y=queue.pop(0)
if x>0 and grid[x-1][y]=='1' and not visited[x-1][y]:
queue.append((x-1,y))
visited[x-1][y]=True
if x<len(grid)-1 and grid[x+1][y]=='1' and not visited[x+1][y]:
queue.append((x+1,y))
visited[x+1][y]=True
if y>0 and grid[x][y-1]=='1' and not visited[x][y-1]:
queue.append((x,y-1))
visited[x][y-1]=True
if y<len(grid[0])-1 and grid[x][y+1]=='1' and not visited[x][y+1]:
queue.append((x,y+1))
visited[x][y+1]=True
return count | number-of-islands | Easy Python BFS Approach | dipupaul | 0 | 5 | number of islands | 200 | 0.564 | Medium | 3,282 |
https://leetcode.com/problems/number-of-islands/discuss/2815355/Python-solution | class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
ans = 0
directions = [(-1,0),(1,0),(0,1),(0,-1)]
row = len(grid)
col = len(grid[0])
def dfs(i,j):
for x, y in directions:
dx = i + x
dy = j + y
if dx >= 0 and dx < row and dy >= 0 and dy < col:
if grid[dx][dy] == "1":
grid[dx][dy] = "X"
dfs(dx, dy)
for i in range(row):
for j in range(col):
if grid[i][j] == "1":
dfs(i,j)
ans += 1
return ans | number-of-islands | Python solution | maomao1010 | 0 | 6 | number of islands | 200 | 0.564 | Medium | 3,283 |
https://leetcode.com/problems/number-of-islands/discuss/2812473/simple-solution-with-deep-first-search | class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
q=[]
m=len(grid)
n=len(grid[0])
visited=set([])
direction=[[0,1],[0,-1],[1,0],[-1,0]]
count=0
for i in range(m):
for j in range(n):
if grid[i][j]=="1" and (i,j) not in visited:
q.append((i,j))
visited.add((i,j))
while q:
cur=q.pop()
x=cur[0]
y=cur[1]
for k in direction:
if 0<=x+k[0]<m and 0<=y+k[1]<n and (x+k[0],y+k[1])not in visited and grid[x+k[0]][y+k[1]]=="1":
q.append((x+k[0],y+k[1]))
visited.add((x+k[0],y+k[1]))
count+=1
return count | number-of-islands | simple solution with deep first search | althrun | 0 | 1 | number of islands | 200 | 0.564 | Medium | 3,284 |
https://leetcode.com/problems/number-of-islands/discuss/2797091/Python-oror-DFS-Recursive-oror-DFS-Iterative-oror-BFS | class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
R, C = len(grid), len(grid[0])
visited = set()
count = 0
dirs = [[-1,0],[1,0],[0,-1],[0,1]]
W, L = "0", "1"
def is_valid(r,c):
return (0 <= r < R and 0 <= c < C
and (r,c) not in visited
and grid[r][c] == L)
#INSERT BFS OR DFS FUNCTION HERE
for r in range(R):
for c in range(C):
if is_valid(r,c):
count +=1
dfs(r,c) #or bfs(r,c)
return count | number-of-islands | Python || DFS Recursive || DFS Iterative || BFS | sc1233 | 0 | 17 | number of islands | 200 | 0.564 | Medium | 3,285 |
https://leetcode.com/problems/number-of-islands/discuss/2793724/python-3-solution-using-DFS-recursive-method-Please-upvote-if-u-like-it | class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
if not grid:
return 0
rows,cols = len(grid),len(grid[0])
islands = 0
visit = set()
# using dfs in 2 methods
# firstone
def dfs(r,c):
if r <0 or r >= rows or c <0 or c >= len(grid[0]) or grid[r][c]!="1" :
return
if (r,c) not in visit:
visit.add((r,c))
dfs(r+1,c)
dfs(r-1,c)
dfs(r,c+1)
dfs(r,c-1)
for r in range(rows):
for c in range(cols):
if grid[r][c] == "1" and (r,c) not in visit:
dfs(r,c)
islands+=1
return islands | number-of-islands | python 3 solution using DFS recursive method Please upvote if u like it | mohamedsheded606 | 0 | 12 | number of islands | 200 | 0.564 | Medium | 3,286 |
https://leetcode.com/problems/bitwise-and-of-numbers-range/discuss/469130/Python-iterative-sol.-based-on-bit-manipulation | class Solution:
def rangeBitwiseAnd(self, m: int, n: int) -> int:
shift = 0
# find the common MSB bits.
while m != n:
m = m >> 1
n = n >> 1
shift += 1
return m << shift | bitwise-and-of-numbers-range | Python iterative sol. based on bit-manipulation | brianchiang_tw | 9 | 723 | bitwise and of numbers range | 201 | 0.423 | Medium | 3,287 |
https://leetcode.com/problems/bitwise-and-of-numbers-range/discuss/2740509/Python-Solution-or-bit-manipulation | class Solution:
def rangeBitwiseAnd(self, left: int, right: int) -> int:
leftb = "{0:b}".format(left)
rightb = "{0:b}".format(right)
if len(rightb) > len(leftb):
return 0
res = left
for i in range(left + 1, right + 1):
res = res & i
return res | bitwise-and-of-numbers-range | Python Solution | bit manipulation | maomao1010 | 1 | 72 | bitwise and of numbers range | 201 | 0.423 | Medium | 3,288 |
https://leetcode.com/problems/bitwise-and-of-numbers-range/discuss/1514406/Bitwise-AND-of-Numbers-Range-or-Beginner-friendly-or-Python-Solution | class Solution:
def rangeBitwiseAnd(self, left: int, right: int) -> int:
if left == 0 and right == 0: #To check if both inputs are 0
return 0
elif len(bin(left)) != len(bin(right)): #To check if both inputs have unequal binary number length
return 0
else:
left = bin(left)[2:]
right = bin(right)[2:]
for i in range(len(right)):
if left[i] != right[i]: #We need only the equal elements of left and right numbers; discard all elements after an unequal element
left = left[:i] + ("0" * len(right[i:]))
break
return int(left, 2) | bitwise-and-of-numbers-range | Bitwise AND of Numbers Range | Beginner friendly | Python Solution | Shreya19595 | 1 | 217 | bitwise and of numbers range | 201 | 0.423 | Medium | 3,289 |
https://leetcode.com/problems/bitwise-and-of-numbers-range/discuss/1514129/Solution-With-Intuition-Explained | class Solution:
def rangeBitwiseAnd(self, left: int, right: int) -> int:
def check(left, right, p):
d = right - left
x = 1 << p
if d >= x:
return 0
else:
return 1 if right & x != 0 else 0
ans = left
for i in range(32):
if ans & (1 << i) and not check(left, right, i):
ans ^= (1 << i)
return ans | bitwise-and-of-numbers-range | Solution With Intuition Explained 🏞 | yasir991925 | 1 | 97 | bitwise and of numbers range | 201 | 0.423 | Medium | 3,290 |
https://leetcode.com/problems/bitwise-and-of-numbers-range/discuss/2742371/Python-3-line-solution-with-time-less-O(1's-in-bin(right)) | class Solution:
def rangeBitwiseAnd(self, left: int, right: int) -> int:
while right > left:
right = right & (right - 1)
return right | bitwise-and-of-numbers-range | Python 3-line solution with time < O(#1's in bin(right)) | Fredrick_LI | 0 | 3 | bitwise and of numbers range | 201 | 0.423 | Medium | 3,291 |
https://leetcode.com/problems/bitwise-and-of-numbers-range/discuss/2689537/Easy-Fast-Basic-Python-Solution | class Solution:
def rangeBitwiseAnd(self, left: int, right: int) -> int:
#Optimal Solution
if left==0 or right==0:
return 0
left_limit = math.floor(log(left,2))
right_limit = int(log(right,2))
if right_limit - left_limit:
return 0
return reduce(lambda x,y:x&y, [i for i in range(left, right+1)])
# Memory Limit got killed
# return reduce(lambda x,y:x&y, [i for i in range(left, right+1)]) | bitwise-and-of-numbers-range | Easy Fast Basic Python Solution | RajatGanguly | 0 | 6 | bitwise and of numbers range | 201 | 0.423 | Medium | 3,292 |
https://leetcode.com/problems/bitwise-and-of-numbers-range/discuss/1992017/Python-5-lines-or-Easy-to-understand-O(1)-Space-O(1)-Time | class Solution:
def rangeBitwiseAnd(self, left: int, right: int) -> int:
# check is going to be our result, dist is the distance between the left and the right values
check, dist = right & left, right-left
# for ease, we just start with 31 instead of highest set bit
for i in range(31, -1, -1):
# Now if the bit is set i.e check & (1 << i) returns 1
# and that bit flip range i.e (1 << i) is less than the difference between out left and right values
# we unset that bit
if check & (1 << i) and (1 << i) < dist:
check = check & ~(1<<i)
return check | bitwise-and-of-numbers-range | Python 5 lines | Easy to understand O(1) Space O(1) Time | Apurv_Moroney | 0 | 206 | bitwise and of numbers range | 201 | 0.423 | Medium | 3,293 |
https://leetcode.com/problems/bitwise-and-of-numbers-range/discuss/1974912/Python-bit-shifting-solution-(heavily-commented) | class Solution:
def rangeBitwiseAnd(self, left: int, right: int) -> int:
"""
Given
11010 &
11011 &
11100 &
11101 &
11110 &
-----
11000 result
The AND operator keeps those bits which are set in every number!!
"""
#nOTE: if left != right, there is at least one even number
#and one odd number => last bit of the AND result is always 0
#Find the common group of leftmost bits for the numbers
#in [left, right] by right-shifting (bitseq >>= 1 : "cut away" the rightmost bit of bitseq)
#cnt stores the number of trailing zeroes to the right of
#the common group of bits
cnt = 0
while left != right:
left >>= 1
right >>= 1
cnt += 1
#common group of bits + some trailing zeroes = AND result!! (see the example ^)
#thus let's just left-shift by cnt to get the AND result
return left << cnt | bitwise-and-of-numbers-range | Python bit-shifting solution (heavily commented) | Zikker | 0 | 67 | bitwise and of numbers range | 201 | 0.423 | Medium | 3,294 |
https://leetcode.com/problems/bitwise-and-of-numbers-range/discuss/1698884/easy-to-understand-solution-counting-trailing-zeros | class Solution:
# if num = 600000000 next_num = 600000512, since all the numbers between them will return the same number "num"
def get_next_num(self, num):
trailing_zeros = 0
offset = 1
while num&(num+offset) == num:
trailing_zeros+=1
offset=(2*offset)+1
num+=2**trailing_zeros
return num
def rangeBitwiseAnd(self, left: int, right: int) -> int:
next_num, final = left+1, left
while next_num <= right:
final&=next_num
if not final:
return 0
next_num=self.get_next_num(final)
return final | bitwise-and-of-numbers-range | easy to understand solution - counting trailing zeros | SN009006 | 0 | 100 | bitwise and of numbers range | 201 | 0.423 | Medium | 3,295 |
https://leetcode.com/problems/bitwise-and-of-numbers-range/discuss/1622474/Mechanical-boring-non-genius-ideas-based-on-binary-strings... | class Solution:
def rangeBitwiseAnd(self, left: int, right: int) -> int:
right_binary = ['0']+list(bin(right)[2:])
left_binary = list(bin(left)[2:].zfill(len(right_binary)))
res = ['0']*len(right_binary)
last_zero = 0
for i in range(len(left_binary)):
if left_binary[i] == '0':
last_zero = i
elif left_binary[i]=='1' and right_binary[i]=='1':
res_temp = left_binary[0:last_zero]+['1']
res_temp += ['0']*(len(left_binary)-len(res_temp))
if int(''.join(res_temp),2) > right:
res[i] = '1'
return(int(''.join(res),2)) | bitwise-and-of-numbers-range | Mechanical, boring, non-genius ideas based on binary strings... | throwawayleetcoder19843 | 0 | 68 | bitwise and of numbers range | 201 | 0.423 | Medium | 3,296 |
https://leetcode.com/problems/bitwise-and-of-numbers-range/discuss/594583/Python3-Faster-than-92.22-100-memory-efficient | class Solution:
def rangeBitwiseAnd(self, m, n):
a = m
b = n
while(a < b):
b -= (b & -b)
return b | bitwise-and-of-numbers-range | Python3 Faster than 92.22%, 100% memory efficient | Hannibal404 | 0 | 189 | bitwise and of numbers range | 201 | 0.423 | Medium | 3,297 |
https://leetcode.com/problems/bitwise-and-of-numbers-range/discuss/593941/Python3-binary-common-prefix | class Solution:
def rangeBitwiseAnd(self, m: int, n: int) -> int:
k = 0
while m != n and (k:=k+1):
m, n = m >> 1, n >> 1
return m << k | bitwise-and-of-numbers-range | [Python3] binary common prefix | ye15 | 0 | 46 | bitwise and of numbers range | 201 | 0.423 | Medium | 3,298 |
https://leetcode.com/problems/bitwise-and-of-numbers-range/discuss/593941/Python3-binary-common-prefix | class Solution:
def rangeBitwiseAnd(self, left: int, right: int) -> int:
while left < right: right &= right - 1
return right | bitwise-and-of-numbers-range | [Python3] binary common prefix | ye15 | 0 | 46 | bitwise and of numbers range | 201 | 0.423 | Medium | 3,299 |
Subsets and Splits