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/partition-equal-subset-sum/discuss/838500/Python3-knapsack-solved-by-top-down-dp | class Solution:
def canPartition(self, nums: List[int]) -> bool:
sm = sum(nums)
if sm & 1: return False
bits = 1
for x in nums: bits |= bits << x
return bool(bits & (1<<sm//2)) | partition-equal-subset-sum | [Python3] knapsack solved by top-down dp | ye15 | 1 | 118 | partition equal subset sum | 416 | 0.466 | Medium | 7,400 |
https://leetcode.com/problems/partition-equal-subset-sum/discuss/2797452/Python-(Simple-Dynamic-Programming) | class Solution:
def canPartition(self, nums):
if sum(nums)%2 != 0:
return False
max_weight = sum(nums)//2
dp = [0]*(max_weight+1)
for i in nums:
for w in range(max_weight,-1,-1):
if w - i >= 0:
dp[w] = max(dp[w], i + dp[w-i])
return sum(nums) - 2*dp[-1] == 0 | partition-equal-subset-sum | Python (Simple Dynamic Programming) | rnotappl | 0 | 5 | partition equal subset sum | 416 | 0.466 | Medium | 7,401 |
https://leetcode.com/problems/partition-equal-subset-sum/discuss/2745906/python3-Recursion-and-sets-dp-sol-for-reference. | class Solution:
def canPartition(self, nums: List[int]) -> bool:
ans = False
N = len(nums)
ts = sum(nums)
ns = set([0])
for i in range(N):
for j in list(ns):
p = j+nums[i]
if ts-p > p:
ns.add(p)
elif ts-p == p:
return True
return False | partition-equal-subset-sum | [python3] Recursion and sets / dp sol for reference. | vadhri_venkat | 0 | 3 | partition equal subset sum | 416 | 0.466 | Medium | 7,402 |
https://leetcode.com/problems/partition-equal-subset-sum/discuss/2745906/python3-Recursion-and-sets-dp-sol-for-reference. | class Solution:
def canPartition(self, nums: List[int]) -> bool:
ans = False
N = len(nums)
ts = sum(nums)
h = defaultdict(lambda: -1)
@lru_cache(None)
def r(idx, cnt):
nonlocal ans
if idx == N: return False
if ans: return ans
if ts - cnt < cnt: return False
if ts - cnt == cnt:
ans = True
return True
return r(idx+1, cnt+nums[idx]) or r(idx+1, cnt)
return r(0, 0) | partition-equal-subset-sum | [python3] Recursion and sets / dp sol for reference. | vadhri_venkat | 0 | 3 | partition equal subset sum | 416 | 0.466 | Medium | 7,403 |
https://leetcode.com/problems/partition-equal-subset-sum/discuss/2715144/Python3-DP-Solution | class Solution:
def isSubSet(self, nums, n, dp, total):
if total==0:
return True
if n==-1:
return False
if dp[n][total]!=-1:
return dp[n][total]
if nums[n]>total:
dp[n][total] = self.isSubSet(nums,n-1,dp,total)
dp[n][total] = self.isSubSet(nums,n-1,dp,total) or self.isSubSet(nums,n-1,dp,total-nums[n])
return dp[n][total]
def canPartition(self, nums: List[int]) -> bool:
total = sum(nums)
if total%2 == 1:
return False
dp = [[-1 for i in range(total//2 + 1)] for j in range(len(nums))]
return self.isSubSet(nums,len(nums)-1,dp, total//2) | partition-equal-subset-sum | Python3 DP Solution | paul1202 | 0 | 8 | partition equal subset sum | 416 | 0.466 | Medium | 7,404 |
https://leetcode.com/problems/partition-equal-subset-sum/discuss/2686880/Python-3-solution-faster-than-99 | class Solution:
def canPartition(self, nums: List[int]) -> bool:
target = sum(nums) / 2
if target%1 != 0: # if not even, there can't be a solution
return False
possib = {0} # set to store all the subset sums seen
for num in nums[:-1]:
possib = possib | {x+num for x in possib} # new subset sums are the older ones and older ones plus new value
if target in possib:
return True
return False | partition-equal-subset-sum | Python 3 solution faster than 99% | user6658I | 0 | 22 | partition equal subset sum | 416 | 0.466 | Medium | 7,405 |
https://leetcode.com/problems/partition-equal-subset-sum/discuss/2660341/RECURSION-WITH-MEMOIZATION | class Solution:
def canPartition(self, nums: List[int]) -> bool:
if sum(nums) % 2:
return False
target = sum(nums) // 2
memo = [[-1 for _ in range(target+1)] for _ in range(len(nums)+1)]
def part(nums, target, n):
if target == 0:
return True
if n == 0:
return False
if memo[n][target] != -1:
return memo[n][target]
if (nums[n-1] <= target):
memo[n][target] = part(nums, target-nums[n-1], n-1) or part(nums, target, n-1)
return memo[n][target]
else:
memo[n][target] = part(nums, target, n-1)
return memo[n][target]
part(nums, target, len(nums))
return memo[len(nums)][target] | partition-equal-subset-sum | RECURSION WITH MEMOIZATION | leomensah | 0 | 64 | partition equal subset sum | 416 | 0.466 | Medium | 7,406 |
https://leetcode.com/problems/partition-equal-subset-sum/discuss/2634404/Python-DP-faster-than-98-(Easy-Understanding) | class Solution:
def canPartition(self, nums: List[int]) -> bool:
s = sum(nums)
# Bit operation, if s is odd then returns False otherwise True
if s&1:
return False
# The target is to choose a subset of elements where the sum is equal to the sum(s)/2
# dp saves the sum we have ever seen, the sum is 0 if we don't choose any element, so we initilize dp = set([0])
dp = set([0])
for num in nums:
for seen_sum in list(dp):
if seen_sum+num not in dp:
dp.add(seen_sum+num)
if s/2 in dp:
return True
return False
# Time O(n**2)
# Space O(s) | partition-equal-subset-sum | Python DP faster than 98% (Easy Understanding) | mkming1226 | 0 | 45 | partition equal subset sum | 416 | 0.466 | Medium | 7,407 |
https://leetcode.com/problems/partition-equal-subset-sum/discuss/2497705/Cleanest-Simplest-Fastest-Python3-You've-Ever-Seen | class Solution:
def canPartition(self, nums: List[int]) -> bool:
n, sm = len(nums), sum(nums)
if n < 2 or sm % 2:
return False
half = sm // 2
mem = [True] + [False] * half
for i in range(n):
for sum1 in range(half, 0, -1):
if sum1 >= nums[i] and mem[sum1 - nums[i]]:
mem[sum1] = True
if mem[half]:
return True
return mem[half] | partition-equal-subset-sum | Cleanest, Simplest, Fastest Python3 You've Ever Seen | ryangrayson | 0 | 48 | partition equal subset sum | 416 | 0.466 | Medium | 7,408 |
https://leetcode.com/problems/partition-equal-subset-sum/discuss/2472800/DP-Subset-Sum-Python3 | class Solution:
def canPartition(self, nums: List[int]) -> bool:
if sum(nums)%2==1:
return False
summ=sum(nums)//2
dp=[[False for i in range(summ+1)]for j in range(len(nums)+1)]
for i in range(len(nums)+1):
dp[i][0]=True
for i in range(1,len(nums)+1):
for j in range(1,summ+1):
if j<nums[i-1]:
dp[i][j]=dp[i-1][j]
else:
dp[i][j]=dp[i-1][j] or dp[i-1][j-nums[i-1]]
# print(dp)
return dp[len(nums)][summ]
# dp[i][j]=dp[i-1][j | partition-equal-subset-sum | DP Subset Sum - Python3 | Prithiviraj1927 | 0 | 76 | partition equal subset sum | 416 | 0.466 | Medium | 7,409 |
https://leetcode.com/problems/partition-equal-subset-sum/discuss/2411618/Python3-or-Solved-Bottom-Up-or-DP-or-Tabulation | class Solution:
#Time-Complexity: O(n * summation), since in worst case the distinct subset sum vals
#can range from 1 to summation! -> We are iterating through n distinct state parameter
#values for index position i!
#Space-Complexity: O(n * summation)
def canPartition(self, nums: List[int]) -> bool:
#Total Sum of All Elements = 2 * (sum of all elements in any given subset)
#if there exists valid partitioning!
#Let's say we are able to find one subset of elements, whose sum matches
#total sum / 2! Then, we can use remaining unused elements to form the other
#subset whose sum will be total sum - (totalsum)/2 = totalsum /2, which match!
#So, if valid partioning exists for given array, all we have to do is verify that
#a subset with elements' sum equalling exactly sum(nums) / 2 exists!
#dp table with indices ranging from 0 to n-1, where index of dp represents
#the index position of all elements up to who we are considering when trying
#to form all possible subsets and record all distinct subset sum values!
n = len(nums)
dp = [set()] * n
#get sum of all elements!
summation = sum(nums)
#get the target single subset sum value!
target = float(summation / 2)
dp[0].add(nums[0])
#iterate through each state parameter: there's only one, which again represents
#index position i up to!
#State i -> set(all distinct subset sum vals using elements up to nums[i])
for i in range(1, n):
#iterate through each possible subset sum using elements up to element at
#previous index position, i - 1
new_subset_sums = []
for subsetsum in dp[i-1]:
#check if subset sum previously alone equals target or if subsetsum added # the current element nums[i] equals target!
if(float(subsetsum) == target or float(subsetsum + nums[i]) == target):
return True
new_subset_sums.append(subsetsum + nums[i])
dp[i] = dp[i-1]
for element in set(new_subset_sums):
dp[i].add(element)
return False | partition-equal-subset-sum | Python3 | Solved Bottom-Up | DP | Tabulation | JOON1234 | 0 | 34 | partition equal subset sum | 416 | 0.466 | Medium | 7,410 |
https://leetcode.com/problems/partition-equal-subset-sum/discuss/2339554/python3-easy-fast-concise-solution | class Solution:
def canPartition(self, nums: List[int]) -> bool:
if sum(nums) % 2:
return False
dp = set()
dp.add(0)
target = sum(nums) // 2
for i in range(len(nums) - 1, -1, -1):
nextDp = set()
for t in dp:
if t + nums[i] == target:
return True
nextDp.add(t + nums[i])
nextDp.add(t)
dp = nextDp
return True if target in dp else False | partition-equal-subset-sum | python3 easy fast concise solution | soumyadexter7 | 0 | 74 | partition equal subset sum | 416 | 0.466 | Medium | 7,411 |
https://leetcode.com/problems/partition-equal-subset-sum/discuss/2279474/Python-DP-Solution | class Solution:
def canPartition(self, nums: List[int]) -> bool:
dp = {}
def r(index, target):
if index == 0:
return target == nums[0]
if target == 0:
return True
if (index, target) in dp:
return dp[(index, target)]
notTake = r(index-1, target)
if notTake == True:
return True
take = False
if nums[index] <= target:
take = r(index-1, target - nums[index])
if take == True:
return True
dp[(index, target)] = (take or notTake)
return dp[(index, target)]
if sum(nums) % 2 != 0:
return False
else:
return r(len(nums)-1, sum(nums) // 2) | partition-equal-subset-sum | Python DP Solution | DietCoke777 | 0 | 39 | partition equal subset sum | 416 | 0.466 | Medium | 7,412 |
https://leetcode.com/problems/partition-equal-subset-sum/discuss/2152308/Python(DP%2BCache-Solution) | class Solution:
def canPartition(self, nums: List[int]) -> bool:
target = sum(nums)//2
if sum(nums)%2==1:
return False
def dfs(target,start):
if target==0:
return True
if target<0:
return False
if target in dp:
return False
for i in range(start,len(nums)):
if dfs(target-nums[i],i+1) or dfs(target,i+1):
return True
dp[target]=False
return dp[target]
dp={}
return dfs(target,0)
def canPartition3(self, nums: List[int]) -> bool:
target = sum(nums)//2
if sum(nums)%2==1:
return False
dpSet = set()
dpSet.add(0)
for i in nums[::-1]:
newDpSet = set()
for n in dpSet:
if n+i == target:
return True
newDpSet.add(n+i)
newDpSet.add(n)
dpSet = newDpSet
return target in dpSet
def canPartition2(self, nums: List[int]) -> bool:
#self.canPartition2(len(nums)-2,sum(nums)-nums[-1],nums)
n=len(nums)
target=sum(nums)
if target%2!=0:
return False
target=target//2
dp=[[True for _ in range(target+1)]for _ in range(len(nums)+1)]
for i in range(1,n):
dp[i][0]=True
for i in range(1,target+1):
dp[0][i]=False
print(dp)
for i in range(1,len(nums)+1):
for j in range(1,target+1):
if j>=nums[i-1]:
dp[i][j]=dp[i-1][j] or dp[i-1][j-nums[i-1]]
else:
dp[i][j]=dp[i-1][j]
#print(dp)
return dp[len(nums)][target] | partition-equal-subset-sum | Python(DP+Cache Solution) | sethaman1112 | 0 | 50 | partition equal subset sum | 416 | 0.466 | Medium | 7,413 |
https://leetcode.com/problems/partition-equal-subset-sum/discuss/2100378/python-or-dp-or-example | class Solution:
def canPartition(self, nums: List[int]) -> bool:
total = sum(nums)
if total & 1:
return False
target = total >> 1
# print([i for i in range(target + 1)])
# print()
dp = [[0 for _ in range(target + 1)] for _ in range(len(nums) + 1)]
for i in range(1, len(dp)):
cur_val = nums[i - 1]
for j in range(1, len(dp[0])):
prev = cur_val + dp[i - 1][j - cur_val] if cur_val <= j else 0
dp[i][j] = max(dp[i - 1][j], prev if prev <= j else 0)
if dp[i][j] == target:
return True
# for i, r in enumerate(dp):
# print(0 if i == 0 else nums[i - 1], r)
return False
return dp[-1][-1] == target
"""
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
1 [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
5 [0, 1, 1, 1, 1, 5, 6, 6, 6, 6, 6, 6]
11 [0, 1, 1, 1, 1, 5, 6, 6, 6, 6, 6, 11]
5 [0, 1, 1, 1, 1, 5, 6, 6, 6, 6, 10, 11]
Find target = 11 return True
""" | partition-equal-subset-sum | python | dp | example | yzhao156 | 0 | 30 | partition equal subset sum | 416 | 0.466 | Medium | 7,414 |
https://leetcode.com/problems/partition-equal-subset-sum/discuss/2086646/Python-Solution | class Solution:
def canPartition(self, nums: List[int]) -> bool:
s=sum(nums)
if s%2==1:
return False
else:
s=s//2
n=len(nums)
dp =([[False for i in range(s+1)] for i in range(n + 1)])
for i in range(n+1):
for j in range(s+1):
if i==0:
dp[i][j]=False
if j==0:
dp[i][j]=True
for i in range(1,len(dp)):
for j in range(1,len(dp[0])):
if nums[i-1]<=j:
dp[i][j]=dp[i-1][j-nums[i-1]] or dp[i-1][j]
else:
dp[i][j]=dp[i-1][j]
return dp[n][s] | partition-equal-subset-sum | Python Solution | a_dityamishra | 0 | 71 | partition equal subset sum | 416 | 0.466 | Medium | 7,415 |
https://leetcode.com/problems/partition-equal-subset-sum/discuss/2076192/Python3-Very-Simple-Top-Down-Solution | class Solution:
from functools import cache
def canPartition(self, nums: List[int]) -> bool:
n, sum_ = len(nums), sum(nums)
if n == 1 or sum_ % 2 != 0:
return False
half_sum = sum_ / 2
@cache
def recurse(start: int, curr_sum: int) -> bool:
if curr_sum == half_sum:
return True
if curr_sum > half_sum:
return False
for i in range(start + 1, n + 1):
if recurse(i, curr_sum + nums[start]):
return True
return False
return recurse(0, 0) | partition-equal-subset-sum | Python3 Very Simple Top-Down Solution | martynas-subonis | 0 | 68 | partition equal subset sum | 416 | 0.466 | Medium | 7,416 |
https://leetcode.com/problems/partition-equal-subset-sum/discuss/2068021/Using-dp-learned-from-NeetCode | class Solution:
def canPartition(self, nums: List[int]) -> bool:
res = sum(nums)
if res % 2:
return False
res /= 2
t1 = set([0])
for n in nums:
if res in t1:
return True
t2 = set(t + n for t in t1)
t1.update(t2)
return False
# Link: https://www.youtube.com/watch?v=IsvocB5BJhw | partition-equal-subset-sum | Using dp learned from NeetCode | andrewnerdimo | 0 | 68 | partition equal subset sum | 416 | 0.466 | Medium | 7,417 |
https://leetcode.com/problems/partition-equal-subset-sum/discuss/2019151/Python3-Solution-or-Dynamic-Programming | class Solution:
def canPartition(self, nums: List[int]) -> bool:
if sum(nums) & 1:
return False
target = sum(nums) >> 1
dp = [True] + [False] * target
for i in nums:
for j in range(target , i - 1, -1):
dp[j] |= dp[j-i]
return dp[target] | partition-equal-subset-sum | Python3 Solution | Dynamic Programming | satyam2001 | 0 | 103 | partition equal subset sum | 416 | 0.466 | Medium | 7,418 |
https://leetcode.com/problems/partition-equal-subset-sum/discuss/2000757/Simple-easy-to-understand-and-a-clean-code-in-python | class Solution:
def canPartition(self, nums: List[int]) -> bool:
if sum(nums)%2!=0:
return False
target=sum(nums)//2
@lru_cache(None)
def rec(i,tsum):
if tsum==target:
return True
if i==len(nums):
return False
if tsum+nums[i]>target:
return rec(i+1,tsum)
return rec(i+1,tsum+nums[i]) or rec(i+1,tsum)
return rec(0,0) | partition-equal-subset-sum | Simple, easy to understand and a clean code in python | pbhuvaneshwar | 0 | 107 | partition equal subset sum | 416 | 0.466 | Medium | 7,419 |
https://leetcode.com/problems/partition-equal-subset-sum/discuss/1700120/Python-or-Recursion | class Solution:
def canPartition(self, nums: List[int]) -> bool:
sm=sum(nums)
if sm%2==1:
return False
tomake=sm//2
nums.sort()
@lru_cache(None)
def dfs(tomake,start):
if tomake==0:
return True
for i in range(start,len(nums)):
if tomake-nums[i]>=0:
r=dfs(tomake-nums[i],i+1)
if r:
return r
return False
return dfs(tomake,0) | partition-equal-subset-sum | Python | Recursion | heckt27 | 0 | 55 | partition equal subset sum | 416 | 0.466 | Medium | 7,420 |
https://leetcode.com/problems/partition-equal-subset-sum/discuss/1625345/Python3-DP-solution | class Solution:
def canPartition(self, nums: List[int]) -> bool:
_sum = sum(nums)
if _sum % 2 != 0:
return False
target = _sum // 2
dp = [[False for _ in range(target + 1)] for _ in range(len(nums) + 1)]
dp[0][0] = True
for i in range(1, len(nums) + 1):
num = nums[i - 1]
for j in range(target + 1):
if j < num:
dp[i][j] = dp[i - 1][j]
else:
dp[i][j] = dp[i - 1][j - num] or dp[i - 1][j]
return dp[len(nums)][-1] | partition-equal-subset-sum | [Python3] DP solution | maosipov11 | 0 | 37 | partition equal subset sum | 416 | 0.466 | Medium | 7,421 |
https://leetcode.com/problems/partition-equal-subset-sum/discuss/1624455/Python3-or-Solution-or-Works-or-Alts-tried-it-and-it-worked-or | class Solution:
def canPartition(self, nums: List[int]) -> bool:
r = sum(nums)
if r%2 != 0:
return False
f = {}
return self.canSum(nums, r/2, f)
def canSum(self, nums, ew, f):
if ew in f: return f[ew]
if ew < 0: return False
if ew == 0: return True
for index, num in enumerate(nums):
remainder = ew - num
arr = [*nums[:index], *nums[index+1:]]
if self.canSum(arr, remainder, f) == True:
f[ew] = True
return True
f[ew] = False
return False
# 🔥 Please upvote 🔥 | partition-equal-subset-sum | 📌 Python3 | Solution | Works | Alts tried it and it worked | | underplaceomg | 0 | 80 | partition equal subset sum | 416 | 0.466 | Medium | 7,422 |
https://leetcode.com/problems/partition-equal-subset-sum/discuss/1624341/Python-Solution | class Solution:
def canPartition(self, nums: List[int]) -> bool:
nums.sort(key=lambda x: -x)
e = len(nums)
r = sum(nums)
if r % 2 == 1:
return False
re = r // 2
if nums[0] > re:
return False
def dp(total, mask):
if total > re:
return False
if total == re:
return True
for i in range(e):
if mask & (1 << i) == 0:
mask2 = mask | (1 << i)
if dp(total+nums[i], mask2):
return True
return False
return dp(0, 0)
```
Please Upvote :) | partition-equal-subset-sum | Python Solution | underplaceomg | 0 | 74 | partition equal subset sum | 416 | 0.466 | Medium | 7,423 |
https://leetcode.com/problems/partition-equal-subset-sum/discuss/1502793/Python-DP-Memoization-Simple-Solution | class Solution:
def canPartition(self, nums: List[int]) -> bool:
tot = sum(nums)
N = len(nums)
if tot % 2 == 1: return False
memo = {}
def backtrack(cumsum=0, pos=0):
if pos >= N:
return False
if (cumsum, pos) in memo:
return memo[(cumsum, pos)]
if cumsum == tot // 2:
return True
memo[(cumsum, pos)] = backtrack(cumsum + nums[pos], pos+1) or backtrack(cumsum, pos+1)
return memo[(cumsum, pos)]
return backtrack()
``` | partition-equal-subset-sum | Python DP Memoization Simple Solution | vharigovind9 | 0 | 217 | partition equal subset sum | 416 | 0.466 | Medium | 7,424 |
https://leetcode.com/problems/partition-equal-subset-sum/discuss/1454567/PyPy3-Solution-using-recursion-%2B-memoization-w-comments | class Solution:
def canPartition(self, nums: List[int]) -> bool:
"""
# NOTE: Time limit execeeds for this function.
# Solution using recursion
def subsetSum(a: List[int], target: int) -> bool:
def recursiveSubsetSum(n, w):
if n==0 and w==0:
return True
elif n==0 and w!=0:
return False
else:
if a[n-1] <= w:
if w-a[n-1] == 0:
return True
else:
return recursiveSubsetSum(n-1, w-a[n-1]) or recursiveSubsetSum(n-1, w)
else:
return recursiveSubsetSum(n-1, w)
return False
return recursiveSubsetSum(len(a), target)
"""
# Solution using recursion with memoization
def subsetSum(a: List[int], target: int) -> bool:
t = dict()
def recursiveSubsetSum(n, w):
# Base Condition 1
if n == 0 and w == 0:
t[(n,w)] = True
# Base Condition 2
elif n==0 and w!= 0:
t[(n,w)] = False
# Regular Operation
else:
# If key exsit in t, i.e, sub-problem detected, ignore rest
if (n,w) not in t:
# if current value is less than expected value
if a[n-1] <= w:
# See if target reached using current value
if w-a[n-1] == 0:
t[(n,w)] = True
else: # Select or Don't select current value
t[(n,w)] = recursiveSubsetSum(n-1,w-a[n-1]) or recursiveSubsetSum(n-1,w)
else: # Dont select current value
t[(n,w)] = recursiveSubsetSum(n-1,w)
# Return the answer
return t[(n,w)]
return recursiveSubsetSum(len(a), target)
# Init
n = len(nums)
total = sum(nums)
# In case if the sum of array
# is odd return false
if total%2:
return False
# Find the subset sum of nums
# whose sum equal to half of total
if subsetSum(nums, total//2):
return True
return False | partition-equal-subset-sum | [Py/Py3] Solution using recursion + memoization w/ comments | ssshukla26 | 0 | 121 | partition equal subset sum | 416 | 0.466 | Medium | 7,425 |
https://leetcode.com/problems/partition-equal-subset-sum/discuss/1190653/Python-Recursive-and-Tabulation-DP-Solution | class Solution:
def canPartition(self, nums: List[int]) -> bool:
n = len(nums)
sumArr = sum(nums)
if sumArr%2 != 0:
return False
#return self.partition(nums,n,sumArr//2)
return self.dpApproach(nums,n,sumArr//2)
def recursive(self,nums,n,target):
if n <= 0 and target>0:
return False
if n>=0 and target==0:
return True
if nums[n-1] <= target:
return self.partition(nums,n-1,target-nums[n-1]) or self.partition(nums,n-1,target)
else:
return self.partition(nums,n-1,target)
def dpApproach(self,nums,n,target):
dpTable = [[False for i in range(0,target+1)] for j in range(0,n+1)]
for j in range(0,n+1):
dpTable[j][0] = True
for r in range(1,n+1):
for c in range(1,target+1):
if nums[r-1] <= c:
dpTable[r][c] = dpTable[r-1][c-nums[r-1]] or dpTable[r-1][c]
else:
dpTable[r][c] = dpTable[r-1][c]
return dpTable[-1][-1] | partition-equal-subset-sum | Python - Recursive and Tabulation DP Solution | tgoel219 | 0 | 98 | partition equal subset sum | 416 | 0.466 | Medium | 7,426 |
https://leetcode.com/problems/partition-equal-subset-sum/discuss/951162/Python3-Beats-90-in-Time-and-70-in-Space | class Solution:
def canPartition(self, nums: List[int]) -> bool:
summation = sum(nums)
if summation % 2:
# if odd sum, return False
return False
nums = sorted(nums)
def selection(ls, target):
"""
ls is sorted.
This function is to select elements from the list whose sum is the target.
It will start from the smaller ones.
Once the sum of the selection surpasses the target,
it will find if there are any elements whose sum is the selection sum minus target.
If not, it will substitude the largest one in the selection with a larger value in ls next to it
and do the same.
"""
if sum(ls) < target:
return False
if ls[0] > target:
return False
if ls[0] == target or ls[-1] == target:
return True
tmp = 0
res = False
flag = 0
for i in range(len(ls)):
tmp += ls[i]
if tmp == target:
return True
elif tmp > target:
if flag == 0:
flag = 1
j = i
"""
The key thing is that once we reach a position j where ls[:j + 1] > target
We do not need to include more than 1 element from ls[j + 1:]
1. Because ls is sorted, ls[t] >= ls[j] for t > j and thus sum(ls[:j]) + ls[t] > target
2. Let's assume we include a ls[t] where t > j
and we want to find out if we can remove any elements
so that their sum is sum(ls[:j]) + ls[t] - target.
If there is any, we return True.
Otherwise, if we continue to include another element ls[s] where s > t.
We are trying to find out if there is any elements in ls[:j] + [ls[t]]
that have sum as sum(ls[:j]) + ls[t] + ls[s] - target,
which is equivalent to dropping ls[t]
"""
res = res or selection(ls[:j], tmp - target)
if res:
return True
tmp -= ls[i]
return False
return selection(nums, summation // 2) | partition-equal-subset-sum | [Python3] Beats 90% in Time and 70% in Space | leonine9 | 0 | 59 | partition equal subset sum | 416 | 0.466 | Medium | 7,427 |
https://leetcode.com/problems/partition-equal-subset-sum/discuss/950616/python-dp-solution | class Solution:
def canPartition(self, nums: List[int]) -> bool:
if sum(nums)%2 != 0:
return False
target = (sum(nums)//2)
dp = [0] * (target*2)
dp[0] = 1
for item in nums:
if item > sum(nums)//2:
return False
if item == sum(nums)//2:
return True
for j in range(target,-1,-1):
if dp[j] == 1:
dp[j+item] = 1
if dp[target]:
return True
return False | partition-equal-subset-sum | python dp solution | yingziqing123 | 0 | 295 | partition equal subset sum | 416 | 0.466 | Medium | 7,428 |
https://leetcode.com/problems/partition-equal-subset-sum/discuss/487165/Python3-three-different-solutions-with-time-limit-test-case | class Solution:
def canPartition(self, nums: List[int]) -> bool:
s = sum(nums)
if s%2!=0: return False
ht = {0}
for num in nums:
ht.update({sum + num for sum in ht})
return s//2 in ht
def canPartitionDP(self, nums: List[int]) -> bool:
s = sum(nums)
if s%2!=0: return False
dp = []
for row in range(s//2+1):
dp.append([False]+[True]*(len(nums)))
for i in range(1,s//2+1):
for j in range(1,len(nums)+1):
dp[i][j]=dp[i][j-1]
if i>=nums[j-1]:
dp[i][j] = dp[i][j] or dp[i-nums[j-1]][j-1]
return dp[-1][-1]
def canPartitionRecursive(self, nums: List[int]) -> bool:
s = sum(nums)
if s%2!=0: return False
return self.isSubset(nums,len(nums),s//2)
def isSubset(self,arr,n,sum):
if sum == 0: return True
if n == 0 and sum != 0: return False
if arr[n-1]>sum:
return self.isSubset(arr,n-1,sum)
return self.isSubset(arr,n-1,sum) or self.isSubset(arr,n-1,sum-arr[n-1]) | partition-equal-subset-sum | Python3 three different solutions with time limit test case | jb07 | 0 | 225 | partition equal subset sum | 416 | 0.466 | Medium | 7,429 |
https://leetcode.com/problems/partition-equal-subset-sum/discuss/1564627/Python-2-way-of-solution-with-same-time-complexity-but-different-space-complexity-using-DP | class Solution:
def canPartition(self, nums: List[int]) -> bool:
total = sum(nums)
limit = total//2
if total%2==1: return False
dp = [[0 for j in range(limit+1)] for i in range(len(nums))]
for i in range(len(nums)):
for j in range(1, limit+1):
dp[i][j] = max(
dp[i-1][j] if i>0 else 0,
nums[i] + dp[i-1][j-nums[i]] if j>=nums[i] and i>0 else 0
)
if dp[i][j]==limit: return True
return False | partition-equal-subset-sum | Python - 2 way of solution with same time complexity, but different space complexity using DP | abrarjahin | -1 | 205 | partition equal subset sum | 416 | 0.466 | Medium | 7,430 |
https://leetcode.com/problems/partition-equal-subset-sum/discuss/1564627/Python-2-way-of-solution-with-same-time-complexity-but-different-space-complexity-using-DP | class Solution:
def canPartition(self, nums: List[int]) -> bool:
total = sum(nums)
if total % 2 != 0: return False
target = total // 2
dp = [False]*(target + 1)
dp[0] = True
for num in nums:
for i in range(target, num-1, -1):
dp[i] = dp[i] or dp[i-num]
if dp[target]: return True
return dp[target] | partition-equal-subset-sum | Python - 2 way of solution with same time complexity, but different space complexity using DP | abrarjahin | -1 | 205 | partition equal subset sum | 416 | 0.466 | Medium | 7,431 |
https://leetcode.com/problems/pacific-atlantic-water-flow/discuss/2507252/PYTHON-oror-EXPLAINED-oror | class Solution:
def pacificAtlantic(self, ht: List[List[int]]) -> List[List[int]]:
def pac(i,j):
if rp[i][j]:
return True
k=False
h=ht[i][j]
ht[i][j]=100001
if ht[i-1][j]<=h:
k=k or pac(i-1,j)
if ht[i][j-1]<=h:
k=k or pac(i,j-1)
if i<m-1 and ht[i+1][j]<=h:
k=k or pac(i+1,j)
if j<n-1 and ht[i][j+1]<=h:
k=k or pac(i,j+1)
ht[i][j]=h
rp[i][j]=k
return k
def ant(i,j):
if ra[i][j]:
return True
k=False
h=ht[i][j]
ht[i][j]=100001
if i>0 and ht[i-1][j]<=h:
k=k or ant(i-1,j)
if j>0 and ht[i][j-1]<=h:
k=k or ant(i,j-1)
if ht[i+1][j]<=h:
k=k or ant(i+1,j)
if ht[i][j+1]<=h:
k=k or ant(i,j+1)
ht[i][j]=h
ra[i][j]=k
return k
m=len(ht)
n=len(ht[0])
rp=[[False for i in range(n)] for j in range(m)]
ra=[[False for i in range(n)] for j in range(m)]
for i in range(m):
rp[i][0]=True
ra[i][-1]=True
for i in range(n):
rp[0][i]=True
ra[-1][i]=True
for i in range(m):
for j in range(n):
pac(i,j)
ant(i,j)
res=[]
for i in range(m):
for j in range(n):
if rp[i][j] and ra[i][j]:
res.append([i,j])
return res | pacific-atlantic-water-flow | 🥇 PYTHON || EXPLAINED || ; ] | karan_8082 | 16 | 1,900 | pacific atlantic water flow | 417 | 0.541 | Medium | 7,432 |
https://leetcode.com/problems/pacific-atlantic-water-flow/discuss/882548/Python-3-or-BFS-Set-Intersection-or-Explanation | class Solution:
def pacificAtlantic(self, matrix: List[List[int]]) -> List[List[int]]:
if not matrix: return []
m, n = len(matrix), len(matrix[0])
pacific = [(0, i) for i in range(n)] + [(i, 0) for i in range(1, m)]
atlantic = [(m-1, i) for i in range(n)] + [(i, n-1) for i in range(m-1)]
def bfs(q):
visited = set()
q = collections.deque(q)
while q:
i, j = q.popleft()
visited.add((i, j))
for ii, jj in map(lambda x: (x[0]+i, x[1]+j), [(-1, 0), (1, 0), (0, -1), (0, 1)]):
if 0 <= ii < m and 0 <= jj < n and (ii, jj) not in visited and matrix[ii][jj] >= matrix[i][j]:
q.append((ii, jj))
return visited
return bfs(pacific) & bfs(atlantic) | pacific-atlantic-water-flow | Python 3 | BFS, Set Intersection | Explanation | idontknoooo | 12 | 1,600 | pacific atlantic water flow | 417 | 0.541 | Medium | 7,433 |
https://leetcode.com/problems/pacific-atlantic-water-flow/discuss/2508533/Python-Elegant-and-Short-or-DFS-or-99.21-faster | class Solution:
"""
Time: O(n*m)
Memory: O(n*m)
"""
MOVES = [(-1, 0), (0, -1), (1, 0), (0, 1)]
def pacificAtlantic(self, heights: List[List[int]]) -> Set[Tuple[int, int]]:
def dfs(i: int, j: int, visited: set):
visited.add((i, j))
for di, dj in self.MOVES:
x, y = i + di, j + dj
if 0 <= x < n and 0 <= y < m and (x, y) not in visited and heights[i][j] <= heights[x][y]:
dfs(x, y, visited)
n, m = len(heights), len(heights[0])
atl_visited = set()
pas_visited = set()
for i in range(n):
dfs(i, 0, pas_visited)
dfs(i, m - 1, atl_visited)
for j in range(m):
dfs( 0, j, pas_visited)
dfs(n - 1, j, atl_visited)
return atl_visited & pas_visited | pacific-atlantic-water-flow | Python Elegant & Short | DFS | 99.21% faster | Kyrylo-Ktl | 10 | 690 | pacific atlantic water flow | 417 | 0.541 | Medium | 7,434 |
https://leetcode.com/problems/pacific-atlantic-water-flow/discuss/954799/DFS-Python3-easy-to-understand-with-comments. | class Solution:
def pacificAtlantic(self, matrix: List[List[int]]) -> List[List[int]]:
if not matrix or not matrix[0]:
return []
# list which will have both the coordinates
pacific = set()
atlantic = set()
# get the number of rows and columns
m,n = len(matrix), len(matrix[0])
# define left, right, up, down
directions = [(-1,0),(1,0),(0,1),(0,-1)]
# define the dfs traversal
def dfs(visited, x,y):
visited.add((x,y))
for dx, dy in directions:
new_x, new_y = x + dx, y + dy
# if the coordinates are valid and if c(i) > c (i-1)
if 0 <= new_x < m and 0 <= new_y < n and (new_x, new_y) not in visited and matrix[new_x][new_y] >= matrix[x][y]:
dfs (visited, new_x, new_y)
# iterate for rows
for i in range(m):
dfs(pacific, i , 0)
dfs(atlantic, i, n-1)
# iterate for columns
for j in range(n):
dfs(pacific, 0 , j)
dfs(atlantic, m-1, j)
# return the matching coordinates
return list(pacific.intersection(atlantic)) | pacific-atlantic-water-flow | DFS Python3, easy to understand with comments. | rotikapdamakan | 10 | 554 | pacific atlantic water flow | 417 | 0.541 | Medium | 7,435 |
https://leetcode.com/problems/pacific-atlantic-water-flow/discuss/1581227/Clean-python-code-O(mn)-DFS | class Solution:
def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:
m, n = len(heights), len(heights[0])
v_pac = set()
v_atl = set()
def dfs(v_set, row, col, curr_height):
if row < 0 or row >= m or \
col < 0 or col >= n or \
(row,col) in v_set or \
curr_height > heights[row][col]:
return
v_set.add((row, col))
curr_height = heights[row][col]
dfs(v_set, row + 1, col, curr_height)
dfs(v_set, row - 1, col, curr_height)
dfs(v_set, row, col + 1, curr_height)
dfs(v_set, row, col - 1, curr_height)
# Approach is to start from both sides of
# the oceans and then reach each point that can be
# reached while maintaining the visited indices
# Iterate over columns and start from both 0, m-1 rows
for col in range(n):
dfs(v_pac, 0, col, heights[0][col]) # First row
dfs(v_atl, m - 1, col, heights[m-1][col]) # Last row
# Iterate over rows and start from both 0, n-1 cols
for row in range(m):
dfs(v_pac, row, 0, heights[row][0]) # First column
dfs(v_atl, row, n-1, heights[row][n-1]) # Last column
# Co-ordinates which can reach both the oceans are the winners
# so we take intersection
result = v_atl.intersection(v_pac)
return result | pacific-atlantic-water-flow | Clean python code O(mn) - DFS | Arvindn | 6 | 911 | pacific atlantic water flow | 417 | 0.541 | Medium | 7,436 |
https://leetcode.com/problems/pacific-atlantic-water-flow/discuss/2321368/Python-DFS-Beats-99.13-with-full-working-explanation | class Solution:
def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]: # Time: O(mn) and Space: O(mn)
rows, cols = len(heights), len(heights[0])
pac, atl = set(), set()
def dfs(r, c, visit, prevHeight): # current location, set of already visited tiles, the value of the tile where we are calling the dfs function
# we will check if the index[r, c] is not already visited, row and column is inbounds and
# the current tile should be lower than from we are coming from, it's the condition for waterflow mentioned
# if any one of these conditions fails exit the dfs by returning to from we came from
if (r, c) in visit or r < 0 or c < 0 or r == rows or c == cols or heights[r][c] < prevHeight:
return
visit.add((r, c)) # mark the tile visited(pac or atl depending on what is passed from the dfs function) when the if conditions true
dfs(r + 1, c, visit, heights[r][c]) # we will next visit the tile down from the current one
dfs(r - 1, c, visit, heights[r][c]) # up
dfs(r, c + 1, visit, heights[r][c]) # right
dfs(r, c - 1, visit, heights[r][c]) # left
for c in range(cols): # we will traverse the first & last row by fixing the r and moving c
dfs(0, c, pac, heights[0][c]) # first row is just next to pacific
dfs(rows - 1, c, atl, heights[rows - 1][c]) # last row is just next to atlantic
for r in range(rows): # we will traverse the first & last column by fixing the c and moving r
dfs(r, 0, pac, heights[r][0]) # first column is just next to pacific
dfs(r, cols - 1, atl, heights[r][cols - 1]) # last column is just next to atlantic
return list(pac.intersection(atl)) # returns the list which contains the same [i, j] in both the sets | pacific-atlantic-water-flow | Python [DFS / Beats 99.13%] with full working explanation | DanishKhanbx | 5 | 343 | pacific atlantic water flow | 417 | 0.541 | Medium | 7,437 |
https://leetcode.com/problems/pacific-atlantic-water-flow/discuss/2694838/Python-or-BFS | class Solution:
def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:
ROWS, COLS = len(heights), len(heights[0])
pacificQueue, atlanticQueue = deque(), deque()
for col in range(COLS):
pacificQueue.append((0, col, heights[0][col]))
atlanticQueue.append((ROWS-1, col, heights[ROWS-1][col]))
for row in range(ROWS):
pacificQueue.append((row, 0, heights[row][0]))
atlanticQueue.append((row, COLS-1, heights[row][COLS-1]))
directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
def bfs(queue):
reachable = set()
while queue:
for _ in range(len(queue)):
r, c, level = queue.popleft()
reachable.add((r, c))
for dr, dc in directions:
nr, nc = r + dr, c + dc
if (nr < 0 or nr >= ROWS or
nc < 0 or nc >= COLS or
heights[nr][nc] < level or
(nr, nc) in reachable):
continue
queue.append((nr, nc, heights[nr][nc]))
return reachable
atlanticReachable = bfs(atlanticQueue)
pacificReachable = bfs(pacificQueue)
return list(atlanticReachable.intersection(pacificReachable)) | pacific-atlantic-water-flow | Python | BFS | seangohck | 3 | 149 | pacific atlantic water flow | 417 | 0.541 | Medium | 7,438 |
https://leetcode.com/problems/pacific-atlantic-water-flow/discuss/2694838/Python-or-BFS | class Solution:
def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:
ROWS, COLS = len(heights), len(heights[0])
def dfs(r, c, prev_height):
if r < 0 or c < 0 or r == ROWS or c == COLS or heights[r][c] < prev_height or (r, c) in reachable:
return
reachable.add((r, c))
for dr, dc in [(0, 1), (1, 0), (0, -1), (-1, 0)]:
dfs(r + dr, c + dc, heights[r][c])
reachable = set()
for r in range(ROWS):
for c in range(COLS):
if r == 0 or c == 0:
dfs(r, c, -1)
pacific_reachable = reachable
reachable = set()
for r in range(ROWS):
for c in range(COLS):
if r == ROWS - 1 or c == COLS - 1:
dfs(r, c, -1)
atlantic_reachable = reachable
return list(pacific_reachable.intersection(atlantic_reachable)) | pacific-atlantic-water-flow | Python | BFS | seangohck | 3 | 149 | pacific atlantic water flow | 417 | 0.541 | Medium | 7,439 |
https://leetcode.com/problems/pacific-atlantic-water-flow/discuss/1203469/Python-BFS-Time-and-Space-O(M*N) | class Solution:
def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:
if not heights or not heights[0]:
return []
row, col = len(heights), len(heights[0])
pacific_queue = deque([(r, c) for r in range(row) for c in range(col) if (r == 0) or (c == 0)])
atlantic_queue = deque([(r, c) for r in range(row) for c in range(col) if (r == row-1) or (c == col-1)])
def _bfs_helper(queue):
nonlocal row, col
visited, directions = set(), [(-1, 0), (1, 0), (0, 1), (0, -1)]
while queue:
x, y = queue.popleft()
visited.add((x, y))
for d in directions:
dx, dy = d[0] + x, d[1] + y
# check bounds
if 0 <= dx < row and 0 <= dy < col and (dx, dy) not in visited and heights[dx][dy] >= heights[x][y]:
queue.append((dx, dy))
visited.add((dx, dy))
return visited
pacific_visited = _bfs_helper(pacific_queue)
atlantic_visited = _bfs_helper(atlantic_queue)
return list(pacific_visited.intersection(atlantic_visited)) | pacific-atlantic-water-flow | Python BFS - Time & Space O(M*N) | ChidinmaKO | 2 | 476 | pacific atlantic water flow | 417 | 0.541 | Medium | 7,440 |
https://leetcode.com/problems/pacific-atlantic-water-flow/discuss/2509465/python-solution-using-BFS | class Solution:
def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:
res2=set()
n,m=len(heights),len(heights[0])
def check(pair):
vis=set()
pacific=False
atlantic=False
qu=deque([pair])
moves=[(1,0),(0,1),(-1,0),(0,-1)]
while qu:
r=len(qu)
for i in range(r):
temp=qu.popleft()
if temp in res2:
return True
if temp[0]==0 or temp[1]==0:
pacific=True
if temp[0]==n-1 or temp[1]==m-1:
atlantic=True
if atlantic and pacific:
return True
for move in moves:
rw=temp[0]+move[0]
cl=temp[1]+move[1]
if rw in range(n) and cl in range(m):
if heights[rw][cl]<=heights[temp[0]][temp[1]] and (rw,cl) not in vis:
qu.append((rw,cl))
vis.add((rw,cl))
return False
res=[]
for i in range(n):
for j in range(m):
if check((i,j)):
res.append([i,j])
res2.add((i,j))
return res | pacific-atlantic-water-flow | python solution using BFS | benon | 1 | 75 | pacific atlantic water flow | 417 | 0.541 | Medium | 7,441 |
https://leetcode.com/problems/pacific-atlantic-water-flow/discuss/2161314/simple-dfs-beats-98 | class Solution:
def pacificAtlantic(self, board: List[List[int]]) -> List[List[int]]:
def reachable(stack, visited):
while(stack):
node = stack.pop()
if node not in visited:
visited[node] = True
x, y = node
if x - 1 >= 0:
if (x-1, y) not in visited and board[x-1][y] >= board[x][y]:
stack.append((x-1, y))
if x + 1 < len(board):
if (x+1, y) not in visited and board[x+1][y] >= board[x][y]:
stack.append((x+1, y))
if y - 1 >= 0:
if (x, y-1) not in visited and board[x][y-1] >= board[x][y]:
stack.append((x, y-1))
if y + 1 < len(board[0]):
if (x, y+1) not in visited and board[x][y+1] >= board[x][y]:
stack.append((x, y+1))
visited = {}
stack = []
for j in range(len(board[0])):
stack.append((0, j))
for i in range(len(board)):
stack.append((i, 0))
reachable(stack, visited)
reachable_pacific = set(list(visited.keys()))
stack.clear()
visited.clear()
for j in range(len(board[0])):
stack.append((len(board)-1, j))
for i in range(len(board)):
stack.append((i, len(board[0])-1))
reachable(stack, visited)
reachable_atlantic = set(list(visited.keys()))
reachable_both = reachable_pacific & reachable_atlantic
return reachable_both | pacific-atlantic-water-flow | simple dfs beats 98% | gabhinav001 | 1 | 85 | pacific atlantic water flow | 417 | 0.541 | Medium | 7,442 |
https://leetcode.com/problems/pacific-atlantic-water-flow/discuss/2117317/python-3-oror-simple-dfs | class Solution:
def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:
m, n = len(heights), len(heights[0])
pac, atl = set(), set()
def dfs(i, j, visited, prevHeight):
if (i, j) in visited or heights[i][j] < prevHeight:
return
visited.add((i, j))
if i != m - 1:
dfs(i + 1, j, visited, heights[i][j])
if i != 0:
dfs(i - 1, j, visited, heights[i][j])
if j != n - 1:
dfs(i, j + 1, visited, heights[i][j])
if j != 0:
dfs(i, j - 1, visited, heights[i][j])
for i in range(m):
dfs(i, 0, pac, 0)
dfs(i, n - 1, atl, 0)
for j in range(n):
dfs(0, j, pac, 0)
dfs(m - 1, j, atl, 0)
return list(map(list, pac.intersection(atl))) | pacific-atlantic-water-flow | python 3 || simple dfs | dereky4 | 1 | 202 | pacific atlantic water flow | 417 | 0.541 | Medium | 7,443 |
https://leetcode.com/problems/pacific-atlantic-water-flow/discuss/1829555/Python-clean-dfs-solution | class Solution:
def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:
pac, atl = set(), set()
rows, cols = len(heights), len(heights[0])
def dfs(r, c, visited, prevHeight):
if r < 0 or r >= rows or c < 0 or c >= cols or (r,c) in visited or heights[r][c] < prevHeight:
return
visited.add((r,c))
dfs(r-1,c,visited,heights[r][c])
dfs(r+1,c,visited,heights[r][c])
dfs(r,c-1,visited,heights[r][c])
dfs(r,c+1,visited,heights[r][c])
for r in range(rows):
# col = 0, pacific
dfs(r, 0, pac, heights[r][0])
# col = cols-1, atlantic
dfs(r, cols - 1, atl, heights[r][cols-1])
for c in range(cols):
# row = 0, pacific
dfs(0, c, pac, heights[0][c])
# row = rows-1, atlantic
dfs(rows - 1, c, atl, heights[rows-1][c])
return list(pac.intersection(atl)) | pacific-atlantic-water-flow | Python clean dfs solution | johnnychang | 1 | 158 | pacific atlantic water flow | 417 | 0.541 | Medium | 7,444 |
https://leetcode.com/problems/pacific-atlantic-water-flow/discuss/1503405/Well-Coded-oror-Easy-to-Understand-oror-For-Beginner-(DP) | class Solution:
def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:
m,n = len(heights),len(heights[0])
pacific = [[-1 for _ in range(n)] for _ in range(m)]
atlantic= [[-1 for _ in range(n)] for _ in range(m)]
def isValid(i,j):
if 0<=i<m and 0<=j<n:
return True
return False
def isPacBorder(i,j):
if i==0 or j==0:
return True
return False
def isAtlanticBorder(i,j):
if i==m-1 or j==n-1:
return True
return False
def dfs(dp,i,j,flag,seen): # flag==1 it means dp is pacific, and flag==0 means dp is atlantic.
if isValid(i,j) and (i,j) not in seen:
if flag==1 and isPacBorder(i,j):
dp[i][j] = "#"
return 1
if flag==0 and isAtlanticBorder(i,j):
dp[i][j] = "*"
return 1
if dp[i][j]=="#" or dp[i][j]=="*":
return 1
seen.add((i,j))
if isValid(i+1,j) and heights[i+1][j]<=heights[i][j] and dfs(dp,i+1,j,flag,seen):
dp[i][j] = "#" if flag==1 else "*"
if isValid(i-1,j) and heights[i-1][j]<=heights[i][j] and dfs(dp,i-1,j,flag,seen):
dp[i][j] = "#" if flag==1 else "*"
if isValid(i,j+1) and heights[i][j+1]<=heights[i][j] and dfs(dp,i,j+1,flag,seen):
dp[i][j] = "#" if flag==1 else "*"
if isValid(i,j-1) and heights[i][j-1]<=heights[i][j] and dfs(dp,i,j-1,flag,seen):
dp[i][j] = "#" if flag==1 else "*"
seen.remove((i,j))
if dp[i][j]=="#" or dp[i][j]=="*":
return 1
return 0
res = []
for i in range(m):
for j in range(n):
if pacific[i][j]!="#":
dfs(pacific,i,j,1,set())
if atlantic[i][j]!="*":
dfs(atlantic,i,j,0,set())
if pacific[i][j]=="#" and atlantic[i][j]=="*":
res.append([i,j])
return res | pacific-atlantic-water-flow | 📌📌 Well-Coded || Easy-to-Understand || For-Beginner (DP) 🐍 | abhi9Rai | 1 | 191 | pacific atlantic water flow | 417 | 0.541 | Medium | 7,445 |
https://leetcode.com/problems/pacific-atlantic-water-flow/discuss/838783/Python3-flood-fill | class Solution:
def pacificAtlantic(self, matrix: List[List[int]]) -> List[List[int]]:
if not matrix: return [] # edge case
m, n = len(matrix), len(matrix[0])
ans = [[0]*n for _ in matrix]
def dfs(i, j, v):
"""Flood fill matrix with given value."""
if ans[i][j] >= v: return
ans[i][j] += v # mark visited
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 matrix[ii][jj] >= matrix[i][j]: dfs(ii, jj, v)
# flood fill pacific with "1"
for j in range(n): dfs(0, j, 1)
for i in range(m): dfs(i, 0, 1)
# flood fill atlantic with "2"
for j in range(n): dfs(m-1, j, 2)
for i in range(m): dfs(i, n-1, 2)
return [[i, j] for i in range(m) for j in range(n) if ans[i][j] == 3] | pacific-atlantic-water-flow | [Python3] flood fill | ye15 | 1 | 224 | pacific atlantic water flow | 417 | 0.541 | Medium | 7,446 |
https://leetcode.com/problems/pacific-atlantic-water-flow/discuss/2837489/Python-3-BFS-fast-and-very-simple-solution | class Solution:
def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:
def find_ocean_cells(arr):
visited, queue = set(), deque()
queue.extend(arr)
directions = [[-1, 0], [0, -1], [1, 0], [0, 1]]
while queue:
r, c, prv_v = queue.popleft()
if (r, c) in visited: continue
if heights[r][c] < prv_v: continue
# add to set cell whose value is equal or bigger
# than value of previous cell
visited.add((r,c))
for dlt_r, dlt_c in directions:
if 0 <= r + dlt_r < row_n and \
0 <= c + dlt_c < col_n:
queue.append([r + dlt_r, c + dlt_c, heights[r][c]])
return visited
row_n = len(heights)
col_n = len(heights[0])
# boarders of Pacific Ocean, format: [cell row, cell column, cell value]
borders = []
borders.extend([[0, c, heights[0][c]] for c in range(col_n)]) # top boarder
borders.extend([[r, 0, heights[r][0]] for r in range(row_n)]) # left boarder
pacific_set = find_ocean_cells(borders) # get set with cells of Pacific Ocean
# boarders of Atlantic Ocean , format: [cell row, cell column, cell value]
borders.clear()
borders.extend([[row_n - 1, c, heights[row_n - 1][c]] for c in range(col_n)]) # bottom boarder
borders.extend([[r, col_n - 1, heights[r][col_n - 1]] for r in range(row_n)]) # right boarder
atlantic_set = find_ocean_cells(borders) # get set with cells of Atlantic Ocean
return pacific_set & atlantic_set # find intersection of pacific cells and atlantic cells | pacific-atlantic-water-flow | Python 3 - BFS - fast and very simple solution | noob_in_prog | 0 | 4 | pacific atlantic water flow | 417 | 0.541 | Medium | 7,447 |
https://leetcode.com/problems/pacific-atlantic-water-flow/discuss/2797686/Basic-DFS | class Solution:
def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:
#Pacific contains all the coordinates of Pacific ocean
#Atlantic contains all coordinates of Atlantic Ocean
pacific_ocean = set()
atlantic_ocean = set()
ans = []
#if pacific = first row, first column
rows = len(heights)
cols = len(heights[0])
for i in range(len(heights)):
for j in range(len(heights[0])):
if i == 0 or j == 0:
pacific_ocean.add((i,j))
if i == len(heights)-1 or j == len(heights[0])-1:
atlantic_ocean.add((i,j))
#helps to track movable places
def movable(i,j):
move_lst = [[0,1],[1,0],[0,-1],[-1,0]]
lst = []
for position in move_lst:
n_r = position[0] + i
n_cl = position[1]+j
if 0 <= n_r<rows and 0 <= n_cl<cols and heights[i][j] >= heights[n_r][n_cl]:
lst.append([n_r,n_cl])
return lst
#traverse the graph.
print(pacific_ocean)
def dfs(i,j,atlantic_ocean,pacific_ocean):
atlantic = False
pacific= False
stack = [[i,j]]
visited = set()
while stack:
row,col = stack.pop()
visited.add((row,col))
coord = (row,col)
if coord in pacific_ocean:
pacific = True
if coord in atlantic_ocean:
atlantic = True
if atlantic == True and pacific == True:
return True
neighbours = movable(row,col)
for neighbour in neighbours:
if (neighbour[0],neighbour[1]) not in visited:
stack.append(neighbour)
for i in range(len(heights)):
for j in range(len(heights[0])):
if dfs(i,j,atlantic_ocean,pacific_ocean) == True:
ans.append([i,j])
return ans | pacific-atlantic-water-flow | Basic DFS | fellowshiptech | 0 | 9 | pacific atlantic water flow | 417 | 0.541 | Medium | 7,448 |
https://leetcode.com/problems/pacific-atlantic-water-flow/discuss/2738711/DFS-searching-backwards | class Solution:
def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:
ROWS, COLS = len(heights), len(heights[0])
pac, atl = set(), set()
def dfs(r, c, visited, prev_height):
# base case
if ((r, c) in visited or
r < 0 or c < 0 or r == ROWS or c == COLS or
prev_height > heights[r][c]):
return
# recursive case
visited.add((r, c))
dfs(r + 1, c, visited, prev_height=heights[r][c])
dfs(r - 1, c, visited, prev_height=heights[r][c])
dfs(r, c + 1, visited, prev_height=heights[r][c])
dfs(r, c - 1, visited, prev_height=heights[r][c])
for c in range(COLS):
dfs(0, c, pac, heights[0][c])
dfs(ROWS - 1, c, atl, heights[ROWS - 1][c])
for r in range(ROWS):
dfs(r, 0, pac, heights[r][0])
dfs(r, COLS - 1, atl, heights[r][COLS - 1])
res = []
for r in range(ROWS):
for c in range(COLS):
if (r, c) in atl and (r, c) in pac:
res.append([r, c])
return res | pacific-atlantic-water-flow | DFS searching backwards | meechos | 0 | 7 | pacific atlantic water flow | 417 | 0.541 | Medium | 7,449 |
https://leetcode.com/problems/pacific-atlantic-water-flow/discuss/2713300/Python-or-A-different-approach-from-most-or-Memory-efficient | class Solution:
def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:
if not heights or not heights[0]:
return []
nrows = len(heights)
ncols = len(heights[0])
visited = set()
def dfs(r,c,ocean):
nonlocal visited
# Return True if it reaches leftmost col or topmost row for Pacific Ocean only
if (r == 0 or c == 0) and ocean == 0:
return True
# Return True if it reaches rightmost col or bottommost row for Atlantic Ocean only
if (r == nrows-1 or c == ncols-1) and ocean == 1:
return True
if r < 0 or r >= nrows or c < 0 or c >= ncols:
return False
visited.add((r,c))
height = heights[r][c]
for rowOffset, colOffset in [(0, 1), (-1, 0), (0, -1), (1, 0)]:
new_row = r + rowOffset
new_col = c + colOffset
if new_row >= 0 and new_row < nrows and new_col >= 0 and new_col < ncols and (new_row,new_col) not in visited:
neighbor_height = heights[new_row][new_col]
if neighbor_height <= height and dfs(new_row, new_col,ocean):
return True
return False
# 0 - Pacific
# 1 - Atlantic
res = []
for row in range(nrows):
for col in range(ncols):
# Reset visited for every dfs
visited = set()
if dfs(row,col,0):
visited = set()
if dfs(row,col,1):
res.append((row,col))
return res | pacific-atlantic-water-flow | Python | A different approach from most | Memory efficient | asangariu | 0 | 11 | pacific atlantic water flow | 417 | 0.541 | Medium | 7,450 |
https://leetcode.com/problems/pacific-atlantic-water-flow/discuss/2673685/Easy-to-Understand | class Solution:
def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:
m = len(heights)
n = len(heights[0])
def getEdges(i, j):
possibleEdges = [(i-1,j),(i, j+1), (i+1,j), (i, j-1)]
edges = []
for e in possibleEdges:
x = e[0]
y = e[1]
if x >=0 and y >=0 and x < m and y < n:
current = heights[i][j]
target = heights[x][y]
if target >= current:
edges.append(e)
return edges
canFlowToPacific = set()
canFlowToAtlantic = set()
for i in range(n):
canFlowToPacific.add((0, i))
canFlowToAtlantic.add((m-1, i))
for i in range(m):
canFlowToPacific.add((i,0))
canFlowToAtlantic.add((i, n-1))
def searchFlowToAtlantic(h):
if h in visited:
return
visited.add(h)
if not h in canFlowToAtlantic:
canAlsoFlowToAtlantic.add(h)
edges = getEdges(h[0], h[1])
if edges != None:
for e in edges:
searchFlowToAtlantic(e)
def searchFlowToPacific(h):
if h in visited:
return
visited.add(h)
if not h in canFlowToPacific:
canAlsoFlowToPacific.add(h)
edges = getEdges(h[0], h[1])
if edges != None:
for e in edges:
searchFlowToPacific(e)
visited = set()
canAlsoFlowToAtlantic = set()
for h in canFlowToAtlantic:
searchFlowToAtlantic(h)
visited.clear()
canAlsoFlowToPacific = set()
for h in canFlowToPacific:
searchFlowToPacific(h)
canFlowToAtlantic.update(canAlsoFlowToAtlantic)
canFlowToPacific.update(canAlsoFlowToPacific)
return canFlowToAtlantic.intersection(canFlowToPacific) | pacific-atlantic-water-flow | Easy to Understand | lalit84 | 0 | 6 | pacific atlantic water flow | 417 | 0.541 | Medium | 7,451 |
https://leetcode.com/problems/pacific-atlantic-water-flow/discuss/2509857/Python-Solution-or-DFS | class Solution:
def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:
n=len(heights)
m=len(heights[0])
if n==1 and m==1 and heights[n-1][m-1]>=1:
return [[0,0]]
ans=[]
rVector=[-1, 0, 1, 0]
cVector=[0, 1, 0, -1]
pacific=[[0]*m for i in range(n)]
atlantic=[[0]*m for i in range(n)]
def checkPacific(r, c, pacific, prev):
if r<0 or r>n-1 or c<0 or c>m-1:
return
if heights[r][c]<prev:
return
if pacific[r][c]:
return
pacific[r][c]=1
for i in range(4):
row=r+rVector[i]
col=c+cVector[i]
checkPacific(row, col, pacific, heights[r][c])
def checkAtlantic(r, c, atlantic, prev):
if r<0 or r>n-1 or c<0 or c>m-1:
return
if heights[r][c]<prev:
return
if atlantic[r][c]:
return
atlantic[r][c]=1
for i in range(4):
row=r+rVector[i]
col=c+cVector[i]
checkAtlantic(row, col, atlantic, heights[r][c])
return
for i in range(n):
for j in range(m):
if i==0 or j==0:
checkPacific(i, j, pacific, 0)
if i==n-1 or j==m-1:
checkAtlantic(i, j, atlantic, 0)
for i in range(n):
for j in range(m):
if pacific[i][j] and atlantic[i][j]:
ans.append([i,j])
return ans | pacific-atlantic-water-flow | Python Solution | DFS | Siddharth_singh | 0 | 28 | pacific atlantic water flow | 417 | 0.541 | Medium | 7,452 |
https://leetcode.com/problems/pacific-atlantic-water-flow/discuss/2508805/288-ms-faster-than-94.48-of-Python3 | class Solution:
def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:
pac, atl = set(), set()
rows, cols = len(heights), len(heights[0])
def dfs(r, c, visited, prevHeight):
if (r, c) in visited or r < 0 or r == rows or c < 0 or c == cols or prevHeight > heights[r][c]:
return
visited.add((r, c))
dfs(r+1, c, visited, heights[r][c])
dfs(r-1, c, visited, heights[r][c])
dfs(r, c+1, visited, heights[r][c])
dfs(r, c-1, visited, heights[r][c])
for j in range(cols):
dfs(0, j, pac, heights[0][j])
dfs(rows-1, j, atl, heights[rows-1][j])
for i in range(rows):
dfs(i, 0, pac, heights[i][0])
dfs(i, cols-1, atl, heights[i][cols-1])
res = []
for i in range(rows):
for j in range(cols):
if (i, j) in pac and (i, j) in atl:
res.append([i, j])
return res | pacific-atlantic-water-flow | 288 ms, faster than 94.48% of Python3 | sagarhasan273 | 0 | 28 | pacific atlantic water flow | 417 | 0.541 | Medium | 7,453 |
https://leetcode.com/problems/pacific-atlantic-water-flow/discuss/2508740/Python-DFS-from-Water-Verbose-but-readable-solution | class Solution:
def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:
# we could start from every outside cell (every ocean) and keep track
# of cells that are reachable from this cell
# once we did that for both oceans, we can intersect these sets and
# have the result
# make the two sets
atlantic_set = set()
pacific_set = set()
# get the size information
m = len(heights)
n = len(heights[0])
# iterate over all cells left and right of the matrix
for rx in range(m):
# to the left is the pacific ocean
dfs(rx, 0, -1, heights, pacific_set)
# to the right is the atlantic ocean
dfs(rx, n-1, -1, heights, atlantic_set)
# iterate over all cells up and down of the matrix
for cx in range(n):
# above the matrix is the pacific ocean
dfs(0, cx, -1, heights, pacific_set)
# below the matrix is the atlantic ocean
dfs(m-1, cx, -1, heights, atlantic_set)
return atlantic_set.intersection(pacific_set)
def dfs(rx, cx, last_height, heights, correct_set):
# check whether we are out of bounds
if not (0 <= rx < len(heights)) or not (0 <= cx < len(heights[0])):
return
# check whether our current position is already in the set
if (rx, cx) in correct_set:
return
# get our current height
current_height = heights[rx][cx]
# add our position to the set if we are higher than the last height
if current_height >= last_height:
correct_set.add((rx, cx))
else:
return
# go further in all directions
for new_rx, new_cx in yield_new_position(rx, cx):
# go further
dfs(new_rx, new_cx, current_height, heights, correct_set)
def yield_new_position(rx, cx):
# we use a generate to iterate over all directions
# this makes the code in the dfs function more readable
new_pos = [(rx+1, cx), (rx-1, cx), (rx, cx+1), (rx, cx-1)]
for new_rx, new_cx in new_pos:
yield new_rx, new_cx | pacific-atlantic-water-flow | [Python] - DFS from Water - Verbose but readable solution | Lucew | 0 | 17 | pacific atlantic water flow | 417 | 0.541 | Medium | 7,454 |
https://leetcode.com/problems/pacific-atlantic-water-flow/discuss/2508351/Easy-to-follow-python3-solution-with-complexity-analysis | class Solution:
# O(n) time,
# O(n) space,
# Approach: BFS, reverse thinking, hashset, matrix
def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:
n = len(heights)
m = len(heights[0])
def bfs(qu: Deque) -> Set[int]:
vstd = set()
for cell in qu:
vstd.add(cell)
while qu:
n = len(qu)
for i in range(n):
cell = qu.popleft()
nbrs = getNeighbours(cell)
for nb in nbrs:
if nb in vstd: continue
qu.append(nb)
vstd.add(nb)
return vstd
def getNeighbours(cell: List[int]) -> List[List[int]]:
n = len(heights)
m = len(heights[0])
neighbours = []
x, y = cell
cell_height = heights[x][y]
if x > 0 and heights[x-1][y] >= cell_height:
neighbours.append((x-1, y))
if y > 0 and heights[x][y-1] >= cell_height:
neighbours.append((x, y-1))
if x < n-1 and heights[x+1][y] >= cell_height:
neighbours.append((x+1, y))
if y < m-1 and heights[x][y+1] >= cell_height:
neighbours.append((x, y+1))
return neighbours
pacific_borders = deque()
for i in range(m):
pacific_borders.append((0, i))
for j in range(n):
pacific_borders.append((j, 0))
pacific_reachables = bfs(pacific_borders)
atlantic_borders = deque()
for i in range(m):
atlantic_borders.append((n-1, i))
for j in range(n):
atlantic_borders.append((j, m-1))
atlantic_reachables = bfs(atlantic_borders)
result = []
for cell in atlantic_reachables:
if cell in pacific_reachables:
result.append([cell[0], cell[1]])
return result | pacific-atlantic-water-flow | Easy to follow python3 solution with complexity analysis | destifo | 0 | 7 | pacific atlantic water flow | 417 | 0.541 | Medium | 7,455 |
https://leetcode.com/problems/pacific-atlantic-water-flow/discuss/2508088/GolangPython-O(N*M)-time-or-O(N*M)-space | class Solution:
def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:
pacific = set()
for i in range(len(heights[0])):
dfs(len(heights)-1,i,-1,pacific,heights)
for i in range(len(heights)):
dfs(i,len(heights[0])-1,-1,pacific,heights)
atlantic = set()
for i in range(len(heights[0])):
dfs(0,i,-1,atlantic,heights)
for i in range(len(heights)):
dfs(i,0,-1,atlantic,heights)
return pacific.intersection(atlantic)
def dfs(row,col,prev_height,ocean,heights):
if row < 0 or row >=len(heights):
return
if col < 0 or col >= len(heights[0]):
return
if (row,col) in ocean:
return
curr_height = heights[row][col]
if curr_height < prev_height:
return
ocean.add((row,col))
dfs(row-1,col,curr_height,ocean,heights)
dfs(row+1,col,curr_height,ocean,heights)
dfs(row,col-1,curr_height,ocean,heights)
dfs(row,col+1,curr_height,ocean,heights) | pacific-atlantic-water-flow | Golang/Python O(N*M) time | O(N*M) space | vtalantsev | 0 | 42 | pacific atlantic water flow | 417 | 0.541 | Medium | 7,456 |
https://leetcode.com/problems/pacific-atlantic-water-flow/discuss/2507781/Python-DFS | class Solution:
def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:
m = len(heights)
n = len(heights[0])
pacific_reachable = set()
atlantic_reachable = set()
def dfs(x, y, reachable):
reachable.add((x, y))
dirs = [(1, 0), (-1, 0), (0, 1), (0, -1)]
for x_delta, y_delta in dirs:
new_x = x + x_delta
new_y = y + y_delta
if 0 <= new_x < m and 0 <= new_y < n and heights[new_x][new_y] >= heights[x][y] and (new_x, new_y) not in reachable:
dfs(x + x_delta, y + y_delta, reachable)
for i in range(m):
dfs(i, 0, pacific_reachable)
dfs(i, n - 1, atlantic_reachable)
for j in range(n):
dfs(0, j, pacific_reachable)
dfs(m - 1, j, atlantic_reachable)
return list(pacific_reachable.intersection(atlantic_reachable)) | pacific-atlantic-water-flow | Python DFS | rylim | 0 | 20 | pacific atlantic water flow | 417 | 0.541 | Medium | 7,457 |
https://leetcode.com/problems/pacific-atlantic-water-flow/discuss/2507372/Python-DFS-from-borders | class Solution:
def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:
def dfs(r, c, seen):
seen.add((r, c))
h = heights[r][c]
for nr, nc in [(r-1, c), (r+1, c), (r, c-1), (r, c+1)]:
if (0 <= nr < m and 0 <= nc < n and
(nr, nc) not in seen and heights[nr][nc] >= h):
dfs(nr, nc, seen)
m, n = len(heights), len(heights[0])
pacific = set()
for c in range(n):
dfs(0, c, pacific)
for r in range(1, m):
dfs(r, 0, pacific)
atlantic = set()
for c in range(n):
dfs(m-1, c, atlantic)
for r in range(0, m-1):
dfs(r, n-1, atlantic)
return atlantic & pacific | pacific-atlantic-water-flow | Python, DFS from borders | blue_sky5 | 0 | 52 | pacific atlantic water flow | 417 | 0.541 | Medium | 7,458 |
https://leetcode.com/problems/pacific-atlantic-water-flow/discuss/2450777/Simple-DFS-solution | class Solution:
def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:
rows , cols = len(heights), len(heights[0])
pac , atl = set(), set()
def dfs(r, c , visit, preHeight):
if (r,c) in visit or r<0 or c< 0 or r>= rows or c>= cols or heights[r][c] < preHeight:
return
visit.add((r,c))
dfs(r+1,c, visit, heights[r][c])
dfs(r-1,c, visit, heights[r][c])
dfs(r,c-1, visit, heights[r][c])
dfs(r,c+1, visit, heights[r][c])
for c in range(cols):
dfs(0,c, pac,heights[0][c])
dfs(rows-1, c, atl , heights[rows-1][c])
for r in range(rows):
dfs(r,0 , pac, heights[r][0])
dfs(r, cols-1, atl, heights[r][cols-1])
res = []
for r in range(rows):
for c in range(cols):
if (r,c) in pac and (r,c) in atl:
res.append([r,c])
return res | pacific-atlantic-water-flow | Simple DFS solution | Abhi_009 | 0 | 101 | pacific atlantic water flow | 417 | 0.541 | Medium | 7,459 |
https://leetcode.com/problems/pacific-atlantic-water-flow/discuss/2242774/Python3-Efficient-Solution-oror-Iterative-DFS-and-BFS-Hashset-oror-TC-SC%3A-O(m-x-n)-oror-Clearly-Explained | class Solution:
def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:
num_row = len(heights)
num_col = len(heights[0])
pac = set()
atl = set()
def dfs(row, col, sea, height):
"""DFS traversal to mark which "land" is efficient for the water to flow from the sea into the land (increasing land's values)
@Param:
- row: row index
- col: col index
- sea: pacific or atlantic sea, used to mark if the land is eligible for water to flow
- height: height of the current land
"""
queue = collections.deque()
sea.add((row, col))
# we will keep track of the current land position and its height to check for condition below
queue.append((row, col, height))
# 4 directions - NEWS
directions = [[1,0], [-1,0], [0,1], [0,-1]]
# while there are still lands to be visited
while queue:
# get the row, col and height of the current (main) land
curr_row, curr_col, curr_height = queue.pop() # <<<<< if you want BFS, change this to queue.popleft()
# visit all 4 NEWS directions
for dr, dc in directions:
# update position
row = curr_row + dr
col = curr_col + dc
# check if the new land's position is in the bound and whether we have not visited it
if (row in range(num_row)) and (col in range(num_col)) and ((row, col) not in sea):
# here, it is en eligible land, calculate its height
height = heights[row][col]
# the new land (neighbor)'s height must be large than the previous (main) land's height
if height >= curr_height:
# marked we already visited it and put into the queue
sea.add((row, col))
queue.append((row, col, height))
# DFS from top and bottom row and mark which land able to have water flow to pacific or atlantic accordingly
for col in range(num_col):
dfs(0, col, pac, heights[0][col])
dfs(num_row - 1, col, atl, heights[num_row - 1][col])
# DFS from left and right row and mark which land able to have water flow to pacific or atlantic accordingly
for row in range(num_row):
dfs(row, 0, pac, heights[row][0])
dfs(row, num_col - 1, atl, heights[row][num_col - 1])
res = []
# visit each node and mark which land are able to water flow to pacific AND atlantic
for row in range(num_row):
for col in range(num_col):
if (row, col) in pac and (row, col) in atl:
res.append([row, col])
return res
# TC: O(m x n) - m is number of row, n is number of col. We only visit each position once
# SC: O(m x n) - 2 hashmaps to store which lands we have visited - same for the space occupied by the stack (or queue for BFS) | pacific-atlantic-water-flow | Python3 Efficient Solution || Iterative DFS & BFS, Hashset || TC, SC: O(m x n) || Clearly Explained | minheapolis | 0 | 78 | pacific atlantic water flow | 417 | 0.541 | Medium | 7,460 |
https://leetcode.com/problems/pacific-atlantic-water-flow/discuss/1919467/Python-oror-Solution | class Solution:
def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:
def calculate(x,i,j):
if 0<=i<len(heights) and 0<=j<len(heights[0]) and x[i][j]==0:
x[i][j] = 1
for r,c in [(-1,0),(0,-1),(1,0),(0,1)]:
newr = i+r
newc = j+c
if 0<=newr<len(heights) and 0<=newc<len(heights[0]) and x[newr][newc]==0:
if heights[newr][newc]>=heights[i][j]:
calculate(x,newr,newc)
return
ans = []
p = []
for i in range(len(heights)):
p.append([0 for i in range(len(heights[0]))])
a = []
for i in range(len(heights)):
a.append([0 for i in range(len(heights[0]))])
for i in range(len(heights[0])):
calculate(p,0,i)
calculate(a,len(heights)-1,i)
for i in range(len(heights)):
calculate(p,i,0)
calculate(a,i,len(heights[0])-1)
for i in range(len(heights)):
for j in range(len(heights[0])):
if p[i][j]==a[i][j]==1:
ans.append([i,j])
return ans | pacific-atlantic-water-flow | Python || Solution | Brillianttyagi | 0 | 98 | pacific atlantic water flow | 417 | 0.541 | Medium | 7,461 |
https://leetcode.com/problems/pacific-atlantic-water-flow/discuss/1850976/Python3-save-space-with-bit-operation | class Solution:
def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:
m = len(heights)
n = len(heights[0])
#result is a 2D grid that keeps track of both whether the cell can reach Atlantic
# and whether the cell can reach Pacific. The first bit is used to store whether the cell can
# reach Pacific and the second bit is used to store whether the cell can reach Atlantic
# e.g. 01(binary) = 1(decimal) can one reach Pacific
#. 11(binary) = 3(decimal) can reach both ocean
#. 10(binary) = 2(decimal) can only reach Atlantic
result = [[0 for i in range(n)] for j in range(m)]
# if the current height is higher than the height of last node, the water in the current cell can flow to the last cell
# when bit is 1, this function is used to determine whether the cell can flow to Pacific
# when bit is 2, this function is used to determine whether the cell can flow to Atlantic
def dfs(x,y,last_height,bit):
current_height = heights[x][y]
if current_height >= last_height and result[x][y]&bit == 0:
result[x][y] |= bit
for a,b in (x-1,y),(x+1,y),(x,y-1),(x,y+1):
if 0 <= a < m and 0<=b<n:
dfs(a,b,current_height,bit)
for i in range(n):
dfs(0,i,0,1)
for j in range(m):
dfs(j,0,0,1)
for i in range(n):
dfs(m-1,i,0,2)
for j in range(m):
dfs(j,n-1,0,2)
res = []
for i in range(m):
for j in range(n):
if result[i][j]&3 == 3:
res.append((i,j))
return res | pacific-atlantic-water-flow | Python3 save space with bit operation | Yihang-- | 0 | 30 | pacific atlantic water flow | 417 | 0.541 | Medium | 7,462 |
https://leetcode.com/problems/pacific-atlantic-water-flow/discuss/1773672/Python-BFS-using-bitmask | class Solution:
def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:
def bfs(q, ocean):
while q:
r, c = q.popleft()
for dr, dc in [(-1, 0), (1, 0), (0, 1), (0, -1)]:
nr, nc = r + dr, c + dc
if nr < 0 or nr >= m or nc < 0 or nc >= n:
continue
if heights[nr][nc] < heights[r][c]:
continue
if mask[nr][nc] & ocean:
continue
mask[nr][nc] |= ocean
if mask[nr][nc] == 3:
result.append([nr, nc])
q.append((nr, nc))
result = []
m, n = len(heights), len(heights[0])
mask = [[0] * n for _ in range(m)]
pacific = deque()
atlantic = deque()
for r in range(m):
pacific.append((r, 0))
mask[r][0] |= 1
atlantic.append((r, n - 1))
mask[r][n-1] |= 2
if mask[r][n-1] == 3:
result.append([r, n-1])
for c in range(1, n):
pacific.append((0, c))
mask[0][c] |= 1
if mask[0][c] == 3:
result.append([0, c])
atlantic.append((m-1, n - 1 - c))
mask[m-1][n - 1 - c] |= 2
if mask[m-1][n - 1 - c] == 3:
result.append([m-1, n - 1 - c])
bfs(pacific, ocean=1)
bfs(atlantic, ocean=2)
return result | pacific-atlantic-water-flow | Python BFS using bitmask | blue_sky5 | 0 | 49 | pacific atlantic water flow | 417 | 0.541 | Medium | 7,463 |
https://leetcode.com/problems/pacific-atlantic-water-flow/discuss/1755572/Python-DFS | class Solution:
def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:
def dfs(r, c, h, o):
if r < 0 or c < 0 or r == m or c == n:
return
if values[r][c] & o:
return
if heights[r][c] < h:
return
values[r][c] |= o
if values[r][c] == 3:
result.append([r, c])
h = heights[r][c]
dfs(r-1, c, h, o)
dfs(r+1, c, h, o)
dfs(r, c-1, h, o)
dfs(r, c+1, h, o)
m = len(heights)
n = len(heights[0])
result = []
values = [[0]*n for _ in range(m)]
for c in range(n):
dfs(0, c, 0, 1)
dfs(m-1, c, 0, 2)
for r in range(m):
dfs(r, 0, 0, 1)
dfs(r, n-1, 0, 2)
return result | pacific-atlantic-water-flow | Python, DFS | blue_sky5 | 0 | 233 | pacific atlantic water flow | 417 | 0.541 | Medium | 7,464 |
https://leetcode.com/problems/pacific-atlantic-water-flow/discuss/1532121/Py3Py-Solution-DFS-for-both-sides-w-comments | class Solution:
def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:
# Init
rows = len(heights)
cols = len(heights[0])
pacific = set()
atlantic = set()
# Helper functions
def inLimits(node):
return (0 <= node[0] < rows) and (0 <= node[1] < cols)
def directions(node):
r, c = node
return ((r,c-1),(r,c+1), (r-1,c), (r+1,c))
# DFS with reverse condition w.r.t the question
def dfs(stack: List, visited: Set, ocean: Set):
if stack:
node = stack.pop()
if node not in visited:
visited.add(node)
ocean.add(node)
for adj in directions(node):
if inLimits(adj) and heights[node[0]][node[1]] <= heights[adj[0]][adj[1]]:
stack.append(adj)
dfs(stack, visited, ocean)
return
# For pacific side
pacific_side = [(0, c) for c in range(cols)] + [(r,0) for r in range(rows)]
visited = set()
for node in pacific_side:
dfs([node], visited, pacific)
# For atlantic side
atlantic_side = [(rows-1, c) for c in range(cols)] + [(r,cols-1) for r in range(rows)]
visited = set()
for node in atlantic_side:
dfs([node], visited, atlantic)
# Get results from the intersection of both sides
results = []
for row,col in pacific.intersection(atlantic):
results.append([row, col])
# Sort results before returning
results.sort()
return results | pacific-atlantic-water-flow | [Py3/Py] Solution DFS for both sides w/ comments | ssshukla26 | 0 | 110 | pacific atlantic water flow | 417 | 0.541 | Medium | 7,465 |
https://leetcode.com/problems/pacific-atlantic-water-flow/discuss/1466050/WEEB-DOES-PYTHON-BFS | class Solution:
def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:
row, col = len(heights), len(heights[0])
pacific = deque([(0,i) for i in range(col)] + [(i,0) for i in range(row)])
atlantic = deque([(row-1,i) for i in range(col)] + [(i,col-1) for i in range(row)])
return self.bfs(heights, row, col, pacific).intersection(self.bfs(heights, row, col, atlantic))
def bfs(self, grid, row, col, queue):
visited = set()
while queue:
x,y = queue.popleft()
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[x][y]<=grid[nx][ny]:
queue.append((nx,ny))
return visited | pacific-atlantic-water-flow | WEEB DOES PYTHON BFS | Skywalker5423 | 0 | 102 | pacific atlantic water flow | 417 | 0.541 | Medium | 7,466 |
https://leetcode.com/problems/pacific-atlantic-water-flow/discuss/1449929/Python-Clean-DFS-and-BFS | class Solution:
def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:
def dfs(r, c, vis):
queue = deque([(r, c, vis)])
while queue:
r, c, vis = queue.pop()
for nr, nc in [(r-1, c), (r, c-1), (r, c+1), (r+1, c)]:
if nr in range(M) and nc in range(N) and heights[r][c] <= heights[nr][nc] and (nr, nc) not in vis:
vis.add((nr, nc))
queue.append((nr, nc, vis))
M, N = len(heights), len(heights[0])
pac, atl, result = set(), set(), []
for c in range(N):
dfs(0, c, pac), dfs(M-1, c, atl)
pac.add((0, c)), atl.add((M-1, c))
for r in range(M):
dfs(r, 0, pac), dfs(r, N-1, atl)
pac.add((r, 0)), atl.add((r, N-1))
for r in range(M):
for c in range(N):
if (r, c) in pac and (r, c) in atl:
result.append([r, c])
return result | pacific-atlantic-water-flow | [Python] Clean DFS & BFS | soma28 | 0 | 220 | pacific atlantic water flow | 417 | 0.541 | Medium | 7,467 |
https://leetcode.com/problems/pacific-atlantic-water-flow/discuss/1449929/Python-Clean-DFS-and-BFS | class Solution:
def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:
def bfs(r, c, vis):
queue = deque([(r, c, vis)])
while queue:
r, c, vis = queue.popleft()
for nr, nc in [(r-1, c), (r, c-1), (r, c+1), (r+1, c)]:
if nr in range(M) and nc in range(N) and heights[r][c] <= heights[nr][nc] and (nr, nc) not in vis:
vis.add((nr, nc))
queue.append((nr, nc, vis))
M, N = len(heights), len(heights[0])
pac, atl, result = set(), set(), []
for c in range(N):
bfs(0, c, pac), bfs(M-1, c, atl)
pac.add((0, c)), atl.add((M-1, c))
for r in range(M):
bfs(r, 0, pac), bfs(r, N-1, atl)
pac.add((r, 0)), atl.add((r, N-1))
for r in range(M):
for c in range(N):
if (r, c) in pac and (r, c) in atl:
result.append([r, c])
return result | pacific-atlantic-water-flow | [Python] Clean DFS & BFS | soma28 | 0 | 220 | pacific atlantic water flow | 417 | 0.541 | Medium | 7,468 |
https://leetcode.com/problems/pacific-atlantic-water-flow/discuss/1126721/python3-DFS | class Solution:
def pacificAtlantic(self, matrix: List[List[int]]) -> Set[Tuple[int, int]]:
if not matrix:
return set()
m, n = len(matrix), len(matrix[0])
def dfs(r: int, c: int, res: MutableSet[Tuple[int, int]]) -> None:
res.add((r, c))
for nr, nc in {(r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)} - res:
if 0 <= nr < m and 0 <= nc < n and matrix[nr][nc] >= matrix[r][c]:
dfs(nr, nc, res)
pacific, atlantic = set(), set()
for r in range(m):
dfs(r, 0, pacific)
dfs(r, n - 1, atlantic)
for c in range(n):
dfs(0, c, pacific)
dfs(m - 1, c, atlantic)
return pacific & atlantic | pacific-atlantic-water-flow | python3 DFS | mcolen | 0 | 131 | pacific atlantic water flow | 417 | 0.541 | Medium | 7,469 |
https://leetcode.com/problems/pacific-atlantic-water-flow/discuss/1807361/Python-3-DFS-From-Edge-to-Rest-of-Land | class Solution:
def flow(self, q: List[List[int]], canFlowFrom: List[List[bool]], heights: List[List[int]]):
# directions that we can water can flow from
directions = [[0, 1], [1, 0], [0, -1], [-1, 0]]
while len(q) != 0:
inds = q.pop(0)
for direction in directions:
i = inds[0] + direction[0]
j = inds[1] + direction[1]
# check if coordinates are valid and that they haven't been visited
if i >= 0 and j >= 0 and i < len(heights) and j < len(heights[i]) and heights[inds[0]][inds[1]] <= heights[i][j] and not canFlowFrom[i][j]:
# add coordinates to queue and acknowledge that we can flow to the ocean from [i, j]
q.append([i, j])
canFlowFrom[i][j] = True
def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:
m = len(heights)
n = len(heights[0])
flowToOcean = [[False] * n for i in range(m)]
oceanQ = []
# add left column touching ocean
for i in range(m):
oceanQ.append([i, 0])
flowToOcean[i][0] = True
# add top row touching ocean
for j in range(n):
oceanQ.append([0, j])
flowToOcean[0][j] = True
# flow from edges updwards to validate if can flow to specific ocean
self.flow(oceanQ, flowToOcean, heights)
res = []
for i in range(m):
for j in range(n):
# add coordinates that can flow to ocean
if flowToOcean[i][j]:
res.append([i, j])
return res | pacific-atlantic-water-flow | Python 3 DFS From Edge to Rest of Land | 9D76 | -1 | 69 | pacific atlantic water flow | 417 | 0.541 | Medium | 7,470 |
https://leetcode.com/problems/pacific-atlantic-water-flow/discuss/1807361/Python-3-DFS-From-Edge-to-Rest-of-Land | class Solution:
def flow(self, q: List[List[int]], canFlowFrom: List[List[bool]], heights: List[List[int]]):
# directions that we can water can flow from
directions = [[0, 1], [1, 0], [0, -1], [-1, 0]]
while len(q) != 0:
inds = q.pop(0)
for direction in directions:
i = inds[0] + direction[0]
j = inds[1] + direction[1]
# check if coordinates are valid and that they haven't been visited
if i >= 0 and j >= 0 and i < len(heights) and j < len(heights[i]) and heights[inds[0]][inds[1]] <= heights[i][j] and not canFlowFrom[i][j]:
q.append([i, j])
canFlowFrom[i][j] = True
def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:
m = len(heights)
n = len(heights[0])
flowToAtlantic = [[False] * n for i in range(m)]
flowToPacific = [[False] * n for i in range(m)]
atlanticQ = []
pacificQ = []
# add edges touching ocean
for i in range(m):
pacificQ.append([i, 0])
flowToPacific[i][0] = True
atlanticQ.append([i, n - 1])
flowToAtlantic[i][n - 1] = True
# add edges touching ocean
for j in range(n):
pacificQ.append([0, j])
flowToPacific[0][j] = True
atlanticQ.append([m - 1, j])
flowToAtlantic[m - 1][j] = True
# flow from edges updwards to validate if can flow to specific ocean for each coordinate
self.flow(atlanticQ, flowToAtlantic, heights)
self.flow(pacificQ, flowToPacific, heights)
res = []
for i in range(m):
for j in range(n):
# if we can reach both oceans, then we can add it to the result list
if flowToAtlantic[i][j] and flowToPacific[i][j]:
res.append([i, j])
return res | pacific-atlantic-water-flow | Python 3 DFS From Edge to Rest of Land | 9D76 | -1 | 69 | pacific atlantic water flow | 417 | 0.541 | Medium | 7,471 |
https://leetcode.com/problems/battleships-in-a-board/discuss/1523048/Simple-Easy-to-Understand-Python-O(1)-extra-memory | class Solution:
def countBattleships(self, board: List[List[str]]) -> int:
count = 0
for r in range(len(board)):
for c in range(len(board[0])):
if board[r][c] == 'X':
var = 1
if (r > 0 and board[r-1][c] == 'X') or (c > 0 and board[r][c-1] == 'X'):
var = 0
count += var
return count | battleships-in-a-board | Simple Easy to Understand Python O(1) extra memory | bshien | 9 | 638 | battleships in a board | 419 | 0.747 | Medium | 7,472 |
https://leetcode.com/problems/battleships-in-a-board/discuss/2523176/Python-or-O(NM)-one-liner-Solution-without-modifying-board | class Solution:
def countBattleships(self, board: List[List[str]]) -> int:
count = 0
for i, row in enumerate(board):
for j, cell in enumerate(row):
if cell == "X":
if (i == 0 or board[i - 1][j] == ".") and\
(j == 0 or board[i][j - 1] == "."):
count += 1
return count | battleships-in-a-board | Python | O(NM) one-liner Solution without modifying board | ahmadheshamzaki | 8 | 471 | battleships in a board | 419 | 0.747 | Medium | 7,473 |
https://leetcode.com/problems/battleships-in-a-board/discuss/2523176/Python-or-O(NM)-one-liner-Solution-without-modifying-board | class Solution:
def countBattleships(self, board: List[List[str]]) -> int:
return sum(1 for i, row in enumerate(board) for j, cell in enumerate(row) if cell == "X" and (i == 0 or board[i - 1][j] == ".") and (j == 0 or board[i][j - 1] == ".")) | battleships-in-a-board | Python | O(NM) one-liner Solution without modifying board | ahmadheshamzaki | 8 | 471 | battleships in a board | 419 | 0.747 | Medium | 7,474 |
https://leetcode.com/problems/battleships-in-a-board/discuss/461076/Python-3-(beats-~100)-(one-pass)-(-O(1)-space-)-(60-ms) | class Solution:
def countBattleships(self, B: List[List[str]]) -> int:
if not B[0]: return 0
M, N, t = len(B), len(B[0]), int(B[0][0] == 'X')
for i in range(1,M): t += (B[i-1][0],B[i][0]) == ('.','X')
for j in range(1,N): t += (B[0][j-1],B[0][j]) == ('.','X')
for i,j in itertools.product(range(1,M),range(1,N)): t += B[i][j] == 'X' and (B[i-1][j],B[i][j-1]) == ('.','.')
return t
- Junaid Mansuri
- Chicago, IL | battleships-in-a-board | Python 3 (beats ~100%) (one pass) ( O(1) space ) (60 ms) | junaidmansuri | 6 | 1,300 | battleships in a board | 419 | 0.747 | Medium | 7,475 |
https://leetcode.com/problems/battleships-in-a-board/discuss/838599/Python3-dfs | class Solution:
def countBattleships(self, board: List[List[str]]) -> int:
m, n = len(board), len(board[0])
def dfs(i, j):
"""Traverse the grids connected to (i, j)."""
board[i][j] = "." # mark as visited
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 board[ii][jj] == "X": dfs(ii, jj)
ans = 0
for i in range(m):
for j in range(n):
if board[i][j] == "X":
ans += 1
dfs(i, j)
return ans | battleships-in-a-board | [Python3] dfs | ye15 | 2 | 210 | battleships in a board | 419 | 0.747 | Medium | 7,476 |
https://leetcode.com/problems/battleships-in-a-board/discuss/838599/Python3-dfs | class Solution:
def countBattleships(self, board: List[List[str]]) -> int:
m, n = len(board), len(board[0])
ans = 0
for i in range(m):
for j in range(n):
if board[i][j] == 'X' and (i == 0 or board[i-1][j] == '.') and (j == 0 or board[i][j-1] == '.'):
ans += 1
return ans | battleships-in-a-board | [Python3] dfs | ye15 | 2 | 210 | battleships in a board | 419 | 0.747 | Medium | 7,477 |
https://leetcode.com/problems/battleships-in-a-board/discuss/1906684/Clean-intuitive-Python-O(1)-space-solution-explained | class Solution:
def countBattleships(self, board: List[List[str]]) -> int:
nrows = len(board)
ncols = len(board[0])
count = 0
for row, col in product(range(nrows), range(ncols)):
if board[row][col] == 'X':
if (row == nrows-1 or board[row+1][col] == '.') and (col == ncols-1 or board[row][col+1] == '.'):
count += 1
return count | battleships-in-a-board | Clean, intuitive Python, O(1) space, solution explained | boris17 | 1 | 114 | battleships in a board | 419 | 0.747 | Medium | 7,478 |
https://leetcode.com/problems/battleships-in-a-board/discuss/755605/Simple-Python-Recursive-DFS-beats-86-and-Iterative-BFS-with-Comments! | class Solution:
def countBattleships(self, board: List[List[str]]) -> int:
if not board: return 0
rows = len(board)
cols = len(board[0])
def helper(row, col):
# Make sure the point we're searching is valid if not return
if row >= rows or row < 0 or col >= cols or col < 0 or board[row][col] != 'X':
return
# Mark the location so we know not to count it again.
board[row][col] = '#'
# Search in our other possible directions.
helper(row + 1, col)
helper(row - 1, col)
helper(row, col + 1)
helper(row, col - 1)
res = 0
# Iterate through our grid looking for ships.
for row in range(rows):
for col in range(cols):
if board[row][col] == 'X':
helper(row, col)
# Once we've finished sinking the ship (changing the X's to #'s) add to the count.
res += 1
return res | battleships-in-a-board | Simple Python Recursive DFS beats 86% and Iterative BFS with Comments! | Pythagoras_the_3rd | 1 | 239 | battleships in a board | 419 | 0.747 | Medium | 7,479 |
https://leetcode.com/problems/battleships-in-a-board/discuss/755605/Simple-Python-Recursive-DFS-beats-86-and-Iterative-BFS-with-Comments! | class Solution:
def countBattleships(self, board: List[List[str]]) -> int:
if not board: return 0
rows = len(board)
cols = len(board[0])
directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]
res = 0
# Iterate through our board looking for ships 'X'.
for row in range(rows):
for col in range(cols):
# If we find one start searching from it's starting location.
if board[row][col] == 'X':
q = collections.deque([(row, col)])
# Fill the location to avoid revisiting it.
board[row][col] = '#'
while q:
r, c = q.popleft()
for y, x in directions:
# Create new row and col location to search based on our possible move directions.
nr = r + y
nc = c + x
# Make sure there coords. are valid, ie. on our board and contain an 'X'.
if nr < rows and nr >= 0 and nc < cols and nc >= 0 and board[nr][nc] == 'X':
# If so, we'll append to the deque and mark the location.
q.append((nr, nc))
board[nr][nc] = '#'
# When we get here we know we've found and marked to ship as being found so we count.
res += 1
return res | battleships-in-a-board | Simple Python Recursive DFS beats 86% and Iterative BFS with Comments! | Pythagoras_the_3rd | 1 | 239 | battleships in a board | 419 | 0.747 | Medium | 7,480 |
https://leetcode.com/problems/battleships-in-a-board/discuss/2358712/You-don't-need-to-move-in-Four-Directions.-Just-Two-Directional-Movements. | class Solution:
def countBattleships(self, board: List[List[str]]) -> int:
def isBound(row,col):
return 0<=row<len(board) and 0<=col<len(board[0])
DIR=[(1,0),(0,1)]
@lru_cache(None)
def dfs(row,col):
board[row][col]="."
for neighbor in DIR:
new_row = row + neighbor[0]
new_col = col + neighbor[1]
if isBound(new_row,new_col) and board[new_row][new_col]=="X":
dfs(new_row,new_col)
counter=0
for row in range(len(board)):
for col in range(len(board[0])):
if board[row][col]=="X":
counter+=1
dfs(row,col)
return counter | battleships-in-a-board | You don't need to move in Four Directions. Just Two Directional Movements. | Sefinehtesfa34 | 0 | 41 | battleships in a board | 419 | 0.747 | Medium | 7,481 |
https://leetcode.com/problems/battleships-in-a-board/discuss/1925260/Python3-DFS-solution-(with-comments) | class Solution:
def countBattleships(self, board: List[List[str]]) -> int:
pairs = []
#puts coords of X's in a list
for i,j in enumerate(board):
if 'X' in j:
for x, y in enumerate(j):
if y == 'X':
pairs.append((i,x))
ans = 0
#while pairs is not empty, do DFS with each pair
while pairs:
ans += 1
x, y = pairs[0]
pairs.pop(0)
pairs = self.DFS(pairs, x, y)
return ans
def DFS( temp, x, y) ->List:
if (x+1, y) in temp:
temp.remove((x+1, y))
self.DFS(temp, x+1, y)
elif (x-1, y) in temp:
temp.remove((x-1, y))
self.DFS(temp, x-1, y)
elif (x, y+1) in temp:
temp.remove((x, y+1))
self.DFS(temp, x, y+1)
elif (x, y-1) in temp:
temp.remove((x, y-1))
self.DFS(temp, x, y-1)
return temp | battleships-in-a-board | Python3 DFS solution (with comments) | ssonzeu | 0 | 73 | battleships in a board | 419 | 0.747 | Medium | 7,482 |
https://leetcode.com/problems/battleships-in-a-board/discuss/1912334/Python-Solution-(DFS) | class Solution:
def countBattleships(self, board: List[List[str]]) -> int:
rowlen = len(board)
collen = len(board[0])
def dfs(row,col,d):
board[row][col] = "#"
if (d == "all" or d == "U") and row-1 >= 0 and row-1 < rowlen and col >= 0 and col < collen and board[row-1][col] == "X":
dfs(row-1, col, "U")
if (d == "all" or d == "D") and row+1 >= 0 and row+1 < rowlen and col >= 0 and col < collen and board[row+1][col] == "X":
dfs(row+1, col, "D")
if (d == "all" or d == "R") and row >= 0 and row < rowlen and col+1 >= 0 and col+1 < collen and board[row][col+1] == "X":
dfs(row, col+1, "R")
if (d == "all" or d == "L") and row >= 0 and row < rowlen and col-1 >= 0 and col-1 < collen and board[row][col-1] == "X":
dfs(row, col-1, "L")
cnt = 0
for row in range(rowlen):
for col in range(collen):
if board[row][col] == "X":
cnt += 1
dfs(row,col,"all")
return cnt | battleships-in-a-board | Python Solution (DFS) | DietCoke777 | 0 | 70 | battleships in a board | 419 | 0.747 | Medium | 7,483 |
https://leetcode.com/problems/battleships-in-a-board/discuss/1762461/Python-easy-to-understand-or-DFS | class Solution:
def dfs(self, board, row, col):
if row < 0 or col < 0 or row == len(board) or col == len(board[0]) or board[row][col] != 'X':
return
board[row][col] = 'O'
self.dfs(board, row+1, col)
self.dfs(board, row, col+1)
def countBattleships(self, board: List[List[str]]) -> int:
ans = 0
m, n = len(board), len(board[0])
for i in range(m):
for j in range(n):
if board[i][j] == 'X':
ans += 1
self.dfs(board, i, j)
return ans | battleships-in-a-board | Python easy to understand | DFS | sanial2001 | 0 | 150 | battleships in a board | 419 | 0.747 | Medium | 7,484 |
https://leetcode.com/problems/battleships-in-a-board/discuss/1344826/WEEB-DOES-PYTHON | class Solution:
def countBattleships(self, board: List[List[str]]) -> int:
row, col = len(board), len(board[0])
queue = deque([])
count = 0
for x in range(row):
for y in range(col):
if board[x][y] == "X":
queue.append((x,y))
self.bfs(queue, row, col, board)
count += 1
return count
def bfs(self, queue, row, col, grid):
while queue:
x, y = queue.popleft()
grid[x][y] = "k"
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] == "X":
queue.append((nx,ny)) | battleships-in-a-board | WEEB DOES PYTHON | Skywalker5423 | 0 | 95 | battleships in a board | 419 | 0.747 | Medium | 7,485 |
https://leetcode.com/problems/battleships-in-a-board/discuss/640111/Intuitive-approach-by-looking-for-the-head-of-battleships | class Solution:
def countBattleships(self, board: List[List[str]]) -> int:
# 0) Initialization
count_of_bs = 0
''' count of battle ship'''
def is_head(r, c):
# Check if the given position is the head of battleships
if (r == 0 or board[r-1][c] == '.') and \
(c == 0 or board[r][c-1] == '.'):
print("Found head at ({},{})".format(r, c))
return True
return False
# 1) Run algorithm to look for number of battleships
R = len(board)
C = len(board[0])
for ri in range(R):
for ci in range(C):
if board[ri][ci] == 'X':
if is_head(ri, ci):
count_of_bs += 1
return count_of_bs | battleships-in-a-board | Intuitive approach by looking for the head of battleships | puremonkey2001 | 0 | 111 | battleships in a board | 419 | 0.747 | Medium | 7,486 |
https://leetcode.com/problems/battleships-in-a-board/discuss/340116/Python-solution-using-dictionary | class Solution:
def countBattleships(self, board: List[List[str]]) -> int:
count=0
d={}
for i in range(len(board)):
for j in range(len(board[i])):
if board[i][j]=='X':d[(i,j)]=1
l=list(d.keys())
while d:
k=l[0]
del[d[k]]
l.remove(k)
count+=1
if (k[0],k[1]+1) in d:
while (k[0],k[1]+1) in d:
del(d[(k[0],k[1]+1)])
k=(k[0],k[1]+1)
l.remove(k)
elif (k[0]+1,k[1]) in d:
while (k[0]+1,k[1]) in d:
del(d[(k[0]+1,k[1])])
k=(k[0]+1,k[1])
l.remove(k)
return count | battleships-in-a-board | Python solution using dictionary | ketan35 | 0 | 222 | battleships in a board | 419 | 0.747 | Medium | 7,487 |
https://leetcode.com/problems/battleships-in-a-board/discuss/1022691/Python3%3A-DFS-(Same-solution-can-be-used-to-solve-Number-of-Islands) | class Solution:
def countBattleships(self, board: List[List[str]]) -> int:
if not board:
return 0
counter = 0
for i in range(len(board)):
for j in range(len(board[0])):
if board[i][j] == "X":
self.dfs(board, i, j)
counter += 1
return counter
def dfs(self, board, i, j):
if i < 0 or j < 0 or i >= len(board) or j >= len(board[i]) or board[i][j] != "X":
return
board[i][j] = "#"
self.dfs(board, i+1, j)
self.dfs(board, i-1, j)
self.dfs(board, i, j+1)
self.dfs(board, i, j-1) | battleships-in-a-board | Python3: DFS (Same solution can be used to solve Number of Islands) | MakeTeaNotWar | -1 | 171 | battleships in a board | 419 | 0.747 | Medium | 7,488 |
https://leetcode.com/problems/strong-password-checker/discuss/2345991/Runtime%3A-23-ms-or-Memory-Usage%3A-13.9-MB-or-python3 | class Solution:
def strongPasswordChecker(self, password: str) -> int:
#vimla_kushwaha
s = password
missing_type = 3
if any('a' <= c <= 'z' for c in s): missing_type -= 1
if any('A' <= c <= 'Z' for c in s): missing_type -= 1
if any(c.isdigit() for c in s): missing_type -= 1
change = 0
one = two = 0
p = 2
while p < len(s):
if s[p] == s[p-1] == s[p-2]:
length = 2
while p < len(s) and s[p] == s[p-1]:
length += 1
p += 1
change += length // 3
if length % 3 == 0: one += 1
elif length % 3 == 1: two += 1
else:
p += 1
if len(s) < 6:
return max(missing_type, 6 - len(s))
elif len(s) <= 20:
return max(missing_type, change)
else:
delete = len(s) - 20
change -= min(delete, one)
change -= min(max(delete - one, 0), two * 2) // 2
change -= max(delete - one - 2 * two, 0) // 3
return int(delete + max(missing_type, change)) | strong-password-checker | Runtime: 23 ms | Memory Usage: 13.9 MB | python3 | vimla_kushwaha | 2 | 309 | strong password checker | 420 | 0.143 | Hard | 7,489 |
https://leetcode.com/problems/strong-password-checker/discuss/2545499/Python3-greedy | class Solution:
def strongPasswordChecker(self, password: str) -> int:
digit = lower = upper = 1
for ch in password:
if ch.isdigit(): digit = 0
elif ch.islower(): lower = 0
elif ch.isupper(): upper = 0
missing = digit + lower + upper
reps = one = two = 0
i = 2
while i < len(password):
if password[i-2] == password[i-1] == password[i]:
sz = 3
while i+1 < len(password) and password[i] == password[i+1]:
sz += 1
i += 1
reps += sz // 3
if sz % 3 == 0: one += 1
elif sz % 3 == 1: two += 1
i += 1
if len(password) < 6: return max(missing, 6 - len(password))
elif len(password) <= 20: return max(missing, reps)
else:
dels = len(password) - 20
reps -= min(dels, one)
reps -= min(max(dels - one, 0), two * 2) // 2
reps -= max(dels - one - 2 * two, 0) // 3
return dels + max(missing, reps) | strong-password-checker | [Python3] greedy | ye15 | 0 | 164 | strong password checker | 420 | 0.143 | Hard | 7,490 |
https://leetcode.com/problems/strong-password-checker/discuss/1066447/Python%3A-20ms-98.58-faster | class Solution:
def strongPasswordChecker(self, password: str) -> int:
lengthOfPassword=len(password)
#IF PASSWORD IS LESS THAN 2 CHARACTER
if lengthOfPassword<3:
return 6-lengthOfPassword
isLower=False
isUpper=False
isDigit=False
repeatedCharacters=[]
lastCharacter=''
numberOfRepeatedCharacter=-1
#LOOP TO CHECK ALL CONTITIONS
for i in range(lengthOfPassword):
#CHECKING FOR UPPER<LOER CASE AND DIGIT IN PASSWORD
if not isUpper and password[i].isupper():
isUpper=True
elif not isLower and password[i].islower():
isLower=True
elif not isDigit and password[i].isdigit():
isDigit=True
#COUNTING TOTAL REPEATATION
if lastCharacter==password[i]:
repeatedCharacters[numberOfRepeatedCharacter]+=1
else:
numberOfRepeatedCharacter+=1
repeatedCharacters.append(1)
lastCharacter=password[i]
#<END OF FIRST FOR LOOP>
cases=int(not isUpper)+int(not isLower)+int(not isDigit)
#LOGIC
if lengthOfPassword<6:
#LESS THAN 6 CHARACTERS
return cases if cases>6-lengthOfPassword else 6-lengthOfPassword
elif lengthOfPassword<=20:
#ATLEAST 6 CHARACTER AND ATMOST 20 CHARACTERS
totalRepeats=0
for i in repeatedCharacters:
totalRepeats+=int(i/3)
return cases if cases>totalRepeats else totalRepeats
elif lengthOfPassword>20:
extra=lengthOfPassword-20
totalchanges=0
while extra!=0:
#Negitive Value
pos=-1
#Modulo should be more than 2
value=5.99
countUnique=0
for i in range(len(repeatedCharacters)):
if repeatedCharacters[i]<3:
countUnique+=1
continue
else:
if repeatedCharacters[i]%3==0:
pos=i
value=repeatedCharacters[i]
break
elif repeatedCharacters[i]%3<value%3:
pos=i
value=repeatedCharacters[i]
if value%3==0:
if extra-1>=0:
repeatedCharacters[pos]-=1
extra-=1
totalchanges+=1
else:
break
elif value%3==1:
if extra-2>=0:
repeatedCharacters[pos]-=2
extra-=2
totalchanges+=2
else:
break
elif value%3==2:
if extra-3>=0:
repeatedCharacters[pos]-=3
extra-=3
totalchanges+=3
else:
break
if countUnique>=len(repeatedCharacters):
break
totalRepeats=0
for number in repeatedCharacters:
if number>=3:
totalRepeats+=int(number/3)
first=totalchanges+extra
second=totalRepeats if totalRepeats>cases else cases
result=int(first+second)
return result | strong-password-checker | Python: 20ms - 98.58 % faster | kshitijb | 0 | 745 | strong password checker | 420 | 0.143 | Hard | 7,491 |
https://leetcode.com/problems/maximum-xor-of-two-numbers-in-an-array/discuss/404504/Python-O(N)-Trie-Solution-wcomments-and-explanations | class Solution:
def findMaximumXOR(self, nums: List[int]) -> int:
# need to know the largest binary representation
# bin prepends '0b', ignore
L = len(bin(max(nums))) - 2
# preprocess step - left-pad zeros to ensure each number has L bits
# (x >> i) & 1 produces the bit at position i for number x
# x's value is moved right by i bits, we & 1 to produce 0 or 1
# e.g., if L = 5, then 3 = [0, 0, 0, 1, 1], so the steps to get there are:
# (3 >> 4) & 1 = 0
# (3 >> 3) & 1 = 0
# (3 >> 2) & 1 = 0
# (3 >> 1) & 1 = 1
# (3 >> 0) & 1 = 1
nums_bits = [[(x >> i) & 1 for i in reversed(range(L))] for x in nums]
root = {}
# build the trie
for num, bits in zip(nums, nums_bits):
node = root
for bit in bits:
node = node.setdefault(bit, {})
node["#"] = num
max_xor = 0
for num, bits in zip(nums, nums_bits):
node = root
# we want to find the node that will produce the largest XOR with num
for bit in bits:
# our goal is to find the opposite bit, e.g. bit = 0, we want 1
# this is our goal because we want as many 1's as possible
toggled_bit = 1 - bit
if toggled_bit in node:
node = node[toggled_bit]
else:
node = node[bit]
# we're at a leaf node, now we can do the XOR computation
max_xor = max(max_xor, node["#"] ^ num)
return max_xor | maximum-xor-of-two-numbers-in-an-array | Python O(N) Trie Solution w/comments and explanations | crippled_baby | 2 | 904 | maximum xor of two numbers in an array | 421 | 0.545 | Medium | 7,492 |
https://leetcode.com/problems/maximum-xor-of-two-numbers-in-an-array/discuss/850399/Python-(75-speed-98-memory)-No-Trie-Simple-Explained-O(n) | class Solution:
def findMaximumXOR(self, nums: List[int]) -> int:
def helper(group0=[], group1=[], div_bit=0):
if len(group0) + len(group1) <= 1: return 0
if len(group0) == 1 and len(group1) == 1: return group0[0] ^ group1[0]
if div_bit == -1 and group0 and group1: return group0[0] ^ group1[0]
if div_bit == -1: return 0
nbit = div_bit - 1
if group0 and group1:
group00, group01 = divide_by_bit(group0, div_bit)
group10, group11 = divide_by_bit(group1, div_bit)
if (group00 and group11) and (group01 and group10):
return max(helper(group00, group11, nbit), helper(group10, group01, nbit))
elif group00 and group11:
return helper(group00, group11, nbit)
elif group01 and group10:
return helper(group10, group01, nbit)
else:
return helper(group00 or group01, group10 or group11, nbit)
else:
group0, group1 = divide_by_bit(group0 or group1, div_bit)
return helper(group0, group1, nbit)
max_num = max(nums)
max_bit = int(math.log(max_num, 2)) if max_num else 0
return helper(nums, [], max_bit)
def divide_by_bit(nums, bit):
mask = 1 << bit
g0, g1 = [], []
for num in nums:
if num & mask == 0:
g0.append(num)
else:
g1.append(num)
return g0, g1 | maximum-xor-of-two-numbers-in-an-array | Python (75% speed, 98% memory) - No Trie - Simple, Explained - O(n) | perenially_curious | 1 | 128 | maximum xor of two numbers in an array | 421 | 0.545 | Medium | 7,493 |
https://leetcode.com/problems/maximum-xor-of-two-numbers-in-an-array/discuss/2164227/Simple-Logic-(Python) | class Solution:
def findMaximumXOR(self, nums: List[int]) -> int:
res = [0]
for i,j in combinations(nums, 2):
res.append(i^j)
return max(res) | maximum-xor-of-two-numbers-in-an-array | Simple Logic (Python) | writemeom | 0 | 129 | maximum xor of two numbers in an array | 421 | 0.545 | Medium | 7,494 |
https://leetcode.com/problems/maximum-xor-of-two-numbers-in-an-array/discuss/1723707/10-lines-of-code-with-explanation-by-comments-for-every-line-of-code | class Solution:
def findMaximumXOR(self, nums: List[int]) -> int:
mask, maximum = 0, 0
for i in range(31, -1, -1):
mask = mask | 1 << i
# finding elements having 1's between their msb to ith bit from the start
# eg: when i = 3 then mask is 11111111111111111111111111111000 , num is 11010
# then the element added to set will be 11000
prefixPartSet = { mask & num for num in nums }
# checking possibility of forming a number having 1 at the i position in current max.
# eg: current maximum is 101000 and i = 1 so we're checking if 101010 can be formed or not.
checkingPossibilityOfObtaining = maximum | 1 << i
for prefix in prefixPartSet:
# suppose i = 1 and prefix = 111110 and number we want to obtain is = 111010
# a ^ b = c - here a = prefix, b = unknow, c = number we want to obtain
# if b is in the prefixPartSet then it means that number we want to obtain is obtainable
if checkingPossibilityOfObtaining ^ prefix in prefixPartSet:
maximum = checkingPossibilityOfObtaining
break
return maximum | maximum-xor-of-two-numbers-in-an-array | 10 lines of code with explanation by comments for every line of code | yashmishra0207 | 0 | 219 | maximum xor of two numbers in an array | 421 | 0.545 | Medium | 7,495 |
https://leetcode.com/problems/maximum-xor-of-two-numbers-in-an-array/discuss/1722795/Python-Simple-and-Clear-Python-Solution-Using-Bit-Masking-!! | class Solution:
def findMaximumXOR(self, nums: List[int]) -> int:
maxvalue = 0
mask = 0;
newset = set()
for i in range(30, -1, -1):
mask = mask | (1 << i)
newMaxvalue = maxvalue | (1 << i)
for i in range(len(nums)):
newset.add(nums[i] & mask)
for prefix in newset:
if (newMaxvalue ^ prefix) in newset:
maxvalue = newMaxvalue
break
newset.clear()
return maxvalue | maximum-xor-of-two-numbers-in-an-array | [ Python ] ✔✔ Simple and Clear Python Solution Using Bit Masking !! 🔥🔥✌ | ASHOK_KUMAR_MEGHVANSHI | 0 | 330 | maximum xor of two numbers in an array | 421 | 0.545 | Medium | 7,496 |
https://leetcode.com/problems/maximum-xor-of-two-numbers-in-an-array/discuss/839154/Python3-via-trie-O(N) | class Solution:
def findMaximumXOR(self, nums: List[int]) -> int:
ans = 0
trie = {}
for x in nums:
s = bin(x)[2:].zfill(32)
node = oppo = trie
for c in map(int, s):
node = node.setdefault(c, {}) # add to trie
oppo = oppo.get(1-c) or oppo.get(c) # as "opposite" as possible
node["#"] = x
ans = max(ans, x^oppo["#"])
return ans | maximum-xor-of-two-numbers-in-an-array | [Python3] via trie O(N) | ye15 | 0 | 257 | maximum xor of two numbers in an array | 421 | 0.545 | Medium | 7,497 |
https://leetcode.com/problems/maximum-xor-of-two-numbers-in-an-array/discuss/839154/Python3-via-trie-O(N) | class Solution:
def findMaximumXOR(self, nums: List[int]) -> int:
ans = 0
for i in range(32)[::-1]:
ans <<= 1
prefix = {num >> i for num in nums}
ans += any(ans^1^p in prefix for p in prefix)
return ans | maximum-xor-of-two-numbers-in-an-array | [Python3] via trie O(N) | ye15 | 0 | 257 | maximum xor of two numbers in an array | 421 | 0.545 | Medium | 7,498 |
https://leetcode.com/problems/reconstruct-original-digits-from-english/discuss/1556493/Python3-One-pass-solution | class Solution:
def originalDigits(self, s: str) -> str:
c = collections.Counter(s)
digit_count = [0] * 10
digit_count[0] = c['z']
digit_count[2] = c['w']
digit_count[4] = c['u']
digit_count[6] = c['x']
digit_count[8] = c['g']
digit_count[3] = c['h'] - digit_count[8]
digit_count[5] = c['f'] - digit_count[4]
digit_count[7] = c['s'] - digit_count[6]
digit_count[9] = c['i'] - digit_count[5] - digit_count[6] - digit_count[8]
digit_count[1] = c['n'] - digit_count[9] * 2 - digit_count[7]
return "".join([str(idx) * cnt for idx, cnt in enumerate(digit_count) if cnt > 0]) | reconstruct-original-digits-from-english | [Python3] One pass solution | maosipov11 | 2 | 361 | reconstruct original digits from english | 423 | 0.513 | Medium | 7,499 |
Subsets and Splits