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/best-sightseeing-pair/discuss/2429468/python-oror-DP-oror-constant-space-oror-constant-time-oror-fast-oror | class Solution:
def maxScoreSightseeingPair(self, values: List[int]) -> int:
i = 0
score = 0
for j in range(1, len(values)):
score = max(score, values[i] + values[j] + (i - j))
if values[j] >= values[i]:
i = j
elif values[i] - values[j] < j - i:
i = j
return score
# time and space complexity
# time: O(n)
# space: O(1) | best-sightseeing-pair | python || DP || constant space || constant time || fast || | Yared_betsega | 0 | 48 | best sightseeing pair | 1,014 | 0.595 | Medium | 16,600 |
https://leetcode.com/problems/best-sightseeing-pair/discuss/2204185/Python3-or-Clear-Explanation-with-Illustration-or-Faster-than-93.63-or-Less-than-87.31 | class Solution:
def maxScoreSightseeingPair(self, values: List[int]) -> int:
Max = res = 0
for i in range(1, len(values)):
Max = max(Max-1, values[i-1]-1)
res = max(res, values[i]+Max)
return res | best-sightseeing-pair | ✅[Python3] | Clear Explanation with Illustration | Faster than 93.63% | Less than 87.31% | chanchishen | 0 | 35 | best sightseeing pair | 1,014 | 0.595 | Medium | 16,601 |
https://leetcode.com/problems/best-sightseeing-pair/discuss/2185730/python-3-or-very-simple-solution-or-O(n)O(1) | class Solution:
def maxScoreSightseeingPair(self, values: List[int]) -> int:
score = i = 0
for j in range(1, len(values)):
score = max(score, values[i] + values[j] + i - j)
if values[j] + j - i > values[i]:
i = j
return score | best-sightseeing-pair | python 3 | very simple solution | O(n)/O(1) | dereky4 | 0 | 80 | best sightseeing pair | 1,014 | 0.595 | Medium | 16,602 |
https://leetcode.com/problems/best-sightseeing-pair/discuss/2060075/Python-or-DP | class Solution:
def maxScoreSightseeingPair(self, va: List[int]) -> int:
ma = float("-inf")
ans = float("-inf")
for i in range(len(va)):
if i!=0:
ans = max(ans,va[i]-i+ma)
ma = max(ma,va[i]+i)
return ans | best-sightseeing-pair | Python | DP | Shivamk09 | 0 | 50 | best sightseeing pair | 1,014 | 0.595 | Medium | 16,603 |
https://leetcode.com/problems/best-sightseeing-pair/discuss/2007189/ororPYTHON-SOLoror-FASTER-THAN-99-oror-EASY-oror-LINEAR-TIME-oror-EXPLAINED-oror-INTUTIVE-oror | class Solution:
def maxScoreSightseeingPair(self, values: List[int]) -> int:
ans = 0
n = len(values)
highest = values[0]
for i in range(1,n):
sub = values[i] - i
if sub + highest > ans : ans = sub + highest
if values[i] + i > highest: highest = values[i] + i
return ans | best-sightseeing-pair | ||PYTHON SOL|| FASTER THAN 99% || EASY || LINEAR TIME || EXPLAINED || INTUTIVE || | reaper_27 | 0 | 35 | best sightseeing pair | 1,014 | 0.595 | Medium | 16,604 |
https://leetcode.com/problems/best-sightseeing-pair/discuss/1898262/Python3%3A-DP-Solution-%3A-Easy-to-Understand | class Solution:
def maxScoreSightseeingPair(self, values: List[int]) -> int:
"""
If you look closely on the requirement:
it asks for chosing a previous index(i)
from current index(j) by which the summation is maximum.
So, for a current index(j), our task is to figure out which previous index(i)
we should pick among (0 <= i < j) possible candidate
As we are focusing on choosing the best left value from a current index,
this problem indicates a greedy solution.
Also, if we look closely, we can save the left best found so far in an array,
instead of traversing 0 <= i <= j - 1 every time to find left best for index j.
This save our time complexity from brute-force approach O(n^2) to O(n) linear with an extra O(n) space complexity.
We can reduce that space to O(1) later. But let's focus on the logic development first.
So, the greedy algorithm comes up like this:
1. Save the left best (0 <= i <= j -1) value for an index(j) in an array 'left_best'
2. When we try to compute left best(0 <= i <= j -1) for index j, we already know what is left best for index j - 1 (0 <= i < j - 1)
3. So, the current left best (0 <= i <= j -1) will be, maximum (left best upto j - 1, value of sightseeing spot for index j - 1)
4. When we compute left_best[j], which indicates best candidate sightseeing spot before index j, we can just compute score for current index
5. Also, keeping a global maximum variable to get maximum score for step 1 - 4.
"""
left_best = [0] * len(values)
# base case
# for index 1, our left best if the first(0) element
left_best[1] = values[0] + 0
ans = left_best[1] + values[1] - 1
for idx in range(2, len(values)):
# get the left best upto current index
# it can be the element previously chosen which is left_best[idx - 1]
# or just immediate previous neighbour which is values[idx - 1] + idx - 1
# get maximum for both
curr_left_best = max(
left_best[idx - 1],
values[idx - 1] + idx - 1
)
left_best[idx] = curr_left_best
# calculate the current value based on the requirement
curr_val = curr_left_best + values[idx] - idx
# get global maximum
ans = max(ans, curr_val)
return ans | best-sightseeing-pair | Python3: DP Solution : Easy to Understand | showing_up_each_day | 0 | 71 | best sightseeing pair | 1,014 | 0.595 | Medium | 16,605 |
https://leetcode.com/problems/best-sightseeing-pair/discuss/1849875/Python-One-Pass-or-Clean-Code | class Solution:
def maxScoreSightseeingPair(self, values: List[int]) -> int:
currScore = maxScore = 0
for i in range(len(values)-2,-1,-1):
value1 = values[i] + values[i+1] -1
value2 = currScore - values[i+1] + values[i] -1
currScore=max(value1,value2)
maxScore=max(maxScore,currScore)
return maxScore | best-sightseeing-pair | Python One Pass | Clean Code | deepanksinghal | 0 | 46 | best sightseeing pair | 1,014 | 0.595 | Medium | 16,606 |
https://leetcode.com/problems/best-sightseeing-pair/discuss/1793193/Super-Clear-And-Easy-Understanding-Python3-Solution | class Solution:
def maxScoreSightseeingPair(self, values: List[int]) -> int:
ans=0
curMax=values[0]-1
for i in range(1,len(values)):
ans=max(ans,values[i]+curMax)
if values[i]>=curMax:
curMax=values[i]-1
else:
curMax-=1
return ans | best-sightseeing-pair | ♠️ Super Clear And Easy Understanding Python3 Solution | edwardchor | 0 | 45 | best sightseeing pair | 1,014 | 0.595 | Medium | 16,607 |
https://leetcode.com/problems/best-sightseeing-pair/discuss/1784258/Python-easy-to-read-and-understand-or-DP | class Solution:
def maxScoreSightseeingPair(self, values: List[int]) -> int:
n = len(values)
t1, t2 = [values[0]], [values[0]]
for i in range(1, n):
t1.append(max(values[i]+i, t1[i-1]))
t2.append(values[i]-i)
t1, t2 = t1[:-1], t2[1:]
#print(t1, t2)
ans = 0
for i in range(n-1):
ans = max(ans, t1[i]+t2[i])
return ans | best-sightseeing-pair | Python easy to read and understand | DP | sanial2001 | 0 | 56 | best sightseeing pair | 1,014 | 0.595 | Medium | 16,608 |
https://leetcode.com/problems/best-sightseeing-pair/discuss/1692717/Keep-calculating-best-fit-sightseeing-and-maximum-score | class Solution:
def maxScoreSightseeingPair(self, values: List[int]) -> int:
valuable_point_pair = (values[0], 0)
maxiumum_score = 0
def get_score(p, value):
return valuable_point_pair[0] + value - abs(p-valuable_point_pair[1])
for p, value in enumerate(values[1:], 1):
# 1. Calculate maximum score
maxiumum_score = max(maxiumum_score, get_score(p, value))
# 2. Calculate the best fit sightseeing point
if value + (p -valuable_point_pair[1]) - valuable_point_pair[0] > 0:
valuable_point_pair = (value, p)
return maxiumum_score | best-sightseeing-pair | Keep calculating best fit sightseeing and maximum score | puremonkey2001 | 0 | 43 | best sightseeing pair | 1,014 | 0.595 | Medium | 16,609 |
https://leetcode.com/problems/best-sightseeing-pair/discuss/1689682/One-Pass-Python-O(n) | class Solution:
def maxScoreSightseeingPair(self, values: List[int]) -> int:
best = 0
high, spot = 0, -1
for i, x in enumerate(values):
high -= 1 # old spot loses value due to increase in travel distance
score = high + x
best = max(score, best)
if x > high:
high, spot = x, i
return best | best-sightseeing-pair | One Pass Python [O(n)] | briancoj | 0 | 49 | best sightseeing pair | 1,014 | 0.595 | Medium | 16,610 |
https://leetcode.com/problems/best-sightseeing-pair/discuss/1493819/Simple-Python-Solution-w-explanation-o(1)-space-o(n)-runtime | class Solution(object):
def maxScoreSightseeingPair(self, nums):
starter = nums[0]+0
ender = 0
bestPair = 0
for i in range(1,len(nums)):
ender = starter +nums[i]-i
starter = max(starter,nums[i]+i)
bestPair = max(bestPair,ender)
return bestPair | best-sightseeing-pair | Simple Python Solution w/ explanation, o(1) space, o(n) runtime | CesarDN | 0 | 79 | best sightseeing pair | 1,014 | 0.595 | Medium | 16,611 |
https://leetcode.com/problems/best-sightseeing-pair/discuss/1480982/Python3-solution-with-comment | class Solution:
def maxScoreSightseeingPair(self, values: List[int]) -> int:
# Keeps ith sightseeing spot max value so far
current_max_i = values[0]
# The maximum score of a pair of sightseeing splots to return
answer = 0
for i in range(1, len(values)):
# Image value[i] - i is the jth sightseeing spot score even if it uses i
answer = max(answer, current_max_i + values[i] - i)
# To make one pass possible, keep the max ith sightseeing spot score
current_max_i = max(current_max_i, values[i] + i)
return answer | best-sightseeing-pair | Python3 solution with comment | yukikitayama | 0 | 52 | best sightseeing pair | 1,014 | 0.595 | Medium | 16,612 |
https://leetcode.com/problems/best-sightseeing-pair/discuss/1006939/Python3-linear-scan | class Solution:
def maxScoreSightseeingPair(self, A: List[int]) -> int:
ans = val = 0
for i, x in enumerate(A):
ans = max(ans, x - i + val)
val = max(val, x + i)
return ans | best-sightseeing-pair | [Python3] linear scan | ye15 | 0 | 89 | best sightseeing pair | 1,014 | 0.595 | Medium | 16,613 |
https://leetcode.com/problems/best-sightseeing-pair/discuss/398015/Python-3 | class Solution:
def maxScoreSightseeingPair(self, A):
a, b = A[0], 0
for i in range(1, len(A)):
b, a = max(a + A[i] - i, b), max(A[i] + i, a)
return b | best-sightseeing-pair | Python 3 | slight_edge | 0 | 274 | best sightseeing pair | 1,014 | 0.595 | Medium | 16,614 |
https://leetcode.com/problems/best-sightseeing-pair/discuss/1598504/Python3-One-pass-O(1)-space | class Solution:
def maxScoreSightseeingPair(self, values: List[int]) -> int:
prev, res = values[0], 0
for i in range(1, len(values)):
res = max(res, prev + values[i] - i)
prev = max(prev, values[i] + i)
return res | best-sightseeing-pair | [Python3] One pass, O(1) space | maosipov11 | -1 | 117 | best sightseeing pair | 1,014 | 0.595 | Medium | 16,615 |
https://leetcode.com/problems/smallest-integer-divisible-by-k/discuss/1655649/Python3-Less-Math-More-Intuition-or-2-Accepted-Solutions-or-Intuitive | class Solution:
def smallestRepunitDivByK(self, k: int) -> int:
if not k % 2 or not k % 5: return -1
n = length = 1
while True:
if not n % k: return length
length += 1
n = 10*n + 1 | smallest-integer-divisible-by-k | [Python3] ✔️ Less Math, More Intuition ✔️ | 2 Accepted Solutions | Intuitive | PatrickOweijane | 26 | 1,900 | smallest integer divisible by k | 1,015 | 0.47 | Medium | 16,616 |
https://leetcode.com/problems/smallest-integer-divisible-by-k/discuss/1655649/Python3-Less-Math-More-Intuition-or-2-Accepted-Solutions-or-Intuitive | class Solution:
def smallestRepunitDivByK(self, k: int) -> int:
if not k % 2 or not k % 5: return -1
r = length = 1
while True:
r = r % k
if not r: return length
length += 1
r = 10*r + 1 | smallest-integer-divisible-by-k | [Python3] ✔️ Less Math, More Intuition ✔️ | 2 Accepted Solutions | Intuitive | PatrickOweijane | 26 | 1,900 | smallest integer divisible by k | 1,015 | 0.47 | Medium | 16,617 |
https://leetcode.com/problems/smallest-integer-divisible-by-k/discuss/1655706/Using-while-loop-and-hashmap-in-Python | class Solution:
def smallestRepunitDivByK(self, k: int) -> int:
#edge case
if k % 2 == 0 or k % 5 == 0: return -1
#keep track of the remainder
remain, length = 0, 0
found_so_far = set()
while remain not in found_so_far:
found_so_far.add(remain)
remain = (remain * 10 + 1) % k
length += 1
return length if remain == 0 else -1 | smallest-integer-divisible-by-k | Using while loop and hashmap in Python | kryuki | 2 | 118 | smallest integer divisible by k | 1,015 | 0.47 | Medium | 16,618 |
https://leetcode.com/problems/smallest-integer-divisible-by-k/discuss/948652/Python-Simple-Solutiom | class Solution:
def smallestRepunitDivByK(self, K):
if K % 2 == 0 or K % 5 == 0:
return -1
r = 0
for N in range(1, K + 1):
r = (r * 10 + 1) % K
if r==0:
return N | smallest-integer-divisible-by-k | Python Simple Solutiom | lokeshsenthilkumar | 1 | 175 | smallest integer divisible by k | 1,015 | 0.47 | Medium | 16,619 |
https://leetcode.com/problems/smallest-integer-divisible-by-k/discuss/2007261/oror-PYTHON-SOL-oror-REMAINDER-FIND-oror-HASHMAP-oror-EASY-oror-EXPLAINED | class Solution:
def smallestRepunitDivByK(self, k: int) -> int:
if k % 2 == 0: return -1
n = 1
leng = 1
mapp = {}
while True:
rem = n % k
if rem == 0: return leng
if rem in mapp : return -1
mapp[rem] = True
n = n*10 + 1
leng += 1 | smallest-integer-divisible-by-k | || PYTHON SOL || REMAINDER FIND || HASHMAP || EASY || EXPLAINED | reaper_27 | 0 | 73 | smallest integer divisible by k | 1,015 | 0.47 | Medium | 16,620 |
https://leetcode.com/problems/smallest-integer-divisible-by-k/discuss/1657500/Python3-Performant-and-streamlined-code(payload-4-lines!)-if-you-have-minimum-lines-obsession-%3A) | class Solution:
def smallestRepunitDivByK(self, k: int) -> int:
if math.gcd(k,10) != 1: return -1 # intuitative after some observation: any number divisable by 2 or 5 will never be a divisor of preunit.
reminder = 0
for length in range(1, k+1):
if (reminder := (1+reminder*10) % k) == 0: return length
# return -1 # with some recreational math knowledge, this line is actually unnecessary. | smallest-integer-divisible-by-k | ✅ [Python3] Performant and streamlined code(payload 4 lines!) if you have minimum lines obsession :) | win-9527 | 0 | 21 | smallest integer divisible by k | 1,015 | 0.47 | Medium | 16,621 |
https://leetcode.com/problems/smallest-integer-divisible-by-k/discuss/352334/Solution-in-Python-3-(beats-~98)-(With-Explanation) | class Solution:
def smallestRepunitDivByK(self, K: int) -> int:
if K % 2 == 0 or K % 5 == 0: return -1
i = n = 1
while n % K != 0: n, i = (10*n + 1) % K, i + 1
return i
- Junaid Mansuri
(LeetCode ID)@hotmail.com | smallest-integer-divisible-by-k | Solution in Python 3 (beats ~98%) (With Explanation) | junaidmansuri | 0 | 375 | smallest integer divisible by k | 1,015 | 0.47 | Medium | 16,622 |
https://leetcode.com/problems/binary-string-with-substrings-representing-1-to-n/discuss/1106296/Python3-2-approaches | class Solution:
def queryString(self, S: str, N: int) -> bool:
for x in range(N, 0, -1):
if bin(x)[2:] not in S: return False
return True | binary-string-with-substrings-representing-1-to-n | [Python3] 2 approaches | ye15 | 6 | 387 | binary string with substrings representing 1 to n | 1,016 | 0.575 | Medium | 16,623 |
https://leetcode.com/problems/binary-string-with-substrings-representing-1-to-n/discuss/1106296/Python3-2-approaches | class Solution:
def queryString(self, S: str, N: int) -> bool:
ans = set()
for i in range(len(S)):
for ii in range(i, i + N.bit_length()):
x = int(S[i:ii+1], 2)
if 1 <= x <= N: ans.add(x)
return len(ans) == N | binary-string-with-substrings-representing-1-to-n | [Python3] 2 approaches | ye15 | 6 | 387 | binary string with substrings representing 1 to n | 1,016 | 0.575 | Medium | 16,624 |
https://leetcode.com/problems/binary-string-with-substrings-representing-1-to-n/discuss/2841590/2-LINES-ororor-PYTHON-EASY-SOLUTIONoror-USING-STRING | class Solution:
def queryString(self, s: str, n: int) -> bool:
for i in range(1,n+1):
if bin(i)[2:] not in s:return 0
return 1 | binary-string-with-substrings-representing-1-to-n | 2 LINES ||| PYTHON EASY SOLUTION|| USING STRING | thezealott | 1 | 3 | binary string with substrings representing 1 to n | 1,016 | 0.575 | Medium | 16,625 |
https://leetcode.com/problems/binary-string-with-substrings-representing-1-to-n/discuss/1798033/Python3-solution-or-Using-python-bin()-function-or-88-lesser-memory | class Solution:
def queryString(self, s: str, n: int) -> bool:
for i in range(1,n+1):
if (bin(i)[2:]) not in s:
return False
return True | binary-string-with-substrings-representing-1-to-n | ✔Python3 solution | Using python bin() function | 88% lesser memory | Coding_Tan3 | 1 | 112 | binary string with substrings representing 1 to n | 1,016 | 0.575 | Medium | 16,626 |
https://leetcode.com/problems/binary-string-with-substrings-representing-1-to-n/discuss/2007280/ororPYTHON-SOL-oror-SIMPLE-oror-EXPLAINED-oror-STRINGS-oror | class Solution:
def queryString(self, s: str, n: int) -> bool:
leng_s = len(s)
for i in range(1,n+1):
binary = str(bin(i)[2:])
leng_b = len(binary)
flag = False
for j in range(leng_s - leng_b + 1):
if s[j:j + leng_b] == binary:
flag = True
break
if flag == False:return False
return True | binary-string-with-substrings-representing-1-to-n | ||PYTHON SOL || SIMPLE || EXPLAINED || STRINGS || | reaper_27 | 0 | 95 | binary string with substrings representing 1 to n | 1,016 | 0.575 | Medium | 16,627 |
https://leetcode.com/problems/binary-string-with-substrings-representing-1-to-n/discuss/1408126/24ms-or-96-fasteror-Simple-python3-solution. | class Solution:
def queryString(self, s: str, n: int) -> bool:
while(n):
a=bin(n)
if(a.replace('0b','') not in s):
return 0
n-=1
return 1
Improved version
class Solution:
def queryString(self, s: str, n: int) -> bool:
while(n):
if(bin(n)[2:] not in s):
return 0
n-=1
return 1 | binary-string-with-substrings-representing-1-to-n | 24ms | 96% faster| Simple python3 solution. | kavikidadumbe | 0 | 111 | binary string with substrings representing 1 to n | 1,016 | 0.575 | Medium | 16,628 |
https://leetcode.com/problems/binary-string-with-substrings-representing-1-to-n/discuss/597247/Super-easy-python-solution | class Solution:
def queryString(self, S: str, N: int) -> bool:
for i in range(1,N+1):
x=str(bin(i).replace("0b", ""))
if S.find(x)==-1:
return False
return True | binary-string-with-substrings-representing-1-to-n | Super easy python solution | Ayu-99 | 0 | 86 | binary string with substrings representing 1 to n | 1,016 | 0.575 | Medium | 16,629 |
https://leetcode.com/problems/convert-to-base-2/discuss/2007392/PYTHON-SOL-oror-EASY-oror-BINARY-CONVERSION-oror-WELL-EXPLAINED-oror | class Solution:
def baseNeg2(self, n: int) -> str:
ans = ""
while n != 0:
if n%-2 != 0 :
ans = '1' + ans
n = (n-1)//-2
else:
ans = '0' + ans
n = n//-2
return ans if ans !="" else '0' | convert-to-base-2 | PYTHON SOL || EASY || BINARY CONVERSION || WELL EXPLAINED || | reaper_27 | 1 | 172 | convert to base 2 | 1,017 | 0.61 | Medium | 16,630 |
https://leetcode.com/problems/convert-to-base-2/discuss/2482057/Python-siolution | class Solution:
def baseNeg2(self, n: int) -> str:
result = ""
while n != 0:
if n%2 != 0 :
result = '1' + result
n = (n-1)//-2
else:
result = '0' + result
n = n//-2
return result if result != "" else '0' | convert-to-base-2 | Python siolution | Yauhenish | 0 | 57 | convert to base 2 | 1,017 | 0.61 | Medium | 16,631 |
https://leetcode.com/problems/convert-to-base-2/discuss/1015354/Python3-similar-to-base-2 | class Solution:
def baseNeg2(self, N: int) -> str:
ans = []
while N:
ans.append(N & 1)
N = (1-N) >> 1
return "".join(map(str, ans[::-1] or [0])) | convert-to-base-2 | [Python3] similar to base-2 | ye15 | 0 | 159 | convert to base 2 | 1,017 | 0.61 | Medium | 16,632 |
https://leetcode.com/problems/convert-to-base-2/discuss/1015354/Python3-similar-to-base-2 | class Solution:
def baseNeg2(self, N: int) -> str:
ans = []
while N:
ans.append(N & 1)
N = -(N >> 1)
return "".join(map(str, ans[::-1] or [0])) | convert-to-base-2 | [Python3] similar to base-2 | ye15 | 0 | 159 | convert to base 2 | 1,017 | 0.61 | Medium | 16,633 |
https://leetcode.com/problems/binary-prefix-divisible-by-5/discuss/356289/Solution-in-Python-3-(beats-~98)-(three-lines)-(-O(1)-space-) | class Solution:
def prefixesDivBy5(self, A: List[int]) -> List[bool]:
n = 0
for i in range(len(A)): A[i], n = (2*n + A[i]) % 5 == 0, (2*n + A[i]) % 5
return A
- Junaid Mansuri
(LeetCode ID)@hotmail.com | binary-prefix-divisible-by-5 | Solution in Python 3 (beats ~98%) (three lines) ( O(1) space ) | junaidmansuri | 4 | 349 | binary prefix divisible by 5 | 1,018 | 0.473 | Easy | 16,634 |
https://leetcode.com/problems/binary-prefix-divisible-by-5/discuss/791074/Python-Simple-solution | class Solution:
def prefixesDivBy5(self, A: List[int]) -> List[bool]:
s='';l=[]
for i in A:
s+=str(i)
l.append(int(s,2)%5==0)
return l | binary-prefix-divisible-by-5 | Python Simple solution | lokeshsenthilkumar | 3 | 275 | binary prefix divisible by 5 | 1,018 | 0.473 | Easy | 16,635 |
https://leetcode.com/problems/binary-prefix-divisible-by-5/discuss/1231086/Python3-simple-solution | class Solution:
def prefixesDivBy5(self, nums: List[int]) -> List[bool]:
res = []
n = 0
for i in nums:
n *= 2
if i == 1:
n += 1
res.append(n % 5 == 0)
return res | binary-prefix-divisible-by-5 | Python3 simple solution | EklavyaJoshi | 2 | 59 | binary prefix divisible by 5 | 1,018 | 0.473 | Easy | 16,636 |
https://leetcode.com/problems/binary-prefix-divisible-by-5/discuss/1060101/Time-O(n)-Space-O(1)-Python3-solution | class Solution:
def prefixesDivBy5(self, A: List[int]) -> List[bool]:
# time O(n)
# space O(1)
output = []
last_bit = 0
for i in range(len(A)):
new_bit = last_bit*2 + A[i]
output.append(new_bit % 5 == 0)
last_bit = new_bit
return output | binary-prefix-divisible-by-5 | Time O(n) Space O(1) Python3 solution | mhviraf | 1 | 110 | binary prefix divisible by 5 | 1,018 | 0.473 | Easy | 16,637 |
https://leetcode.com/problems/binary-prefix-divisible-by-5/discuss/2524509/python | class Solution:
def prefixesDivBy5(self, nums: List[int]) -> List[bool]:
s = ''
res = []
for i in nums:
s += str(i)
decimal = int(s , 2)
if decimal % 5 == 0:
res.append(True)
else:
res.append(False)
return res | binary-prefix-divisible-by-5 | python | akashp2001 | 0 | 25 | binary prefix divisible by 5 | 1,018 | 0.473 | Easy | 16,638 |
https://leetcode.com/problems/binary-prefix-divisible-by-5/discuss/2021039/Python-Clean-and-Simple!-Bitwise | class Solution:
def prefixesDivBy5(self, nums):
total, result = 0, []
for num in nums:
total <<= 1
total += num
result.append(total % 5 == 0)
return result | binary-prefix-divisible-by-5 | Python - Clean and Simple! Bitwise | domthedeveloper | 0 | 64 | binary prefix divisible by 5 | 1,018 | 0.473 | Easy | 16,639 |
https://leetcode.com/problems/binary-prefix-divisible-by-5/discuss/1568866/Python3-dollarolution | class Solution:
def prefixesDivBy5(self, nums: List[int]) -> List[bool]:
x, l = 0, []
for i in nums:
n = x * 2 + i
l.append(n%5 == 0)
x = n
return l | binary-prefix-divisible-by-5 | Python3 $olution | AakRay | 0 | 64 | binary prefix divisible by 5 | 1,018 | 0.473 | Easy | 16,640 |
https://leetcode.com/problems/binary-prefix-divisible-by-5/discuss/1248954/Python-or-O(n) | class Solution:
def prefixesDivBy5(self, nums: List[int]) -> List[bool]:
len_nums=len(nums)
result=[False]*len_nums
prev = nums[0]
result[0] = True if prev%5==0 else False
for i in range(1, len_nums):
prev = 2*prev+nums[i] # previous = 2*(2^0num[0] + 2^1*num[1]) + nums[i] (0 or 1)
result[i] = True if prev%5==0 else False
return result | binary-prefix-divisible-by-5 | Python | O(n) | rksharma19896 | 0 | 53 | binary prefix divisible by 5 | 1,018 | 0.473 | Easy | 16,641 |
https://leetcode.com/problems/binary-prefix-divisible-by-5/discuss/1106199/python-direct-approach | class Solution:
def prefixesDivBy5(self, A: List[int]) -> List[bool]:
lis = []
st = ""
for i in range(len(A)):
st = st+str(A[i])
lis.append(int(st,2)%5 == 0)
return lis | binary-prefix-divisible-by-5 | python direct approach | abhisek_ | 0 | 69 | binary prefix divisible by 5 | 1,018 | 0.473 | Easy | 16,642 |
https://leetcode.com/problems/binary-prefix-divisible-by-5/discuss/1085391/Deterministic-Finite-Automaton-Python3-(-96-time-80-memory-) | class Solution:
def prefixesDivBy5(self, A: List[int]) -> List[bool]:
state = 0
answer = []
for a in A:
if a == 0:
state = ( 2*state ) % 5
else:
state = ( 2*state+1 ) % 5
answer.append(state==0)
return answer | binary-prefix-divisible-by-5 | Deterministic Finite Automaton Python3 ( 96% time 80% memory ) | rafic | 0 | 47 | binary prefix divisible by 5 | 1,018 | 0.473 | Easy | 16,643 |
https://leetcode.com/problems/next-greater-node-in-linked-list/discuss/283607/Clean-Python-Code | class Solution:
def nextLargerNodes(self, head: ListNode) -> List[int]:
result = []
stack = []
for i, current in enumerate(self.value_iterator(head)):
result.append(0)
while stack and stack[-1][0] < current:
_, index = stack.pop()
result[index] = current
stack.append((current, i))
return result
def value_iterator(self, head: ListNode):
while head is not None:
yield head.val
head = head.next | next-greater-node-in-linked-list | Clean Python Code | aquafie | 3 | 817 | next greater node in linked list | 1,019 | 0.599 | Medium | 16,644 |
https://leetcode.com/problems/next-greater-node-in-linked-list/discuss/303575/Python-Solution | class Solution:
def nextLargerNodes(self, head: ListNode) -> List[int]:
res, stack, idx = [], [], 0
while head:
while stack and stack[-1][0] < head.val:
_, i = stack.pop()
res[i] = head.val
res.append(0)
stack.append((head.val, idx))
idx += 1
head = head.next
return res | next-greater-node-in-linked-list | Python Solution | tahir3 | 2 | 761 | next greater node in linked list | 1,019 | 0.599 | Medium | 16,645 |
https://leetcode.com/problems/next-greater-node-in-linked-list/discuss/1554340/Python3-Two-version-of-solutions-with-using-stack | class Solution:
def nextLargerNodes(self, head: ListNode) -> List[int]:
res = []
stack = []
idx = 0
while head:
res.append(0)
while stack and stack[-1][0] < head.val:
_, index = stack.pop()
res[index] = head.val
stack.append((head.val, idx))
idx += 1
head = head.next
return res | next-greater-node-in-linked-list | [Python3] Two version of solutions with using stack | maosipov11 | 1 | 81 | next greater node in linked list | 1,019 | 0.599 | Medium | 16,646 |
https://leetcode.com/problems/next-greater-node-in-linked-list/discuss/1554340/Python3-Two-version-of-solutions-with-using-stack | class Solution:
def nextLargerNodes(self, head: ListNode) -> List[int]:
lst = []
stack = []
res = []
while head:
lst.append(head.val)
head = head.next
for i in range(len(lst) - 1, -1, -1):
max_prev = 0
while stack and stack[-1] <= lst[i]:
stack.pop()
if stack:
max_prev = stack[-1]
res.append(max_prev)
stack.append(lst[i])
return reversed(res) | next-greater-node-in-linked-list | [Python3] Two version of solutions with using stack | maosipov11 | 1 | 81 | next greater node in linked list | 1,019 | 0.599 | Medium | 16,647 |
https://leetcode.com/problems/next-greater-node-in-linked-list/discuss/1320814/Python3-solution-using-stack | class Solution:
def nextLargerNodes(self, head: ListNode) -> List[int]:
values = []
temp = head
while temp:
values.append(temp.val)
temp = temp.next
ans = [0]*len(values)
stack = []
for i,j in enumerate(values):
if not stack or stack[-1][0] > j:
stack.append((j,i))
else:
while stack and stack[-1][0] < j:
ans[stack.pop()[1]] = j
stack.append((j,i))
return ans | next-greater-node-in-linked-list | Python3 solution using stack | EklavyaJoshi | 1 | 104 | next greater node in linked list | 1,019 | 0.599 | Medium | 16,648 |
https://leetcode.com/problems/next-greater-node-in-linked-list/discuss/2782042/Easy-python-solution-using-stack | class Solution:
def nextLargerNodes(self, head: ListNode) -> List[int]:
arr = []
while head:
arr.append(head.val)
head = head.next
l=[]
stk=[]
n=len(arr)
for i in range(n-1,-1,-1):
if(len(stk)<=0):
l.append(0)
stk.append(arr[i])
elif(len(stk) and (stk[-1]>arr[i])):
l.append(stk[-1])
stk.append(arr[i])
else:
while(len(stk)>0 and stk[-1]<=arr[i]):
stk.pop()
if(len(stk)<=0):
l.append(0)
stk.append(arr[i])
else:
l.append(stk[-1])
stk.append(arr[i])
l=l[::-1]
return l | next-greater-node-in-linked-list | Easy python solution using stack | liontech_123 | 0 | 2 | next greater node in linked list | 1,019 | 0.599 | Medium | 16,649 |
https://leetcode.com/problems/next-greater-node-in-linked-list/discuss/2781493/Next-Greater-Node-In-Linked-List-(Python) | class Solution:
def nextLargerNodes(self, head: Optional[ListNode]) -> List[int]:
nodeValue=[]
current = head
while current :
nodeValue.append(current.val)
current = current.next
output = [0] * len(nodeValue)
stack = []
for index , value in enumerate(nodeValue) :
while stack and nodeValue[stack[-1]] < value :
output[stack.pop()] = value
stack.append(index)
return output
``` | next-greater-node-in-linked-list | Next Greater Node In Linked List (Python) | abdullah956 | 0 | 1 | next greater node in linked list | 1,019 | 0.599 | Medium | 16,650 |
https://leetcode.com/problems/next-greater-node-in-linked-list/discuss/2577113/Python-92-or-using-deque-as-a-stack | class Solution:
def nextLargerNodes(self, head: Optional[ListNode]) -> List[int]:
#reverse it
r = None
curr = head
while curr:
tmp = curr.next
curr.next = r
r = curr
curr = tmp
curr = r
'''
#use double ended queue because we are using decresing monotonic stack
and the higher values will get appended to the begining of the queue
and the lower values will be appended to the front of the queue
'''
stack = deque()
res = []
while curr:
if stack and stack[-1] > curr.val:
res.append(stack[-1])
# stack.append(curr.val)
else:
while stack:
if curr.val < stack[-1]:
break
stack.pop()
if stack:
res.append(stack[-1])
else:
res.append(0)
#if the stack is empty just append the current value
if not stack:
stack.append(curr.val)
#else if the curr.val is higher than what we have in the stack
#it get's appended to the beginning of stack(or queue) else to the front
else:
if curr.val > stack[-1]:
stack.appendleft(curr.val)
else:
stack.append(curr.val)
curr = curr.next
return res[::-1] | next-greater-node-in-linked-list | Python 92% | using deque as a stack | pandish | 0 | 16 | next greater node in linked list | 1,019 | 0.599 | Medium | 16,651 |
https://leetcode.com/problems/next-greater-node-in-linked-list/discuss/2333834/Python-monotonic-stack | class Solution:
def nextLargerNodes(self, head: Optional[ListNode]) -> List[int]:
result = []
stack = []
idx = 0
node = head
while node:
while stack and node.val > stack[-1][0]:
_, i = stack.pop()
result[i] = node.val
stack.append((node.val, idx))
result.append(0)
idx += 1
node = node.next
return result | next-greater-node-in-linked-list | Python, monotonic stack | blue_sky5 | 0 | 14 | next greater node in linked list | 1,019 | 0.599 | Medium | 16,652 |
https://leetcode.com/problems/next-greater-node-in-linked-list/discuss/1975543/python-simple-easy-small-(Time-On-space-On) | class Solution:
def nextLargerNodes(self, head: Optional[ListNode]) -> List[int]:
l = [head]
w = head.next
while w != None :
while len(l) != 0 and l[-1].val < w.val :
l[-1].val = w.val
l.pop()
l.append(w)
w = w.next
while len(l) != 0 :
l[-1].val = 0
l.pop()
w = head
while w != None :
l.append(w.val)
w = w.next
return l | next-greater-node-in-linked-list | python - simple, easy, small (Time On, space On) | ZX007java | 0 | 53 | next greater node in linked list | 1,019 | 0.599 | Medium | 16,653 |
https://leetcode.com/problems/next-greater-node-in-linked-list/discuss/1764531/Python-oror-Recursion-oror-Stack | class Solution:
def nextLargerNodes(self, head: Optional[ListNode]) -> List[int]:
def recur(head):
if head.next is None:
return [0], [head.val]
ans, stack = recur(head.next)
while stack and stack[-1] <= head.val:
stack.pop(-1)
if stack:
ans.append(stack[-1])
else:
ans.append(0)
return ans, stack + [head.val]
return recur(head)[0][::-1] | next-greater-node-in-linked-list | Python || Recursion || Stack | kalyan_yadav | 0 | 74 | next greater node in linked list | 1,019 | 0.599 | Medium | 16,654 |
https://leetcode.com/problems/next-greater-node-in-linked-list/discuss/1624165/WEEB-DOES-PYTHON-(BEATS-98.48) | class Solution:
def nextLargerNodes(self, head: Optional[ListNode]) -> List[int]:
arr = []
pointer = head
while pointer:
arr.append(pointer.val)
pointer = pointer.next
result = [0] * len(arr)
stack = [] # stores index
for i in range(len(arr)):
# implement decreasing stack
while stack and arr[stack[-1]] < arr[i]:
idx = stack.pop()
result[idx] = arr[i]
stack.append(i)
return result | next-greater-node-in-linked-list | WEEB DOES PYTHON (BEATS 98.48%) | Skywalker5423 | 0 | 127 | next greater node in linked list | 1,019 | 0.599 | Medium | 16,655 |
https://leetcode.com/problems/next-greater-node-in-linked-list/discuss/1452133/In-O(N)-easy-to-undestand-python3 | class Solution:
def nextLargerNodes(self, head: Optional[ListNode]) -> List[int]:
if not head:
return head
arr = []
while head:
arr.append(head.val)
head = head.next
n = len(arr)
stack = []
result = [0]*n
for i in range(n-1,-1,-1):
while len(stack):
s = stack.pop()
if s <= arr[i]:
continue
else:
result[i] = s
stack.append(s)
stack.append(arr[i])
break
if len(stack) == 0:
stack.append(arr[i])
result[i] = 0
return result
```
https://leetcode.com/problems/daily-temperatures/discuss/1452111/In-O(N)-python3-easy-to-understand-Feel-free-to-ask-if-u-can't-the-solution
Refer to daily temperature problem that i have solve for better understanding
just that instead of index value we are now storing the top of stack value to result
other part remain the same..
Feel free to ask Q... | next-greater-node-in-linked-list | In O(N) - easy to undestand - python3 | Shubham_Muramkar | 0 | 112 | next greater node in linked list | 1,019 | 0.599 | Medium | 16,656 |
https://leetcode.com/problems/next-greater-node-in-linked-list/discuss/1387313/Python3-Stacks-89-Faster-with-less-Memory | class Solution:
def nextLargerNodes(self, head: ListNode) -> List[int]:
stack = []
while head:
stack.append(head.val)
head = head.next
tmp = []
i = len(stack) - 1
ans = [0] * len(stack)
while stack:
curr = stack.pop()
while tmp:
if tmp[-1] > curr:
ans[i] = tmp[-1]
tmp.append(curr)
break
tmp.pop()
if not tmp:
tmp.append(curr)
ans[i] = 0
i -= 1
return ans | next-greater-node-in-linked-list | [Python3] Stacks 89%, Faster with less Memory | whitehatbuds | 0 | 163 | next greater node in linked list | 1,019 | 0.599 | Medium | 16,657 |
https://leetcode.com/problems/next-greater-node-in-linked-list/discuss/1387313/Python3-Stacks-89-Faster-with-less-Memory | class Solution:
def nextLargerNodes(self, head: ListNode) -> List[int]:
stack = []
while head:
stack.append(head.val)
head = head.next
tmp = []
i = len(stack) - 1
ans = [0] * len(stack)
for i in range(i, -1, -1):
while tmp and tmp[-1] <= stack[i]:
tmp.pop()
ans[i] = tmp[-1] if tmp else 0
tmp.append(stack[i])
return ans | next-greater-node-in-linked-list | [Python3] Stacks 89%, Faster with less Memory | whitehatbuds | 0 | 163 | next greater node in linked list | 1,019 | 0.599 | Medium | 16,658 |
https://leetcode.com/problems/next-greater-node-in-linked-list/discuss/1387299/Python3-Recursive-Dynamic-Programming-Slow-but-Accepted-One-Pass. | class Solution:
def nextLargerNodes(self, head: ListNode) -> List[int]:
if head is None:
return []
def recurse(node, mem, ans):
if node.next is None:
ans.append(0)
mem[node.val] = 0
return
recurse(node.next, mem, ans)
# Find next node that is larger than me
nextLarger = node.next.val
if nextLarger > node.val:
ans.append(nextLarger)
mem[node.val] = nextLarger
else:
# Find the immediate next node larger than nextNode if exist
nextLarger = mem[nextLarger]
while nextLarger and nextLarger <= node.val:
nextLarger = mem[nextLarger]
ans.append(nextLarger)
mem[node.val] = nextLarger
ans = []
recurse(head, {}, ans)
ans.reverse()
return ans | next-greater-node-in-linked-list | [Python3] Recursive Dynamic Programming, Slow but Accepted, One Pass. | whitehatbuds | 0 | 59 | next greater node in linked list | 1,019 | 0.599 | Medium | 16,659 |
https://leetcode.com/problems/next-greater-node-in-linked-list/discuss/1291620/python3-O(N)-using-stack | class Solution:
def nextLargerNodes(self, head: ListNode) -> List[int]:
if head==None:
return []
if head.next==None:
return [0]
L=[]
while head:
L.append(head.val)
head=head.next
stack=[L[-1]]
t=[None for _ in range(len(L))]
for i in range(len(L)-2,-1,-1):
while L[i]>=stack[-1]:
stack.pop()
if len(stack)==0:
break
if stack:
if stack[-1]==L[i]:
t[i]=0
else:
t[i]=stack[-1]
else:
t[i]=0
stack.append(L[i])
t[-1]=0
return t | next-greater-node-in-linked-list | python3 O(N) using stack | ketan_raut | 0 | 104 | next greater node in linked list | 1,019 | 0.599 | Medium | 16,660 |
https://leetcode.com/problems/next-greater-node-in-linked-list/discuss/1074486/python-3-simple-solution-using-stack | class Solution:
def nextLargerNodes(self, head: ListNode) -> List[int]:
if not head:
return []
stack=[0]
li=[]
prev=head
head=head.next
prev.next=None
while(head):
node=head
head=head.next
node.next=prev
prev=node
while(prev):
i=len(stack)-1
while(True):
if stack[i]>prev.val or stack[i]==0:
li.append(stack[i])
break
else:
stack.pop()
i-=1
stack.append(prev.val)
prev=prev.next
return li[::-1] | next-greater-node-in-linked-list | python 3 simple solution using stack | AchalGupta | 0 | 419 | next greater node in linked list | 1,019 | 0.599 | Medium | 16,661 |
https://leetcode.com/problems/next-greater-node-in-linked-list/discuss/1007891/Python3-forward-and-backward-approaches | class Solution:
def nextLargerNodes(self, head: ListNode) -> List[int]:
ans, stack = [], []
while head:
while stack and stack[-1][1] < head.val: ans[stack.pop()[0]] = head.val
stack.append((len(ans), head.val))
ans.append(0)
head = head.next
return ans | next-greater-node-in-linked-list | [Python3] forward & backward approaches | ye15 | 0 | 46 | next greater node in linked list | 1,019 | 0.599 | Medium | 16,662 |
https://leetcode.com/problems/next-greater-node-in-linked-list/discuss/1007891/Python3-forward-and-backward-approaches | class Solution:
def nextLargerNodes(self, head: ListNode) -> List[int]:
prev, node = None, head
while node: node.next, node, prev = prev, node.next, node
node = prev
ans, stack = [], []
while node:
while stack and stack[-1] <= node.val: stack.pop()
ans.append(stack[-1] if stack else 0)
stack.append(node.val)
node = node.next
return ans[::-1] | next-greater-node-in-linked-list | [Python3] forward & backward approaches | ye15 | 0 | 46 | next greater node in linked list | 1,019 | 0.599 | Medium | 16,663 |
https://leetcode.com/problems/number-of-enclaves/discuss/1040282/Python-BFS-and-DFS-by-yours-truly | class Solution:
def numEnclaves(self, A: List[List[int]]) -> int:
row, col = len(A), len(A[0])
if not A or not A[0]:
return 0
boundary1 = deque([(i,0) for i in range(row) if A[i][0]==1]) + deque([(i,col-1) for i in range(row) if A[i][col-1]==1])
boundary2 = deque([(0,i) for i in range(1,col-1) if A[0][i]==1]) + deque([(row-1,i) for i in range(1,col-1) if A[row-1][i]==1])
queue = boundary1+boundary2
def bfs(queue,A):
visited = set()
while queue:
x,y = queue.popleft()
A[x][y] = "T"
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 A[nx][ny]==1:
A[nx][ny] = "T"
queue.append((nx,ny))
return A
bfs(queue,A)
count = 0
for x in range(row):
for y in range(col):
if A[x][y] == 1:
count+=1
return count | number-of-enclaves | Python BFS and DFS by yours truly | Skywalker5423 | 14 | 1,100 | number of enclaves | 1,020 | 0.65 | Medium | 16,664 |
https://leetcode.com/problems/number-of-enclaves/discuss/1040282/Python-BFS-and-DFS-by-yours-truly | class Solution:
def numEnclaves(self, A: List[List[int]]) -> int:
row, col = len(A), len(A[0])
if not A or not A[0]:
return 0
def dfs(x,y,A):
if 0<=x<row and 0<=y<col and A[x][y] ==1:
A[x][y] = "T"
dfs(x+1,y,A)
dfs(x-1,y,A)
dfs(x,y+1,A)
dfs(x,y-1,A)
for x in range(row):
dfs(x,0,A)
dfs(x,col-1,A)
for y in range(1,col-1):
dfs(0,y,A)
dfs(row-1,y,A)
count=0
for x in range(row):
for y in range(col):
if A[x][y]==1:
count+=1
return count | number-of-enclaves | Python BFS and DFS by yours truly | Skywalker5423 | 14 | 1,100 | number of enclaves | 1,020 | 0.65 | Medium | 16,665 |
https://leetcode.com/problems/number-of-enclaves/discuss/2519350/Python-Elegant-and-Short-or-In-place-or-DFS | class Solution:
"""
Time: O(n^2)
Memory: O(n^2)
"""
WATER = 0
LAND = 1
def numEnclaves(self, grid: List[List[int]]) -> int:
n, m = len(grid), len(grid[0])
for i in range(n):
self.sink_island(i, 0, grid)
self.sink_island(i, m - 1, grid)
for j in range(m):
self.sink_island(0, j, grid)
self.sink_island(n - 1, j, grid)
return sum(map(sum, grid))
@classmethod
def sink_island(cls, row: int, col: int, grid: List[List[int]]):
if grid[row][col] == cls.LAND:
grid[row][col] = cls.WATER
if row > 0:
cls.sink_island(row - 1, col, grid)
if row < len(grid) - 1:
cls.sink_island(row + 1, col, grid)
if col < len(grid[0]) - 1:
cls.sink_island(row, col + 1, grid)
if col > 0:
cls.sink_island(row, col - 1, grid) | number-of-enclaves | Python Elegant & Short | In-place | DFS | Kyrylo-Ktl | 2 | 85 | number of enclaves | 1,020 | 0.65 | Medium | 16,666 |
https://leetcode.com/problems/number-of-enclaves/discuss/2274986/Python3-clean-DFS-solution | class Solution:
def numEnclaves(self, grid: List[List[int]]) -> int:
m,n = len(grid), len(grid[0])
visited = set()
result = [0]
def dfs(i,j, isBoundary):
if i < 0 or i >= m or j < 0 or j>= n or grid[i][j]!=1 or (i,j) in visited:
return
visited.add((i,j))
if not isBoundary:
result[0]+=1
for x,y in [(0,-1), (0,1), (-1,0), (1,0)]:
dfs(i+x, j+y, isBoundary)
for i in [0, m-1]:
for j in range(n):
if grid[i][j] == 1 and (i,j) not in visited:
dfs(i,j, True)
for j in [0, n-1]:
for i in range(m):
if grid[i][j] == 1 and (i,j) not in visited:
dfs(i,j, True)
for i in range(m):
for j in range(n):
if grid[i][j] == 1 and (i,j) not in visited:
dfs(i,j, False)
return result[0] | number-of-enclaves | 📌 Python3 clean DFS solution | Dark_wolf_jss | 1 | 19 | number of enclaves | 1,020 | 0.65 | Medium | 16,667 |
https://leetcode.com/problems/number-of-enclaves/discuss/1853713/Python-DFS-Solution | class Solution:
def numEnclaves(self, grid: List[List[int]]) -> int:
if not grid:
return 0
rows, cols = len(grid), len(grid[0])
def dfs(r, c, value):
if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] == 0:
return
grid[r][c] = value
dfs(r - 1, c, value)
dfs(r + 1, c, value)
dfs(r, c + 1, value)
dfs(r, c - 1, value)
for r in range(rows):
dfs(r, 0, 0)
dfs(r, cols - 1, 0)
for c in range(cols):
dfs(0, c, 0)
dfs(rows - 1, c, 0)
count = 0
return sum([1 for r in range(rows) for c in range(cols) if grid[r][c] == 1]) | number-of-enclaves | [Python] DFS Solution | tejeshreddy111 | 1 | 91 | number of enclaves | 1,020 | 0.65 | Medium | 16,668 |
https://leetcode.com/problems/number-of-enclaves/discuss/2822959/DFS-approach-with-similar-question | class Solution:
def dfs_util(self,grid: List[List[int]],i:int,j:int,r:int,c:int) -> int:
# if any land cell touches boundary return -1
if i<0 or j<0 or i>=r or j>=c:
return -1
if grid[i][j]==0:
return 0
grid[i][j]=0
left = self.dfs_util(grid,i,j-1,r,c)
right = self.dfs_util(grid,i,j+1,r,c)
top = self.dfs_util(grid,i-1,j,r,c)
bottom = self.dfs_util(grid,i+1,j,r,c)
# if any land cell touches boundary return -1
if (left==-1 or right==-1 or top==-1 or bottom==-1):
return -1
return (1+left + right + top + bottom)
def numEnclaves(self, grid: List[List[int]]) -> int:
r = len(grid)
c = len(grid[0]) if r else 0
ans=0
for i in range(r):
for j in range(c):
if grid[i][j]==1:
gridVal = self.dfs_util(grid,i,j,r,c)
# -1 means the island touched boundary thus checking for non -1 values that holds the cell count
if gridVal!=-1:
ans+=gridVal
return ans | number-of-enclaves | DFS approach with similar question | Sakshamji | 0 | 4 | number of enclaves | 1,020 | 0.65 | Medium | 16,669 |
https://leetcode.com/problems/number-of-enclaves/discuss/2772377/Python-or-Easy-Solution-or-Matrix | class Solution(object):
def numEnclaves(self, mat):
"""
:type grid: List[List[int]]
:rtype: int
"""
def solve(r, c):
if r not in range(len(mat)):
return float("inf")
if c not in range(len(mat[0])):
return float("inf")
if mat[r][c] == 0:
return 0
mat[r][c] = 0
return 1 + solve(r+1, c) + solve(r-1, c) + solve(r, c+1) + solve(r, c-1)
count = 0
for r in range(len(mat)):
for c in range(len(mat[0])):
if mat[r][c] == 1:
res = solve(r, c)
if res != float("inf"):
count += res
return count | number-of-enclaves | Python | Easy Solution | Matrix | atharva77 | 0 | 3 | number of enclaves | 1,020 | 0.65 | Medium | 16,670 |
https://leetcode.com/problems/number-of-enclaves/discuss/2690795/DFS-solution-in-python | class Solution:
def numEnclaves(self, grid: List[List[int]]) -> int:
#this bfs function will make all the boundary 1's and the 1's connected to them as 0
def dfs(i,j):
if i<0 or i>=m or j<0 or j>=n or grid[i][j]==0:
return 0
grid[i][j]=0
dfs(i+1,j)
dfs(i-1,j)
dfs(i,j-1)
dfs(i,j+1)
m,n=len(grid),len(grid[0])
for i in range(m):
for j in range(n):
if (i==0 or i==m-1 or j==0 or j==n-1) and grid[i][j]==1:
dfs(i,j)
count=0
#now counting the remaining 1's and that will be our answer
for i in range(m):
for j in range(n):
if grid[i][j]==1:
count+=1
return count | number-of-enclaves | DFS solution in python | shashank_2000 | 0 | 5 | number of enclaves | 1,020 | 0.65 | Medium | 16,671 |
https://leetcode.com/problems/number-of-enclaves/discuss/2642340/Python-BFS | class Solution:
def numEnclaves(self, grid: List[List[int]]) -> int:
R, C = len(grid), len(grid[0])
ans = 0
q = collections.deque([])
for r in range(R):
if r == 0 or r == R-1:
for c in range(C):
if grid[r][c] == 1:
q.append((r,c))
grid[r][c] = 2
else:
if grid[r][0] == 1:
q.append((r,0))
grid[r][0] = 2
if grid[r][C-1] == 1:
q.append((r,C-1))
grid[r][C-1] = 2
while q:
for _ in range(len(q)):
r,c = q.popleft()
for _r,_c in [(r+1,c),(r-1,c),(r,c+1),(r,c-1)]:
if 0 <= _r < R and 0 <= _c < C and grid[_r][_c] == 1:
grid[_r][_c] = 2
q.append((_r,_c))
for r in range(1, R-1):
for c in range(1, C-1):
if grid[r][c] == 1:
ans += 1
return ans | number-of-enclaves | Python BFS | stanleyyuen_pang | 0 | 2 | number of enclaves | 1,020 | 0.65 | Medium | 16,672 |
https://leetcode.com/problems/number-of-enclaves/discuss/2589109/Python-really-easy-to-understand-approach....... | class Solution:
def numEnclaves(self, grid: List[List[int]]) -> int:
visited=set()
for i in range(0,len(grid)):
for j in range(0,len(grid[0])):
if i==0:
if grid[i][j]==1:
visited.add((i,j))
elif j==0:
if grid[i][j]==1:
visited.add((i,j))
elif i==len(grid)-1:
if grid[i][j]==1:
visited.add((i,j))
elif j==len(grid[0])-1:
if grid[i][j]==1:
visited.add((i,j))
q=deque([i for i in visited])
self.bfs(grid,q,visited)
result=0
for i in range(0,len(grid)):
for j in range(0,len(grid[0])):
if grid[i][j]==1 and (i,j) not in visited:
result+=1
return result
def bfs(self,grid,q,visited):
while q:
x,y=q.popleft()
for i,j in [x+1,y],[x-1,y],[x,y+1],[x,y-1]:
if 0<=i<len(grid) and 0<=j<len(grid[0]) and grid[i][j]==1 and (i,j) not in visited:
visited.add((i,j))
q.append((i,j)) | number-of-enclaves | Python really easy to understand approach....... | guneet100 | 0 | 18 | number of enclaves | 1,020 | 0.65 | Medium | 16,673 |
https://leetcode.com/problems/number-of-enclaves/discuss/2407906/Optimal-python3-solution | class Solution:
def numEnclaves(self, grid: List[List[int]]) -> int:
n = len(grid)
m = len(grid[0])
def getNeighbours(root):
x, y = root
neighbours = []
if x > 0 and grid[x-1][y] == 1:
neighbours.append((x-1, y))
if x < n-1 and grid[x+1][y] == 1:
neighbours.append((x+1, y))
if y > 0 and grid[x][y-1] == 1:
neighbours.append((x, y-1))
if y < m-1 and grid[x][y+1] == 1:
neighbours.append((x, y+1))
return neighbours
def markBoundary(root):
x, y = root
if grid[x][y] == 'N':
return
grid[x][y] = 'N'
neighbours = getONeighbours(root)
for neighbour in neighbours:
markBoundary(neighbour)
xborders = [0, n-1]
for i in range(m):
for border in xborders:
if grid[border][i] == 1:
markBoundary((border, i))
yborders = [0, m-1]
for i in range(n):
for border in yborders:
if grid[i][border] == 1:
markBoundary((i, border))
count = 0
for i in range(n):
for j in range(m):
if grid[i][j] == 1:
count +=1
return count | number-of-enclaves | Optimal python3 solution | destifo | 0 | 5 | number of enclaves | 1,020 | 0.65 | Medium | 16,674 |
https://leetcode.com/problems/number-of-enclaves/discuss/2356427/Python-3-or-O(rows*cols)-runtime-solution(Straightforward-BFS-%2B-Queue) | class Solution:
#Time-Complexity: O(rows*cols + rows*cols), since for loop must run through each and every cell grid! Our bfs
#helper in worst case has to run while loop for each entry if our grid is all land cells (rows*cols)!
#-> O(rows*cols)
#Space: O(rows*cols + rows*cols),worst case each and every cell is land! -> O(rows*cols)
def numEnclaves(self, grid: List[List[int]]) -> int:
#Key: If even one land cell of island can walk off grid, this makes
#it possible to walk off grid for any land cell we choose for that
#particular island!
#We can use some kind of boolean flag to indicate whether
#we can walk off the island in any way!
#if boolean value is True, we simply return 0
#otherwise, we return the island size since the entire island
#is enclosed in grid(can't walk off)!
visited = set()
rows, cols = len(grid), len(grid[0])
#bfs helper!
#2 parameters is the starting land cell position: cr =currentrow
#cc = currentcolumn!
def bfs(sr, sc):
nonlocal visited, grid, rows, cols
q = collections.deque()
q.append([sr, sc])
visited.add((sr, sc))
#boolean flag
can_walk_off = False
four_directions = [[1,0], [-1,0], [0, 1], [0, -1]]
island_size = 0
#run bfs as long as queue is non-empty!
while q:
cur_row, cur_col = q.popleft()
#for each new element we process by dequeing, our island
#size we are currently bfsing increases by 1!
island_size += 1
#check if we can walk off grid from current land cell!
if(cur_row + 1 not in range(rows) or
cur_row - 1 not in range(rows) or
cur_col + 1 not in range(cols) or
cur_col - 1 not in range(cols)):
#set on our boolean flag!
can_walk_off = True
#add to queue only neighboring cells that are in-bounds,
#land cell, and not already visited!
for direction in four_directions:
row_change, col_change = direction
if(cur_row + row_change in range(rows) and
cur_col + col_change in range(cols) and
grid[cur_row+row_change][cur_col+col_change]==1 and
(cur_row+row_change, cur_col+col_change) not in visited):
#then add the neighboring cell to queue and mark it as visited!
q.append([cur_row+row_change, cur_col + col_change])
visited.add((cur_row+row_change, cur_col + col_change))
#once bfs ends, check the bool flag!
if(can_walk_off):
return 0
else:
return island_size
#we will run nested for loop and bfs only on land cells that
#have not already been visited
ans = 0
for i in range(rows):
for j in range(cols):
if(grid[i][j] == 1 and (i, j) not in visited):
ans += bfs(i, j)
return ans | number-of-enclaves | Python 3 | O(rows*cols) runtime solution(Straightforward BFS + Queue) | JOON1234 | 0 | 10 | number of enclaves | 1,020 | 0.65 | Medium | 16,675 |
https://leetcode.com/problems/number-of-enclaves/discuss/2285869/Python3-DFS.-Remove-border-islands-and-count-%221%22s | class Solution:
def numEnclaves(self, grid: List[List[int]]) -> int:
C = len(grid[0])
R = len(grid)
if C <= 1 or R <= 1:
return 0
def dfs(i,j):
if (i>=0 and j>=0 and i<R and j<C and grid[i][j] == 1):
#if 0<i<R-1 and 0<j<C-1:
grid[i][j] = 0
if i<R-1: dfs(i+1,j)
if i>0: dfs(i-1,j)
if j<C-1: dfs(i,j+1)
if j>0:dfs(i,j-1)
# remove islands which have borders with edge of grid
for i in range(R):
if grid[i][0] == 1: dfs(i,0)
if grid[i][C-1] == 1: dfs(i,C-1)
for j in range(C):
if grid[0][j] == 1: dfs(0,j)
if grid[R-1][j] == 1: dfs(R-1,j)
# count 1s:
res = 0
for i in range(1,R-1):
for j in range(1,C-1):
if(grid[i][j] == 1):
res+=1
return res | number-of-enclaves | Python3 DFS. Remove border islands and count "1"s | devmich | 0 | 12 | number of enclaves | 1,020 | 0.65 | Medium | 16,676 |
https://leetcode.com/problems/number-of-enclaves/discuss/2186157/python-3-or-simple-dfs-or-O(mn)O(1) | class Solution:
def numEnclaves(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
def dfs(i, j):
if grid[i][j] == 0:
return
grid[i][j] = 0
if i: dfs(i - 1, j)
if i != m - 1: dfs(i + 1, j)
if j: dfs(i, j - 1)
if j != n - 1: dfs(i, j + 1)
for i in range(m):
dfs(i, 0)
dfs(i, n - 1)
for j in range(1, n - 1):
dfs(0, j)
dfs(m - 1, j)
return sum(num for row in grid for num in row) | number-of-enclaves | python 3 | simple dfs | O(mn)/O(1) | dereky4 | 0 | 35 | number of enclaves | 1,020 | 0.65 | Medium | 16,677 |
https://leetcode.com/problems/number-of-enclaves/discuss/2166254/Simple-DFS-Solution | class Solution:
def isSafe(self,i,j,grid):
n = len(grid)
m = len(grid[0])
if 0 <= i < n and 0 <= j < m:
return True
else:
return False
def dfs(self,i,j,grid):
if not self.isSafe(i,j,grid) or grid[i][j] != 1:
return
grid[i][j] = 2
self.dfs(i-1,j,grid)
self.dfs(i+1,j,grid)
self.dfs(i,j-1,grid)
self.dfs(i,j+1,grid)
return
def numEnclaves(self, grid: List[List[int]]) -> int:
coordinateList = []
n = len(grid)
m = len(grid[0])
for i in range(n):
for j in range(m):
if (i == 0 or j == 0 or i == n - 1 or j == m - 1) and grid[i][j] == 1:
self.dfs(i,j,grid)
landCells = 0
for i in range(n):
for j in range(m):
if grid[i][j] == 1:
landCells += 1
return landCells | number-of-enclaves | Simple DFS Solution | Vaibhav7860 | 0 | 56 | number of enclaves | 1,020 | 0.65 | Medium | 16,678 |
https://leetcode.com/problems/number-of-enclaves/discuss/2107023/Python3-or-DFS | class Solution:
def numEnclaves(self, grid: List[List[int]]) -> int:
def dfs(grid, i, j):
if i<0 or j<0 or i >= len(grid) or j >= len(grid[0]):
return
if grid[i][j] == 0:
return
grid[i][j] = 0
dfs(grid, i+1, j)
dfs(grid, i, j+1)
dfs(grid, i-1, j)
dfs(grid, i, j-1)
for i in range(len(grid)):
for j in range(len(grid[0])):
if (i == 0 or j == 0 or i == len(grid)-1 or j == len(grid[0])-1) and grid[i][j] == 1:
dfs(grid, i, j)
return sum(sum(g) for g in grid) | number-of-enclaves | Python3 | DFS | iamirulofficial | 0 | 18 | number of enclaves | 1,020 | 0.65 | Medium | 16,679 |
https://leetcode.com/problems/number-of-enclaves/discuss/2070141/Python3-fill-from-the-edges-and-then-count-ones | class Solution:
def numEnclaves(self, grid: List[List[int]]) -> int:
# 0 = sea, 1 = land
# move = adjacent cells 4-directionally
# can move walk off boundary
# we want number of land cells in grid
# which you cannot move off grid
# aka just fill in from edges and count enclaves aka island
R, C = len(grid), len(grid[0])
def dfs(r, c):
grid[r][c] = 0
for r2, c2 in [(r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)]:
if r2 >= 0 and r2 < R and c2 >= 0 and c2 < C and grid[r2][c2] == 1:
dfs(r2, c2)
# fill from edges
for r in range(R):
if grid[r][0] == 1:
dfs(r, 0)
if grid[r][C - 1] == 1:
dfs(r, C - 1)
for c in range(C):
if grid[0][c] == 1:
dfs(0, c)
if grid[R - 1][c] == 1:
dfs(R - 1, c)
ans = 0
# count islands inside after filling from edges
for r in range(1, R - 1):
for c in range(1, C - 1):
if grid[r][c] == 1:
ans += 1
return ans | number-of-enclaves | Python3 fill from the edges and then count ones | normalpersontryingtopayrent | 0 | 20 | number of enclaves | 1,020 | 0.65 | Medium | 16,680 |
https://leetcode.com/problems/number-of-enclaves/discuss/2007519/PYTHON-SOL-oror-EASY-TO-READ-oror-BFS-SOL-oror-SIMPLE-oror-EXPLAINED-oror | class Solution:
def numEnclaves(self, grid: List[List[int]]) -> int:
rows = len(grid)
cols = len(grid[0])
ones = 0
queue = []
vis =[[False for i in range(cols)] for j in range(rows)]
for i in range(rows):
for j in range(cols):
if grid[i][j] == 0:continue
ones += 1
if i == 0 or i == rows - 1 or j == 0 or j == cols -1 :
queue.append((i,j))
vis[i][j] = True
while queue:
x,y = queue.pop()
ones -= 1
for r,c in ((x+1,y),(x-1,y),(x,y-1),(x,y+1)):
if 0<=r<rows and 0<=c<cols and grid[r][c] == 1 and vis[r][c] == False:
vis[r][c] = True
queue.append((r,c))
return ones | number-of-enclaves | PYTHON SOL || EASY TO READ || BFS SOL || SIMPLE || EXPLAINED || | reaper_27 | 0 | 25 | number of enclaves | 1,020 | 0.65 | Medium | 16,681 |
https://leetcode.com/problems/number-of-enclaves/discuss/2006908/Python-easy-to-read-and-understand-or-DFS | class Solution:
def dfs(self, grid, row, col):
if row < 0 or col < 0 or row == len(grid) or col == len(grid[0]) or grid[row][col] != 1:
return 0
grid[row][col] = 2
t = self.dfs(grid, row-1, col)
l = self.dfs(grid, row, col-1)
d = self.dfs(grid, row+1, col)
r = self.dfs(grid, row, col+1)
return 1+t+l+d+r
def numEnclaves(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
for i in range(m):
_ = self.dfs(grid, i, 0)
_ = self.dfs(grid, i, n-1)
for j in range(n):
_ = self.dfs(grid, 0, j)
_ = self.dfs(grid, m-1, j)
ans = 0
for i in range(m):
for j in range(n):
if grid[i][j] == 1:
ans += self.dfs(grid, i, j)
return ans | number-of-enclaves | Python easy to read and understand | DFS | sanial2001 | 0 | 27 | number of enclaves | 1,020 | 0.65 | Medium | 16,682 |
https://leetcode.com/problems/number-of-enclaves/discuss/1960865/faster-than-98.63-of-Python3-online-submissions-for-Number-of-Enclaves. | class Solution:
def numEnclaves(self, grid: List[List[int]]) -> int:
m,n=len(grid),len(grid[0])
def Util(r,c):
grid[r][c]=0
for i,j in [(r-1,c),(r+1,c),(r,c-1),(r,c+1)]:
if i<0 or i>=m or j<0 or j>=n:
continue
if grid[i][j]==1:
Util(i,j)
for i in range(m):
for j in range(n):
if i==0 or j==0 or i==m-1 or j==n-1:
if grid[i][j]==1:
Util(i,j)
return sum(sum(x) for x in grid) | number-of-enclaves | faster than 98.63% of Python3 online submissions for Number of Enclaves. | Neerajbirajdar | 0 | 30 | number of enclaves | 1,020 | 0.65 | Medium | 16,683 |
https://leetcode.com/problems/number-of-enclaves/discuss/1891956/python-easy-to-understand-bfs-solution | class Solution:
def numEnclaves(self, grid: List[List[int]]) -> int:
enclaves = 0
rows = len(grid)
cols = len(grid[0])
visited = [[False for _ in range(cols)] for _ in range(rows)]
for i in range(rows):
for j in range(cols):
if not visited[i][j] and grid[i][j] == 1:
isClosed, size = self.sizeOfIsland((i, j), grid, visited)
if isClosed:
enclaves += size
return enclaves
def sizeOfIsland(self, pos, grid, visited):
isClosed = True
size = 0
def isValid(pos, grid, visited):
i, j = pos
if i >= 0 and i < len(grid) and j >= 0 and j < len(grid[0]) and not visited[i][j] and grid[i][j] == 1:
return True
return False
q = deque()
r, c = pos
visited[r][c] = True
q.append((r, c))
while q:
i, j = q.popleft()
size += 1
if i == len(grid) - 1 or j == len(grid[0]) - 1 or i == 0 or j == 0:
isClosed = False
if isValid((i-1, j), grid, visited):
q.append((i-1, j))
visited[i-1][j] = True
if isValid((i+1, j), grid, visited):
q.append((i+1, j))
visited[i+1][j] = True
if isValid((i, j+1), grid, visited):
q.append((i, j+1))
visited[i][j+1] = True
if isValid((i, j-1), grid, visited):
q.append((i, j-1))
visited[i][j-1] = True
return (isClosed, size) | number-of-enclaves | python easy to understand bfs solution | karthik2265 | 0 | 14 | number of enclaves | 1,020 | 0.65 | Medium | 16,684 |
https://leetcode.com/problems/number-of-enclaves/discuss/1853496/Dye-mainland-and-remain-enclaves-or-DFS-or-clear-and-with-explanation | class Solution:
def numEnclaves(self, grid):
"""
consider cells out side of grid as 'Mainland', like surrounding by 1s
so any 1 in the border is connect to Mainland, so as that island
since it's not a part of enclave, let's dye it dfs as water
and then use another dfs we can dye each enclave one by one like LC:1254
or: we can just count all 1's in this question
"""
M, N = len(grid), len(grid[0])
max_r, max_c = M - 1, N - 1
# dfs dye mainland as water
def dfs(r, c):
if 0 <= r < M and 0 <= c < N:
if grid[r][c] == 1:
grid[r][c] = 0
dfs(r - 1, c), dfs(r + 1, c), dfs(r, c - 1), dfs(r, c + 1)
# dye mainland from border
for r in range(M):
for c in range(N):
if r == 0 or c == 0 or r == max_r or c == max_c:
if grid[r][c] == 1:
dfs(r, c)
return sum(sum(r) for r in grid) | number-of-enclaves | Dye mainland and remain enclaves | DFS | clear and with explanation | steve-jokes | 0 | 25 | number of enclaves | 1,020 | 0.65 | Medium | 16,685 |
https://leetcode.com/problems/number-of-enclaves/discuss/1808963/Python-Recursive-DFS | class Solution:
def numEnclaves(self, grid: List[List[int]]) -> int:
rows, cols = len(grid), len(grid[0])
Position = namedtuple('Position', ['row', 'col'])
def withinBounds(cell):
return 0 <= cell.row < rows and 0 <= cell.col < cols
def dfs(cell):
if withinBounds(cell) and grid[cell.row][cell.col] == 1:
grid[cell.row][cell.col] = 0
topCell = Position(cell.row - 1, cell.col)
rightCell = Position(cell.row, cell.col + 1)
bottomCell = Position(cell.row + 1, cell.col)
leftCell = Position(cell.row, cell.col - 1)
dfs(topCell), dfs(rightCell), dfs(bottomCell), dfs(leftCell)
# top and bottom row dfs
for i in range(cols):
if grid[0][i]: dfs(Position(0,i))
if grid[rows-1][i]: dfs(Position(rows-1,i))
# left and right column dfs
for i in range(rows):
if grid[i][0]: dfs(Position(i,0))
if grid[i][cols-1]: dfs(Position(i,cols-1))
# count the ones
count = 0
for i in range(1, rows-1):
for j in range(1, cols-1):
if grid[i][j]: count += 1
return count | number-of-enclaves | Python Recursive DFS | Rush_P | 0 | 52 | number of enclaves | 1,020 | 0.65 | Medium | 16,686 |
https://leetcode.com/problems/number-of-enclaves/discuss/1665558/Python-DFS-Readable-with-Comments | class Solution:
def numEnclaves(self, grid: List[List[int]]) -> int:
#we will start dfs from the 1's on the boundary and will keep looking for 1's if we can visit them
#the final result is total number of 1's - visited 1's
M = len(grid)
N = len(grid[0])
visit = set()
count = 0
def dfs(i,j):
if (i,j) in visit:
return None
visit.add((i,j))
dirs = [[1,0], [0,1], [-1,0], [0,-1]]
for di, dj in dirs:
new_row = i + di
new_col = j + dj
if 0 <= new_row < M and 0 <= new_col < N and grid[new_row][new_col] == 1:
dfs(new_row, new_col)
#start the dfs from all the land cells on the boundary
for i in range(M):
for j in range(N):
if (i == 0 or i == M-1 or j == 0 or j == N-1) and grid[i][j] == 1:
dfs(i,j)
#counting the total land cells
for i in range(M):
for j in range(N):
if (0 <= i < M) and (0 <= j < N) and grid[i][j] == 1:
count += 1
#return the difference between the land cells and the ones we were able to visit
return count - len(visit) | number-of-enclaves | Python DFS Readable with Comments | Jazzyb1999 | 0 | 56 | number of enclaves | 1,020 | 0.65 | Medium | 16,687 |
https://leetcode.com/problems/number-of-enclaves/discuss/1659172/Python-simple-bfs-solution-(O(mn)-time-O(mn)-space) | class Solution:
from collections import deque
def numEnclaves(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
def valid(x, y):
return x>=0 and x<=m-1 and y>=0 and y<=n-1
def bfs(p, q):
queue = deque([(p, q)])
while queue:
node = queue.popleft()
x, y = node[0], node[1]
grid[x][y] = 0
if valid(x-1, y) and grid[x-1][y] == 1:
queue.append((x-1, y))
grid[x-1][y] = 0
if valid(x+1, y) and grid[x+1][y] == 1:
queue.append((x+1, y))
grid[x+1][y] = 0
if valid(x, y-1) and grid[x][y-1] == 1:
queue.append((x, y-1))
grid[x][y-1] = 0
if valid(x, y+1) and grid[x][y+1] == 1:
queue.append((x, y+1))
grid[x][y+1] = 0
for i in range(m):
for j in range(n):
if i == 0 or j == 0 or i == m-1 or j == n-1:
if grid[i][j] == 1:
bfs(i, j)
res = 0
return sum([sum(row) for row in grid]) | number-of-enclaves | Python simple bfs solution (O(mn) time, O(mn) space) | byuns9334 | 0 | 30 | number of enclaves | 1,020 | 0.65 | Medium | 16,688 |
https://leetcode.com/problems/number-of-enclaves/discuss/1062883/Easy-Python-Solution-or-DFS-or-Python | class Solution:
def numEnclaves(self, A: List[List[int]]) -> int:
# [[0,0,0,0],
# [1,0,1,0],
# [0,1,1,0],
# [0,0,0,0]]
def dfs(i,j,A):
if i < 0 or i > len(A) - 1 or j < 0 or j > len(A[0]) - 1 or A[i][j] != 1:
return
if A[i][j] == 1:
A[i][j] = -1
dfs(i-1,j,A)
dfs(i+1,j,A)
dfs(i,j-1,A)
dfs(i,j+1,A)
for i in range(len(A)):
for j in range(len(A[0])):
if i == 0 or i == len(A) - 1 or j == 0 or j == len(A[0])-1:
if A[i][j] == 1:
dfs(i,j,A)
count = 0
for i in range(len(A)):
for j in range(len(A[0])):
if A[i][j] == 1:
count += 1
return count | number-of-enclaves | Easy Python Solution | DFS | Python | Ayush87 | 0 | 129 | number of enclaves | 1,020 | 0.65 | Medium | 16,689 |
https://leetcode.com/problems/number-of-enclaves/discuss/1015528/Python-faster-than-93-DFS | class Solution:
def numEnclaves(self, A: List[List[int]]) -> int:
'''
1) We need number of land squares, so a result variable count.
2) Return 0, if the size of A is 0.
3) If not, find a path to land from borders, extract borders and run dfs.
4) In dfs, mark each visited cell to '-1', so as not to repeat and return when 0 is encountered.
5) Iterate through the array again to find cells that are 1 and increment count if found.
6) Return count
'''
count = 0
if len(A) == 0 or len(A[0]) == 0:
return 0
m = len(A)
n = len(A[0])
def dfs(A, i, j):
if A[i][j] != 1:
return
A[i][j] = -1
if i > 0: dfs(A, i-1, j)
if i < m-1: dfs(A, i+1, j)
if j > 0: dfs(A, i, j-1)
if j < n-1: dfs(A, i, j+1)
from itertools import product
borders = list(product(range(m), [0, n-1])) + list(product([0, m-1], range(n)))
for i,j in borders:
dfs(A, i,j)
for i in range(m):
for j in range(n):
if A[i][j] == 1:
count += 1
return count | number-of-enclaves | Python, faster than 93%, DFS | Narasimhag | 0 | 62 | number of enclaves | 1,020 | 0.65 | Medium | 16,690 |
https://leetcode.com/problems/number-of-enclaves/discuss/1007898/Python3-flood-fill-via-dfs | class Solution:
def numEnclaves(self, A: List[List[int]]) -> int:
m, n = len(A), len(A[0]) # dimensions
stack = []
for i in range(m):
if A[i][0]: stack.append((i, 0))
if A[i][n-1]: stack.append((i, n-1))
for j in range(n):
if A[0][j]: stack.append((0, j))
if A[m-1][j]: stack.append((m-1, j))
while stack: # dfs
i, j = stack.pop()
A[i][j] = 0 # mark as seen
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 A[ii][jj]: stack.append((ii, jj))
return sum(map(sum, A)) | number-of-enclaves | [Python3] flood fill via dfs | ye15 | 0 | 39 | number of enclaves | 1,020 | 0.65 | Medium | 16,691 |
https://leetcode.com/problems/number-of-enclaves/discuss/650787/Python3-flood-fill-%2B-sum-Number-of-Enclaves | class Solution:
def numEnclaves(self, A: List[List[int]]) -> int:
m = len(A)
n = len(A[0])
def floodFill(i: int, j:int) -> None:
nonlocal m, n
if not 0 <= i < m or not 0 <= j < n or not A[i][j]:
return
A[i][j] = 0
for x, y in [[i+1, j], [i-1, j], [i, j+1], [i, j-1]]:
floodFill(x, y)
for i, j in itertools.chain(
itertools.product([0, m-1], range(n)),
itertools.product(range(1, m-1), [0, n-1])):
floodFill(i, j)
return sum(sum(row) for row in A) | number-of-enclaves | Python3 flood fill + sum - Number of Enclaves | r0bertz | 0 | 100 | number of enclaves | 1,020 | 0.65 | Medium | 16,692 |
https://leetcode.com/problems/number-of-enclaves/discuss/479657/520ms-python3-using-stack | class Solution:
def numEnclaves(self, A: List[List[int]]) -> int:
m = len(A)
n = len(A[0])
stack = []
for i in range(m):
if A[i][0]==1:
A[i][0]=2
if 1<=i<=m-2 and A[i][1]==1 and n>=2:
A[i][1]=2
stack.append((i,1))
if A[i][-1]==1:
A[i][-1]=2
if 1<=i<=m-2 and A[i][-2]==1 and n>=2:
A[i][-2]=2
stack.append((i,-2))
for j in range(n):
if A[0][j]==1:
A[0][j]=2
if 1<=j<=n-2 and A[1][j]==1 and m>=2:
A[1][j]=2
stack.append((1,j))
if A[-1][j]==1:
A[-1][j]=2
if 1<=j<=n-2 and A[-2][j]==1 and m>=2:
A[-2][j]=2
stack.append((-2,j))
while stack:
site = stack.pop()
for pos in ((-1,0),(1,0),(0,-1),(0,1)):
if A[site[0]+pos[0]][site[1]+pos[1]]==1:
A[site[0]+pos[0]][site[1]+pos[1]]=2
stack.append((site[0]+pos[0],site[1]+pos[1]))
count = 0
for i in range(m):
for j in range(n):
if A[i][j]==1:
count += 1
return count | number-of-enclaves | 520ms python3, using stack | felicia1994 | 0 | 53 | number of enclaves | 1,020 | 0.65 | Medium | 16,693 |
https://leetcode.com/problems/number-of-enclaves/discuss/471336/Python3-98.40-(496-ms)100.00-(13.9-MB)-O(n)-time-O(1)-space-recursion | class Solution:
def delete_valid_squares(self, A, row, column, max_row, max_column):
if (A[row][column]):
A[row][column] = 0
if (column < max_column):
self.delete_valid_squares(A, row, column + 1, max_row, max_column)
if (column > 0):
self.delete_valid_squares(A, row, column - 1, max_row, max_column)
if (row < max_row):
self.delete_valid_squares(A, row + 1, column, max_row, max_column)
if (row > 0):
self.delete_valid_squares(A, row - 1, column, max_row, max_column)
def numEnclaves(self, A: List[List[int]]) -> int:
rows = len(A)
columns = len(A[0])
max_row = len(A) - 1
max_column = len(A[0]) - 1
offsets = [[0, 1], [1, 0], [0, -1], [-1, 0]]
row = 0
column = 0
ret = 0
for offset in offsets:
if (row == rows):
row -= 1
elif (column == columns):
column -= 1
elif (column == -1):
column = 0
while (0 <= row < rows and 0 <= column < columns):
if (A[row][column]):
self.delete_valid_squares(A, row, column, max_row, max_column)
row += offset[0]
column += offset[1]
for row in A:
for column in row:
if (column == 1):
ret += 1
return ret | number-of-enclaves | Python3 98.40% (496 ms)/100.00% (13.9 MB) -- O(n) time / O(1) space -- recursion | numiek_p | 0 | 73 | number of enclaves | 1,020 | 0.65 | Medium | 16,694 |
https://leetcode.com/problems/number-of-enclaves/discuss/300833/Python%3A-Using-generators-to-make-the-code-easier-to-read-(beats-95) | class Solution:
# Generates all coordinates on boundaries
def boundary_coordinates(self, grid):
rows = len(grid)
cols = len(grid[0])
for row_index in range(rows):
yield (row_index, 0)
yield (row_index, cols - 1)
for col_index in range(1, cols - 1):
yield (0, col_index)
yield (rows - 1, col_index)
# Returns a set of all 1's on boundaries.
def ones_on_boundaries(self, grid):
coordinates = self.boundary_coordinates(grid)
return {(row, col) for row, col in coordinates if grid[row][col] == 1}
# Generates the neighbours of a given cell
def get_neighbours(self, row, col, grid):
if row > 0:
yield (row - 1, col)
if col > 0:
yield (row, col - 1)
if row < len(grid) - 1:
yield (row + 1, col)
if col < len(grid[0]) - 1:
yield (row, col + 1)
# Counts the number of enclaves.
def numEnclaves(self, A: List[List[int]]) -> int:
total_ones = sum([sum(row) for row in A])
reachable_ones = 0
visited = self.ones_on_boundaries(A)
ones_reachable_on_boundary = list(visited)
while ones_reachable_on_boundary:
row, col = ones_reachable_on_boundary.pop()
reachable_ones += 1
for adj_row, adj_col in self.get_neighbours(row, col, A):
if (adj_row, adj_col) not in visited and A[adj_row][adj_col] == 1:
visited.add((adj_row, adj_col))
ones_reachable_on_boundary.append((adj_row, adj_col))
return total_ones - reachable_ones | number-of-enclaves | Python: Using generators to make the code easier to read (beats 95%) | Hai_dee | 0 | 119 | number of enclaves | 1,020 | 0.65 | Medium | 16,695 |
https://leetcode.com/problems/remove-outermost-parentheses/discuss/1162269/Python-Simplest-Solution | class Solution:
def removeOuterParentheses(self, S: str) -> str:
stack=[]
counter=0
for i in S:
if i=='(':
counter=counter+1
if counter==1:
pass
else:
stack.append(i)
else:
counter=counter-1
if counter == 0:
pass
else:
stack.append(i)
return (''.join(stack)) | remove-outermost-parentheses | Python Simplest Solution | aishwaryanathanii | 5 | 164 | remove outermost parentheses | 1,021 | 0.802 | Easy | 16,696 |
https://leetcode.com/problems/remove-outermost-parentheses/discuss/942888/Python-Simple-Solution | class Solution:
def removeOuterParentheses(self, S: str) -> str:
ans=[];o=0
for i in S:
if i=='(' and o>0:
ans.append(i)
if i==')' and o>1:
ans.append(')')
o+=1 if i=='(' else -1
return ''.join(ans) | remove-outermost-parentheses | Python Simple Solution | lokeshsenthilkumar | 2 | 534 | remove outermost parentheses | 1,021 | 0.802 | Easy | 16,697 |
https://leetcode.com/problems/remove-outermost-parentheses/discuss/2819789/Python-oror-96.77-Faster-oror-Without-Stack-oror-O(n)-Solution | class Solution:
def removeOuterParentheses(self, s: str) -> str:
c,j,n=0,0,len(s)
ans=[]
for i in range(n):
if s[i]=='(':
c+=1 #If there is opening paranthesis we increment the counter variable
else:
c-=1 #If there is closing paranthesis we decrement the counter variable
#If counter variable is 0 it means that No. of opening paranthesis = No. of closing paranthesis and we get a set of valid parethesis
if c==0:
#Once we get a valid set of parenthesis we store it in the list where j is the starting index of the valid parenthesis set and i is the last index.
#j+1 will remove the opening parenthesis and slicing the string till i(i.e., i-1) will store the valid set of parethesis in list after removing the outermost parenthis
ans.append(s[j+1:i])
j=i+1 #Changing the value of starting index for next valid set of parenthesis
return ''.join(ans) #It will change the list into string | remove-outermost-parentheses | Python || 96.77% Faster || Without Stack || O(n) Solution | DareDevil_007 | 1 | 95 | remove outermost parentheses | 1,021 | 0.802 | Easy | 16,698 |
https://leetcode.com/problems/remove-outermost-parentheses/discuss/2819732/Python-Easy-Solution-Using-Stack-in-O(n)-Complexity | class Solution:
def removeOuterParentheses(self, s: str) -> str:
a,n=[],len(s)
i=j=0
t=''
while i<n:
print(s[i],"s[i]")
if a and a[-1]=='(' and s[i]==')':
a.pop()
elif len(a)==0 and s[i]=='(' and i>0:
t+=s[j+1:i-1]
j=i
a.append(s[i])
else:
a.append(s[i])
i+=1
t+=s[j+1:i-1]
return t | remove-outermost-parentheses | Python Easy Solution Using Stack in O(n) Complexity | DareDevil_007 | 1 | 61 | remove outermost parentheses | 1,021 | 0.802 | Easy | 16,699 |
Subsets and Splits
Top 2 Solutions by Upvotes
Identifies the top 2 highest upvoted Python solutions for each problem, providing insight into popular approaches.