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/largest-odd-number-in-string/discuss/1284349/Easy-%2B-Straightforward-%2B-Clean-Python
class Solution: def largestOddNumber(self, num: str) -> str: i = len(num)-1 while i >= 0: if int(num[i]) % 2 != 0: return num[:i+1] i -= 1 return ''
largest-odd-number-in-string
Easy + Straightforward + Clean Python
Pythagoras_the_3rd
1
119
largest odd number in string
1,903
0.557
Easy
26,900
https://leetcode.com/problems/largest-odd-number-in-string/discuss/2768549/Python3-Reverse-iteration-easy-approach
class Solution: def largestOddNumber(self, num: str) -> str: # find the last digit that is odd for i in range(len(num)-1,-1,-1): number= int(num[i]) if number%2 !=0: return num[:i+1] return ""
largest-odd-number-in-string
Python3 Reverse iteration easy approach
melaksenay
0
1
largest odd number in string
1,903
0.557
Easy
26,901
https://leetcode.com/problems/largest-odd-number-in-string/discuss/2706109/Easy-Solution-O(N)-4-lines
class Solution: def largestOddNumber(self, num: str) -> str: for i in reversed(range(len(num))): if int(num[i]) % 2 == 1: return num[ : i + 1] return ""
largest-odd-number-in-string
Easy Solution O(N), 4 lines
user6770yv
0
3
largest odd number in string
1,903
0.557
Easy
26,902
https://leetcode.com/problems/largest-odd-number-in-string/discuss/2676869/Python-or-Find-Last-Odd-Digit
class Solution: def largestOddNumber(self, num: str) -> str: n = len(num) odd_digits = {'1', '3', '5', '7', '9'} i = n - 1 while i >= 0 and num[i] not in odd_digits: i -= 1 return num[0:i+1]
largest-odd-number-in-string
Python | Find Last Odd Digit
on_danse_encore_on_rit_encore
0
6
largest odd number in string
1,903
0.557
Easy
26,903
https://leetcode.com/problems/largest-odd-number-in-string/discuss/2642655/Window-method
class Solution: def largestOddNumber(self, num: str) -> str: n = len(num) r = n - 1 while not(int(num[r]) % 2) and r > 0: r -= 1 num = num[:r + 1] n = r + 1 for i in range(n, 0, -1): for j in range(n): k = int(num[j:i + j]) if k % 2: return str(k) return ""
largest-odd-number-in-string
Window method
maq2628
0
2
largest odd number in string
1,903
0.557
Easy
26,904
https://leetcode.com/problems/largest-odd-number-in-string/discuss/2395408/Python-remove-digits-until-rightmost-odd
class Solution: def largestOddNumber(self, num: str) -> str: num=list(num) l=len(num)-1 for i in range(l,-1,-1): x=int(num[i]) if x%2==0: num.pop() else: return "".join(num) return "".join(num)
largest-odd-number-in-string
[Python] remove digits until rightmost odd
sunakshi132
0
56
largest odd number in string
1,903
0.557
Easy
26,905
https://leetcode.com/problems/largest-odd-number-in-string/discuss/2188695/Python-interesting-solution
class Solution: def largestOddNumber(self, num: str) -> str: for i in range(len(num)-1,-1,-1): if int(num[i])%2 == 0: num = num[:-1] else: return num if not num: return num
largest-odd-number-in-string
Python interesting solution
StikS32
0
46
largest odd number in string
1,903
0.557
Easy
26,906
https://leetcode.com/problems/largest-odd-number-in-string/discuss/2029891/Python-3-or-2-Solutions-or-With-And-Without-Slicing
class Solution: def largestOddNumber(self, num: str) -> str: for i in range(len(num)-1, -1, -1): Val = int(num[i]) if(Val%2): return num[:i+1] return ""
largest-odd-number-in-string
Python 3 | 2 Solutions | With And Without Slicing
sunilsai1066
0
128
largest odd number in string
1,903
0.557
Easy
26,907
https://leetcode.com/problems/largest-odd-number-in-string/discuss/2029891/Python-3-or-2-Solutions-or-With-And-Without-Slicing
class Solution: def largestOddNumber(self, num: str) -> str: Ind = -1 for i in range(len(num)-1, -1, -1): Val = int(num[i]) if(Val % 2): Ind = i break return "" if(Ind == -1) else num[:Ind+1]
largest-odd-number-in-string
Python 3 | 2 Solutions | With And Without Slicing
sunilsai1066
0
128
largest odd number in string
1,903
0.557
Easy
26,908
https://leetcode.com/problems/largest-odd-number-in-string/discuss/2022155/Python-Clean-and-Concise!
class Solution: def largestOddNumber(self, num): for i in range(len(num)-1,-1,-1): d = int(num[i]) if d%2: return num[:i+1] return ""
largest-odd-number-in-string
Python - Clean and Concise!
domthedeveloper
0
109
largest odd number in string
1,903
0.557
Easy
26,909
https://leetcode.com/problems/largest-odd-number-in-string/discuss/1903528/Recursive-solution
class Solution: def largestOddNumber(self, num: str) -> str: if set(num).isdisjoint(set("13579")): return "" if int(num) % 2 == 1: return num return self.largestOddNumber(num[:len(num) - 1])
largest-odd-number-in-string
Recursive solution
andrewnerdimo
0
32
largest odd number in string
1,903
0.557
Easy
26,910
https://leetcode.com/problems/largest-odd-number-in-string/discuss/1872130/Python-dollarolution
class Solution: def largestOddNumber(self, num: str) -> str: for i in range(1,len(num)+1): if int(num[-i])%2 != 0: return (num[:len(num)-i+1]) return ''
largest-odd-number-in-string
Python $olution
AakRay
0
75
largest odd number in string
1,903
0.557
Easy
26,911
https://leetcode.com/problems/largest-odd-number-in-string/discuss/1869126/Python3-or-simple-soln
class Solution: def largestOddNumber(self, num: str) -> str: num_r = num[::-1] for index, n in enumerate(num_r): if int(n) %2 != 0: return num_r[index:][::-1] return ""
largest-odd-number-in-string
Python3 | simple soln
user0270as
0
71
largest odd number in string
1,903
0.557
Easy
26,912
https://leetcode.com/problems/largest-odd-number-in-string/discuss/1800962/3-Lines-Python-Solution-oror-70-Faster-oror-Memory-less-than-80
class Solution: def largestOddNumber(self, num: str) -> str: for i in range(len(num)): if int(num[len(num)-i-1])%2==1: return num[:len(num)-i] return ''
largest-odd-number-in-string
3-Lines Python Solution || 70% Faster || Memory less than 80%
Taha-C
0
92
largest odd number in string
1,903
0.557
Easy
26,913
https://leetcode.com/problems/largest-odd-number-in-string/discuss/1646295/Python3-solution-oror-Easy-to-understand
class Solution: def largestOddNumber(self, num: str) -> str: count = 0 for i in num[::-1]: if int(i)%2 == 0: count += 1 else: return num[:len(num)-count] return ""
largest-odd-number-in-string
Python3 solution || Easy to understand
CodeSavitar
0
71
largest odd number in string
1,903
0.557
Easy
26,914
https://leetcode.com/problems/largest-odd-number-in-string/discuss/1536317/One-pass-from-the-right-94-speed
class Solution: odd_digits = set("13579") def largestOddNumber(self, num: str) -> str: for i in range(len(num) - 1, -1, -1): if num[i] in Solution.odd_digits: return num[:i + 1] return ""
largest-odd-number-in-string
One pass from the right, 94% speed
EvgenySH
0
62
largest odd number in string
1,903
0.557
Easy
26,915
https://leetcode.com/problems/largest-odd-number-in-string/discuss/1413340/WEEB-DOES-PYTHON
class Solution: def largestOddNumber(self, num: str) -> str: for i in range(len(num)-1, -1, -1): if int(num[i]) % 2 == 1: return num[0:i+1] return ""
largest-odd-number-in-string
WEEB DOES PYTHON
Skywalker5423
0
81
largest odd number in string
1,903
0.557
Easy
26,916
https://leetcode.com/problems/largest-odd-number-in-string/discuss/1323314/Traversing-from-back
class Solution: def largestOddNumber(self, num: str) -> str: for i in reversed(range(len(num))): if int(num[i])%2: return num[:i+1] return ""
largest-odd-number-in-string
Traversing from back
atharva_shirode
0
47
largest odd number in string
1,903
0.557
Easy
26,917
https://leetcode.com/problems/largest-odd-number-in-string/discuss/1297953/Python-or-Simple-solution-with-3-lines-of-code.
class Solution: def largestOddNumber(self, num: str) -> str: while(len(num)>0 and (int(num[-1]) % 2==0)): num = num[:-1] return num
largest-odd-number-in-string
Python | Simple solution with 3 lines of code.
Shreevasatantry
0
115
largest odd number in string
1,903
0.557
Easy
26,918
https://leetcode.com/problems/largest-odd-number-in-string/discuss/1284970/Python-easy-O(n)
class Solution: def largestOddNumber(self, num: str) -> str: found = False for i in range(len(num)-1,-1,-1): if int(num[i]) % 2: found = True break if not found: return "" return num[:i+1]
largest-odd-number-in-string
Python easy O(n)
ermolushka2
0
42
largest odd number in string
1,903
0.557
Easy
26,919
https://leetcode.com/problems/largest-odd-number-in-string/discuss/1284727/Reducing-end-pointer-Easy-Python-solution
class Solution: def largestOddNumber(self, num: str) -> str: start = 0 end = len(num) - 1 while(end >= start): if(int(num[end]) % 2 == 1): return num[start: end+1] else: end-=1 return ""
largest-odd-number-in-string
Reducing end pointer - Easy Python solution
afrozchakure
0
26
largest odd number in string
1,903
0.557
Easy
26,920
https://leetcode.com/problems/largest-odd-number-in-string/discuss/1284694/Easy-straightforward-Puthon3-solution
class Solution: def largestOddNumber(self, num): last_odd_digit = -1 for i in range(len(num)-1, -1,-1): if int(num[i])%2==1: last_odd_digit = i break return num[:last_odd_digit+1]
largest-odd-number-in-string
Easy straightforward Puthon3 solution
tglukhikh
0
32
largest odd number in string
1,903
0.557
Easy
26,921
https://leetcode.com/problems/largest-odd-number-in-string/discuss/1284446/Python-or-3-lines-or-Simple
class Solution: def largestOddNumber(self, num: str) -> str: for i in reversed(range(len(num))): if int(num[i]) % 2: return num[:i+1] return ''
largest-odd-number-in-string
Python | 3 lines | Simple
leeteatsleep
0
32
largest odd number in string
1,903
0.557
Easy
26,922
https://leetcode.com/problems/largest-odd-number-in-string/discuss/1284419/Python3-Simple-and-intuitive-Solution-EXPLAINED
class Solution: def largestOddNumber(self, num: str) -> str: """ In order to solve this just iterate from the back if you find an odd number return till that part of the string else---> return "" """ i=len(num)-1 while i>=0: #The loop is working till the final digit if int(num[i])%2==1: # Returning the string using the slicing in Python return num[:i+1] i-=1 return "" #If no odd digits return ""
largest-odd-number-in-string
[Python3] Simple and intuitive Solution EXPLAINED
mostlyAditya
0
35
largest odd number in string
1,903
0.557
Easy
26,923
https://leetcode.com/problems/largest-odd-number-in-string/discuss/1284405/Python3-Simple-and-short-solution
class Solution: def largestOddNumber(self, num: str) -> str: #start from the last element so that you can return once you find an odd element for i in reversed(range(len(num))): #If the number is odd, break the loop and return the largest number starting from 0 index to this number if int(num[i])%2!=0: return num[0:i+1] #If you reach till here, that means there is no odd number in the string and hence return the empty string return ""
largest-odd-number-in-string
Python3 Simple and short solution
avichess
0
33
largest odd number in string
1,903
0.557
Easy
26,924
https://leetcode.com/problems/largest-odd-number-in-string/discuss/1284388/Greedy-oror-Simple-approach-oror-2-line-oror-93-faster
class Solution: def largestOddNumber(self, num: str) -> str: for j in range(len(num)-1,-1,-1): if int(num[j])%2==1: return num[:j+1] return ""
largest-odd-number-in-string
🐍 Greedy || Simple-approach || 2-line || 93% faster 📌
abhi9Rai
0
25
largest odd number in string
1,903
0.557
Easy
26,925
https://leetcode.com/problems/largest-odd-number-in-string/discuss/1284292/Python-string-manipulation-using-constant-space
class Solution: def largestOddNumber(self, num: str) -> str: ''' Runtime: O(N) Space: O(1) ''' for i in range(len(num)-1,-1,-1): if int(num[i])%2 != 0: return num[:i+1] else: return ""
largest-odd-number-in-string
Python string manipulation using constant space
dee7
0
31
largest odd number in string
1,903
0.557
Easy
26,926
https://leetcode.com/problems/largest-odd-number-in-string/discuss/1494728/Python-No-Slice
class Solution: def largestOddNumber(self, num: str) -> str: val, idx = '', len(num) - 1 while idx > -1: odd = int(num[idx]) % 2 while odd and idx > -1: val = num[idx] + val idx -= 1 idx -= 1 return val
largest-odd-number-in-string
Python No Slice
jlee9077
-1
65
largest odd number in string
1,903
0.557
Easy
26,927
https://leetcode.com/problems/the-number-of-full-rounds-you-have-played/discuss/1284279/Python3-math-ish
class Solution: def numberOfRounds(self, startTime: str, finishTime: str) -> int: hs, ms = (int(x) for x in startTime.split(":")) ts = 60 * hs + ms hf, mf = (int(x) for x in finishTime.split(":")) tf = 60 * hf + mf if 0 <= tf - ts < 15: return 0 # edge case return tf//15 - (ts+14)//15 + (ts>tf)*96
the-number-of-full-rounds-you-have-played
[Python3] math-ish
ye15
18
1,300
the number of full rounds you have played
1,904
0.456
Medium
26,928
https://leetcode.com/problems/the-number-of-full-rounds-you-have-played/discuss/1284279/Python3-math-ish
class Solution: def numberOfRounds(self, startTime: str, finishTime: str) -> int: ts = 60 * int(startTime[:2]) + int(startTime[-2:]) tf = 60 * int(finishTime[:2]) + int(finishTime[-2:]) if 0 <= tf - ts < 15: return 0 # edge case return tf//15 - (ts+14)//15 + (ts>tf)*96
the-number-of-full-rounds-you-have-played
[Python3] math-ish
ye15
18
1,300
the number of full rounds you have played
1,904
0.456
Medium
26,929
https://leetcode.com/problems/the-number-of-full-rounds-you-have-played/discuss/1284460/O(1)-time-complexity-easy-to-understand-2-solutions
class Solution: def numberOfRounds(self, startTime: str, finishTime: str) -> int: start=startTime.split(":") startHour,startMin=int(start[0]),int(start[1]) end=finishTime.split(":") endHour,endMin=int(end[0]),int(end[1]) # if start time is greater than endtime, calculate round till 00:00 and then till finish time if (startHour>endHour ) or (startHour==endHour and startMin >endMin): return (24-startHour-1)*4+(60-startMin)//15 +self.numberOfRounds("00:00",finishTime) else: if startMin not in [0,15,30,45]: if startMin<15:startMin=15 elif startMin<30:startMin=30 elif startMin<45:startMin=45 elif startHour!=23: startMin=0 startHour+=1 else: startMin=0 startHour=0 if endHour==startHour:return (endMin-startMin)//15 else: return (endHour-startHour)*4+(endMin-startMin)//15
the-number-of-full-rounds-you-have-played
O(1) time complexity, easy to understand, 2 solutions
code-fanatic
2
173
the number of full rounds you have played
1,904
0.456
Medium
26,930
https://leetcode.com/problems/the-number-of-full-rounds-you-have-played/discuss/2196398/Python-straightforward-parse-string
class Solution: def numberOfRounds(self, loginTime: str, logoutTime: str) -> int: login = self.to_min(loginTime) logout = self.to_min(logoutTime) if logout < login: # new day after midnight logout = logout + 24 * 60 if logout - login < 15: return 0 login = self.round_login(login) logout = self.round_logout(logout) return (logout - login) // 15 def to_min(self, current_time: str) -> int: h, m = map(int, current_time.split(":")) return h * 60 + m def round_login(self, m: int): return m if m % 15 == 0 else m + (15 - m % 15) def round_logout(self, m: int): return m if m % 15 == 0 else m - (m % 15)
the-number-of-full-rounds-you-have-played
[Python] straightforward, parse string
Opeth
1
83
the number of full rounds you have played
1,904
0.456
Medium
26,931
https://leetcode.com/problems/the-number-of-full-rounds-you-have-played/discuss/1284739/No-Math-and-magic-numbers-BS-Just-check-intersection-of-time-ranges
class Solution: def numberOfRounds(self, startTime: str, finishTime: str) -> int: res = 0 if startTime > finishTime: res += self.find_intersecting_rounds(startTime, '24:00') res += self.find_intersecting_rounds('00:00', finishTime) else: res += self.find_intersecting_rounds(startTime, finishTime) return res def find_intersecting_rounds(self, start, end): start_hour, _ = [int(x) for x in start.split(':')] end_hour, _ = [int(x) for x in end.split(':')] count = 0 for current_hour in range(start_hour, end_hour+1): quarters = [0, 15, 30, 45, 60] for i in range(len(quarters) - 1): first_q = '%02d:%02d' % (current_hour, quarters[i]) second_q = '%02d:%02d' % (current_hour, quarters[i+1]) # 00:00 <= 00:15 <= 23:59 and 00:00 <= 00:30 <= 23.59 if (start <= first_q <= end) and (start <= second_q <= end): count += 1 return count
the-number-of-full-rounds-you-have-played
No Math and magic numbers BS, Just check intersection of time ranges
prudentprogrammer
1
102
the number of full rounds you have played
1,904
0.456
Medium
26,932
https://leetcode.com/problems/the-number-of-full-rounds-you-have-played/discuss/2415582/Python3-easy-to-understand-no-math-magic-)
class Solution: def numberOfRounds(self, loginTime: str, logoutTime: str) -> int: h1, m1 = map(int, loginTime.split(':')) h2, m2 = map(int, logoutTime.split(':')) # Corner case like 23:47 and 23:57 if 0 <= (h2*60 + m2 - (h1*60 + m1)) < 15: return 0 while m1 % 15: m1 += 1 if m1 == 60: m1 = 0 h1 = (h1 + 1) % 24 while m2 % 15: m2 -= 1 minutes_played = (h2-h1) * 60 + (m2-m1) if minutes_played < 0: minutes_played += 24 * 60 return minutes_played // 15
the-number-of-full-rounds-you-have-played
Python3, easy to understand, no math magic =)
mhryshyn
0
53
the number of full rounds you have played
1,904
0.456
Medium
26,933
https://leetcode.com/problems/the-number-of-full-rounds-you-have-played/discuss/1285402/Easy-Python-Solution(16ms)
class Solution: def numberOfRounds(self, startTime: str, finishTime: str) -> int: s=startTime.split(":") f=finishTime.split(":") a=int(s[1]) b=int(f[1]) # g1,g2=0,0 for i in [0,15,30,45,60]: if(i-a>=0 and i-a<15): g1=i if(b-i>=0 and b-i<15): g2=i if(int(s[0])<int(f[0])): x=int(f[0])-int(s[0]) if(g1<=g2): g=((g2-g1)/15)+(x*4) else: g=((60-(g1-g2))/15)+((x-1)*4) elif(int(s[0])>int(f[0])): x=24-int(s[0])+int(f[0]) if(g1<=g2): g=((g2-g1)/15)+(x*4) else: g=((60-(g1-g2))/15)+((x-1)*4) else: if(g1<=g2): g=((g2-g1)/15) else: g=96-((g1-g2)/15) return int(g)
the-number-of-full-rounds-you-have-played
Easy Python Solution(16ms)
Sneh17029
0
164
the number of full rounds you have played
1,904
0.456
Medium
26,934
https://leetcode.com/problems/the-number-of-full-rounds-you-have-played/discuss/1284480/Python-3-I-cannot-write-3-liners-so-here-is-a-not-a-3-liner-solution
class Solution: def numberOfRounds(self, startTime: str, finishTime: str) -> int: """ We first simply calculate and get the different hours and minutes """ hS=int(startTime[:2]) mS=int(startTime[-2:]) hF=int(finishTime[:2]) mF=int(finishTime[-2:]) hourCount=0 #Variable to store the total number hours of uninterrupted play if hF<hS: #If the we have to travel the clock hourCount=(24-hS)+hF-1 elif hF==hS: if mS>mF: # That special case where you most of us get stuck hourCount=(24-hS)+hF-1 else: hourCount=-1 else: hourCount=hF-hS-1 """ I have subtracted -1 because I want uninterrupted play and which does not involve the start and the end hour i will add them manually """ # Calculating that games hGames=4*hourCount firstHour,lastHour=0,0 #Calculate the number of games that can be played during the first hour if mS==0: firstHour=4 elif mS<=15: firstHour=3 elif mS<=30: firstHour=2 elif mS<=45: firstHour=1 else: firstHour=0 # Calculate the number of games that can be played in the last hour if mF<15: lastHour=0 elif mF<30: lastHour=1 elif mF<45: print(mF) lastHour=2 elif mF<=59: lastHour=3 #Summing it all and then returning the answer if (minuteGame+minuteGame2+hGames)>0: return minuteGame+minuteGame2+hGames return 0
the-number-of-full-rounds-you-have-played
Python 3 I cannot write 3 liners so here is a not a 3 liner solution
mostlyAditya
0
83
the number of full rounds you have played
1,904
0.456
Medium
26,935
https://leetcode.com/problems/the-number-of-full-rounds-you-have-played/discuss/1364443/Floor-and-ceil-86-speed
class Solution: def numberOfRounds(self, startTime: str, finishTime: str) -> int: start_time = sum(t if i else 60 * t for i, t in enumerate(map(int, startTime.split(":")))) finish_time = sum(t if i else 60 * t for i, t in enumerate(map(int, finishTime.split(":")))) if finish_time < start_time: finish_time += 1440 return (floor(finish_time / 15) - ceil(start_time / 15) if finish_time - start_time >= 15 else 0)
the-number-of-full-rounds-you-have-played
Floor and ceil, 86% speed
EvgenySH
-2
153
the number of full rounds you have played
1,904
0.456
Medium
26,936
https://leetcode.com/problems/count-sub-islands/discuss/1284306/98-faster-oror-Simple-approach-oror-well-explained
class Solution: def countSubIslands(self, grid1: List[List[int]], grid2: List[List[int]]) -> int: m=len(grid1) n=len(grid1[0]) def dfs(i,j): if i<0 or i>=m or j<0 or j>=n or grid2[i][j]==0: return grid2[i][j]=0 dfs(i+1,j) dfs(i,j+1) dfs(i,j-1) dfs(i-1,j) # removing all the non-common sub-islands for i in range(m): for j in range(n): if grid2[i][j]==1 and grid1[i][j]==0: dfs(i,j) c=0 # counting sub-islands for i in range(m): for j in range(n): if grid2[i][j]==1: dfs(i,j) c+=1 return c
count-sub-islands
🐍 98% faster || Simple approach || well-explained 📌
abhi9Rai
148
4,900
count sub islands
1,905
0.677
Medium
26,937
https://leetcode.com/problems/count-sub-islands/discuss/1297304/WEEB-DOES-PYTHON-BFS-(BEATS-93.93)
class Solution: def countSubIslands(self, grid1: List[List[int]], grid2: List[List[int]]) -> int: queue, row, col, visited = deque([]),len(grid1), len(grid1[0]), set([]) count = 0 for x in range(row): for y in range(col): if grid1[x][y] == 1 and grid2[x][y] == 1: grid2[x][y] = "X" queue.append((x,y)) count += self.subCheck(queue,row,col,visited,grid1,grid2) return count def subCheck(self,queue, row, col, visited, grid1, grid2): key = True while queue: x,y = queue.popleft() 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 grid2[nx][ny] == 1: if grid1[nx][ny] != 1: key = False grid2[nx][ny] = "X" queue.append((nx,ny)) if key: return 1 return 0
count-sub-islands
WEEB DOES PYTHON BFS (BEATS 93.93%)
Skywalker5423
9
495
count sub islands
1,905
0.677
Medium
26,938
https://leetcode.com/problems/count-sub-islands/discuss/1426989/Python-3-Recursive-DFS-With-Comments
class Solution: def check_islands(self, grid1, grid2, row, col): if row < 0 or row >= len(grid2) or col < 0 or col >= len(grid2[0]) or grid2[row][col] == 0: return True # If one of the cells in either grid is land and the other is water, then the current cell can **not** be a sub-island. elif (grid1[row][col] == 0 and grid2[row][col] == 1) or (grid1[row][col] == 1 and grid2[row][col] == 0): return False # If the cell in both grids is land, we want to change the value so we don't check this same cell later. elif grid1[row][col] == 1 and grid2[row][col] == 1: grid2[row][col] = 0 left = self.check_islands(grid1, grid2, row, col - 1) right = self.check_islands(grid1, grid2, row, col + 1) top = self.check_islands(grid1, grid2, row - 1, col) bottom = self.check_islands(grid1, grid2, row + 1, col) # If all directions of a land cell in grid2 match with corresponding land cells in grid1, then a sub-island was found. return left and right and top and bottom def countSubIslands(self, grid1: List[List[int]], grid2: List[List[int]]) -> int: num_sub_islands = 0 for row in range(len(grid2)): for col in range(len(grid2[row])): # If grid2 is land, and grid2 is a sub-island of grid 1 if grid2[row][col] == 1 and self.check_islands(grid1, grid2, row, col): num_sub_islands += 1 return num_sub_islands
count-sub-islands
Python 3 Recursive DFS With Comments
APet99
8
315
count sub islands
1,905
0.677
Medium
26,939
https://leetcode.com/problems/count-sub-islands/discuss/1284850/O(m*n)-Time-complexity-95-faster-with-comments
class Solution: def countSubIslands(self, grid1: List[List[int]], grid2: List[List[int]]) -> int: # Time complexity: O(m*n+m*n)=>O(m*n) (we are iteraing twice through every cell) # Space complexity: O(1) m=len(grid2) n=len(grid2[0]) def dfs(i,j): if i<0 or i>=m or j<0 or j>=n or grid2[i][j]==0:return # update the value as we don't want to navigate the same cell again grid2[i][j]=0 #visit all directions dfs(i,j-1) dfs(i,j+1) dfs(i-1,j) dfs(i+1,j) for i in range(m): for j in range(n): #removing potenial islands which are not present in grid1 if grid2[i][j]==1 and grid1[i][j]==0: dfs(i,j) count=0 for i in range(m): for j in range(n): #simply calculating different islands if grid2[i][j]==1: count+=1 dfs(i,j) return count
count-sub-islands
O(m*n) Time complexity, 95% faster with comments
code-fanatic
4
174
count sub islands
1,905
0.677
Medium
26,940
https://leetcode.com/problems/count-sub-islands/discuss/1284448/easy-python-solution-on-dfs
class Solution(object): def countSubIslands(self, grid1, grid2): m=len(grid1) n=len(grid1[0]) def dfs(i,j): if i<0 or i>=m or j<0 or j>=n or grid2[i][j]==0: return grid2[i][j]=0 dfs(i+1,j) dfs(i-1,j) dfs(i,j+1) dfs(i,j-1) # here we remove the unnecesaary islands by seeing the point that if for a land in grid2 and water in grid1 it cannot be a subisland and hence island in which this land resides should be removed for i in range(m): for j in range(n): if grid2[i][j]==1 and grid1[i][j]==0: dfs(i,j) #now we just need to count the islands left over count=0 for i in range(m): for j in range(n): if grid2[i][j]==1: dfs(i,j) count+=1 return count ```
count-sub-islands
easy python solution on dfs
aayush_chhabra
4
180
count sub islands
1,905
0.677
Medium
26,941
https://leetcode.com/problems/count-sub-islands/discuss/1284287/Python3-dfs
class Solution: def countSubIslands(self, grid1: List[List[int]], grid2: List[List[int]]) -> int: m, n = len(grid1), len(grid1[0]) # dimensions def fn(i, j): """Return True if i, j is in a sub-island.""" grid2[i][j] = 0 # mark as visited ans = grid1[i][j] 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 grid2[ii][jj]: ans &amp;= fn(ii, jj) return ans ans = 0 for i in range(m): for j in range(n): if grid2[i][j] and fn(i, j): ans += 1 return ans
count-sub-islands
[Python3] dfs
ye15
4
149
count sub islands
1,905
0.677
Medium
26,942
https://leetcode.com/problems/count-sub-islands/discuss/2519379/Python-Elegant-and-Short-or-In-place-or-DFS
class Solution: """ Time: O(n^2) Memory: O(n^2) """ LAND = 1 WATER = 0 def countSubIslands(self, grid1: List[List[int]], grid2: List[List[int]]) -> int: m, n = len(grid1), len(grid1[0]) for i in range(m): for j in range(n): if grid2[i][j] == self.LAND and grid1[i][j] == self.WATER: self.sink_island(i, j, grid2) islands = 0 for i in range(m): for j in range(n): if grid2[i][j] == self.LAND: self.sink_island(i, j, grid2) islands += 1 return islands @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)
count-sub-islands
Python Elegant & Short | In-place | DFS
Kyrylo-Ktl
3
149
count sub islands
1,905
0.677
Medium
26,943
https://leetcode.com/problems/count-sub-islands/discuss/1312631/Python-3-or-Math-DFS-or-Explanation
class Solution: def countSubIslands(self, grid1: List[List[int]], grid2: List[List[int]]) -> int: m, n = len(grid1), len(grid1[0]) for i in range(m): # Add grid1 to grid2, total time: O(m*n) for j in range(n): if grid2[i][j] == 1: grid2[i][j] += grid1[i][j] def dfs(i, j): # Find sub-island, return true if grid2[i][j] is part of an sub-island if i < 0 or i > m-1 or j < 0 or j > n-1:# If out of bound, return True return True if grid2[i][j] < 1: return True # If met water or visited node, return True tmp = grid2[i][j] grid2[i][j] = -1 # Mark as visited a = dfs(i-1, j) # DFS on each direction b = dfs(i+1, j) c = dfs(i, j+1) d = dfs(i, j-1) # If current node is covered, return True if all 4 directions are also of the sub-island # otherwise return False return a and b and c and d if tmp == 2 else False ans = 0 for i in range(m): # DFS on each (i, j), O(m*n) on nested loop + O(m*n) on DFS for j in range(n): if grid2[i][j] == 2 and dfs(i, j): # DFS on only covered islands, dfs(i, j) will take only O(m*n) during iterating the ENTIRE matrix, since each node will only be visited once ans += 1 return ans
count-sub-islands
Python 3 | Math, DFS | Explanation
idontknoooo
2
171
count sub islands
1,905
0.677
Medium
26,944
https://leetcode.com/problems/count-sub-islands/discuss/2275048/Python3-simple-solution-do-DFS-twice
class Solution: def countSubIslands(self, grid1: List[List[int]], grid2: List[List[int]]) -> int: m,n,result = len(grid1), len(grid1[0]), 0 def dfs(i,j): if i < 0 or i>= m or j < 0 or j >= n or grid2[i][j]!=1: return grid2[i][j] = 0 for x,y in [(0,-1), (0,1), (-1,0), (1,0)]: dfs(i+x, j+y) for i in range(m): for j in range(n): if grid2[i][j] == 1 and grid1[i][j] == 0: dfs(i,j) for i in range(m): for j in range(n): if grid2[i][j] == 1: dfs(i,j) result+=1 return result
count-sub-islands
📌 Python3 simple solution do DFS twice
Dark_wolf_jss
1
21
count sub islands
1,905
0.677
Medium
26,945
https://leetcode.com/problems/count-sub-islands/discuss/1874175/Python-dfs-solution-(commented)
class Solution: def dfs(self, sr, sc, grid1, grid2): m, n = len(grid1), len(grid1[0]) if sr < 0 or sr >= m or sc < 0 or sc >= n: return # normal dfs return (out of bound) if grid2[sr][sc] != 1: return # normal dfs return (sea or a visited land cell) if grid1[sr][sc] != 1: self.sub = False # no return, keep traversing the whole island on grid2! grid1[sr][sc] = '#' grid2[sr][sc] = '#' self.dfs(sr+1, sc, grid1, grid2) self.dfs(sr, sc+1, grid1, grid2) self.dfs(sr-1, sc, grid1, grid2) self.dfs(sr, sc-1, grid1, grid2) def countSubIslands(self, grid1: List[List[int]], grid2: List[List[int]]) -> int: # dfs on grid 2 and check on grid 1 simultaneously m, n = len(grid1), len(grid1[0]) count = 0 self.sub = True for i in range(m): for j in range(n): if grid2[i][j] == 1: self.dfs(i,j, grid1, grid2) if self.sub: count += 1 self.sub = True return count
count-sub-islands
Python dfs solution (commented)
LemonHerbs
1
51
count sub islands
1,905
0.677
Medium
26,946
https://leetcode.com/problems/count-sub-islands/discuss/1669488/Python3-DFS-Solution-with-Explanation
class Solution: def countSubIslands(self, grid1: List[List[int]], grid2: List[List[int]]) -> int: ROWS = len(grid1) COLS = len(grid1[0]) visited = set() def dfs(r,c): # base case - just because we found water in grid2 does not mean that this island is not a sub-island - we will eventually reach the edge of the island # these conditions do not eliminate the possibility of the current island we're on being a sub-island if (r < 0 or c < 0 or r == ROWS or c == COLS or grid2[r][c] == 0 or (r,c) in visited): return True # if we passed our base case, then we have not visited these coordinates before and must add it to our set visited.add((r,c)) res = True # we don't want to return res immediately b/c we want to still want to visit the entirity of the island we're at in grid2 &amp; later on we will search in all 4 directions. # this condition will eliminate the possibilty of the current island being a sub-island # if we did NOT return in the first if statement that means grid2 IS LAND (grid2[r][c] == 1) AND if grid1[r][c] == 0, then we know it is not a sub-island if (grid1[r][c] == 0): res = False # we explore in the 4 possible directions and if any one of these directions we find a cell in grid2 that is land, but is water in grid1. What we assumed to be a sub-island is no longer a sub-island # so if any of these 4 dfs function calls returns false - then we will ultimately return False b/c all it takes is 1 missing cell in grid1 res = dfs(r + 1, c) and res res = dfs(r - 1, c) and res res = dfs(r, c + 1) and res res = dfs(r, c - 1) and res return res count = 0 # explore every single position in the grid for r in range(ROWS): for c in range(COLS): # we want to run dfs on a coordinate that is land (condition1) # we need to make sure the coordinate we're at hasn't already been visited (c2) # we need to make sure that every cell in the island in grid2 is also available in the island in grid1 (c3) if grid2[r][c] == 1 and (r,c) not in visited and dfs(r,c): count += 1 return count
count-sub-islands
Python3 DFS - Solution with Explanation
lennywgonzalez
1
154
count sub islands
1,905
0.677
Medium
26,947
https://leetcode.com/problems/count-sub-islands/discuss/1285030/Python3-DFS
class Solution: def countSubIslands(self, grid1: List[List[int]], grid2: List[List[int]]) -> int: seen = set() n, m = len(grid1), len(grid1[0]) def dfs(i, j, grid): if 0 <= i < n and 0 <= j < m and (i, j) not in seen and grid[i][j] == 1: seen.add((i, j)) grid[i][j] = 2 dfs(i+1, j, grid) dfs(i-1, j, grid) dfs(i, j+1, grid) dfs(i, j-1, grid) for i in range(n): for j in range(m): if grid1[i][j]: dfs(i, j, grid1) res = 0 for i in range(n): for j in range(m): if grid2[i][j] == 1: seen = set() dfs(i, j, grid2) if all(grid1[a][b] == 2 for a, b in seen): res += 1 return res
count-sub-islands
Python3 DFS
ermolushka2
1
51
count sub islands
1,905
0.677
Medium
26,948
https://leetcode.com/problems/count-sub-islands/discuss/2806400/Python3-DFS
class Solution: answer = 0 def countSubIslands(self, grid1: List[List[int]], grid2: List[List[int]]) -> int: len_row, len_col = len(grid1), len(grid1[0]) visited = [[0]*len_col for _ in range(len_row)] def is_safe(r, c): return 0 <= r and r <= len_row - 1 and 0 <= c and c <= len_col - 1 def dfs(r, c, flag): visited[r][c] = 1 for row, col in [(-1,0),(1,0),(0,1),(0,-1)]: if not is_safe(r+row,c+col) or visited[r+row][c+col] or not grid2[r+row][c+col]: continue if not grid1[r+row][c+col] and flag: flag = False self.answer -= 1 flag = dfs(r+row, c+col, flag) return flag for r in range(len_row): for c in range(len_col): if visited[r][c] or not grid2[r][c] or not grid1[r][c]: continue self.answer += 1 dfs(r, c, True) return self.answer
count-sub-islands
Python3 DFS
Coaspe
0
2
count sub islands
1,905
0.677
Medium
26,949
https://leetcode.com/problems/count-sub-islands/discuss/2805752/Python3-or-DFS-Solution
class Solution: def countSubIslands(self, grid1: List[List[int]], grid2: List[List[int]]) -> int: m = len(grid1);n = len(grid1[0]) ans = 0 for i in range(m): for j in range(n): if(grid2[i][j]==1): isSubLand = [True] DFS(i,j,m,n,grid1,grid2,isSubLand) if(isSubLand[0]): ans+=1 return ans def DFS(x,y,m,n,grid1,grid2,isSubLand): grid2[x][y] = 0 if(grid1[x][y]==0): isSubLand[0] = False for i,j in [(x+1,y),(x,y-1),(x-1,y),(x,y+1)]: if(0<=i<m and 0<=j<n): if(grid2[i][j]==1): DFS(i,j,m,n,grid1,grid2,isSubLand)
count-sub-islands
Python3 | DFS Solution
ty2134029
0
1
count sub islands
1,905
0.677
Medium
26,950
https://leetcode.com/problems/count-sub-islands/discuss/2775715/Python-or-BFS
class Solution: def countSubIslands(self, grid1: List[List[int]], grid2: List[List[int]]) -> int: n_row, n_col = len(grid1), len(grid1[0]) res = 0 islands2 = [] q2 = deque([]) for row in range(n_row): for col in range(n_col): island2 = set() if grid2[row][col] == 1: q2.append((row, col)) while q2: r_g2, c_g2 = q2.popleft() if grid2[r_g2][c_g2] == 1: island2.add((r_g2, c_g2)) grid2[r_g2][c_g2] = 0 for dr_g2, dc_g2 in [(1, 0), (-1, 0), (0, 1), (0, -1)]: r1_g2, c1_g2 = r_g2+dr_g2, c_g2+dc_g2 if 0 <= r1_g2 < n_row and 0 <= c1_g2 < n_col and grid2[r1_g2][c1_g2] == 1: island2.add((r1_g2, c1_g2)) q2.append((r1_g2, c1_g2)) grid2[r1_g2][c1_g2] = 0 if island2: islands2.append(island2) for i in islands2: key = True for x, y in i: if grid1[x][y] == 0: key = False if key: res += 1 return res
count-sub-islands
Python | BFS
aaron61083511
0
3
count sub islands
1,905
0.677
Medium
26,951
https://leetcode.com/problems/count-sub-islands/discuss/2721130/bfs-and-dfs-python-solution
class Solution: def countSubIslands(self, grid1: List[List[int]], grid2: List[List[int]]) -> int: # O(n*m), O(n*m) rows, cols = len(grid1), len(grid1[0]) visited = set() # ==================== BFS ================================== def bfs(r, c): q = [(r, c)] island = True while q: row, col = q.pop(0) directions = [[1, 0], [-1, 0], [0, 1], [0, -1]] for dr, dc in directions: r, c = row + dr, col + dc if r in range(rows) and c in range(cols) and grid2[r][c] == 1 and (r, c) not in visited: if grid1[r][c] != 1: island = False grid2[r][c] = "#" q.append((r, c)) visited.add((r, c)) if island: return 1 return 0 count = 0 for r in range(rows): for c in range(cols): if grid1[r][c] == 1 and grid2[r][c] == 1: grid2[r][c] = "#" count += bfs(r, c) return count # ==================== DFS ================================== # def dfs(r, c): # if r not in range(rows) or c not in range(cols) or grid2[r][c] == 0 or (r, c) in visited: # return True # visited.add((r, c)) # res = True # if grid1[r][c] == 0: # res = False # res = dfs(r + 1, c) and res # res = dfs(r - 1, c) and res # res = dfs(r, c + 1) and res # res = dfs(r, c - 1) and res # return res # count = 0 # for r in range(rows): # for c in range(cols): # if grid2[r][c] and (r, c) not in visited and dfs(r, c): # count += 1 # return count
count-sub-islands
bfs and dfs python solution
sahilkumar158
0
6
count sub islands
1,905
0.677
Medium
26,952
https://leetcode.com/problems/count-sub-islands/discuss/2678192/Python-BFS-oror-Runtime-Beats-93-oror-Memory-Beats-94-With-explanation-%3A)
class Solution: def countSubIslands(self, grid1, grid2): ROWS = len(grid2) COLS = len(grid2[0]) def bfs(i, j): q = collections.deque() q.append((i, j)) subisland = True while q: for _ in range(len(q)): i, j = q.popleft() # no-land if (i < 0 or j < 0 or i >= ROWS or j >= COLS or grid2[i][j] == 0): continue # check if cell is land in grid1 too (if not the island will be False in the end) subisland &amp;= (grid1[i][j] == 1) # set as water so next iterations won't be checked again grid2[i][j] = 0 q.append((i + 1, j)) q.append((i - 1, j)) q.append((i, j + 1)) q.append((i, j - 1)) return subisland c = 0 for i in range(ROWS): for j in range(COLS): if grid2[i][j] == 1: # if this island is also a sub-island in grid 2 from the other grid if bfs(i, j): c += 1 return c
count-sub-islands
Python BFS || Runtime Beats 93% || Memory Beats 94% -- With explanation :)
yllera
0
4
count sub islands
1,905
0.677
Medium
26,953
https://leetcode.com/problems/count-sub-islands/discuss/2500060/Easy-Python-DFS-solution
class Solution: def countSubIslands(self, grid1: List[List[int]], grid2: List[List[int]]) -> int: valid = True count = 0 nc = len(grid2[0]) nr = len(grid2) def dfs(i, j): nonlocal valid if not (0 <= i < nr and 0 <= j < nc) or grid2[i][j] == 0: return if grid1[i][j] == 0: valid = False return grid2[i][j] = 0 dfs(i+1, j) dfs(i-1, j) dfs(i, j+1) dfs(i, j-1) for i in range(nr): for j in range(nc): if grid2[i][j] == 1: dfs(i,j) count += 1 if valid else 0 valid = True return count
count-sub-islands
Easy Python DFS solution
bubae
0
17
count sub islands
1,905
0.677
Medium
26,954
https://leetcode.com/problems/count-sub-islands/discuss/2357108/Python3-or-Solved-Using-BFS-%2B-Queue-O(n*m)-Complexity!
class Solution: #Time-Complexity: O(n*m + n*m) -> O(n*m) #Space-Complexity: O(n*m + n*m) -> O(n*m) def countSubIslands(self, grid1: List[List[int]], grid2: List[List[int]]) -> int: #Here, we are gauranteed that grid1 and grid2 have same dimension m*n m, n = len(grid1), len(grid1[0]) visited = set() #bfs traversal helper function for traversing each and every island that exists in grid2! #basically checks whether island is sub_island of any given island in grid1! def bfs(sr, sc): nonlocal m, n, visited, grid1, grid2 q = collections.deque() q.append([sr, sc]) visited.add((sr, sc)) #bool flag indicating whether current island is sub_island! I will set to default value True! is_subIsland = True four_directions = [[1, 0], [-1, 0], [0,1], [0,-1]] while q: cr, cc = q.popleft() #check if current land cell is also land cell at same position in grid1! if(grid1[cr][cc] != 1): is_subIsland = False #for each of the four-directional adjacent neighboring cells, add to queue only if #it is in-bounds, land cell, and not already visited! for direction in four_directions: r_change, c_change = direction #do the check I mentioned previously! if(cr+r_change in range(m) and cc + c_change in range(n) and grid2[cr+r_change][cc+c_change] == 1 and (cr+r_change, cc+c_change) not in visited): q.append([cr+r_change, cc+c_change]) visited.add((cr+r_change, cc+c_change)) #once we exit the while loop, our bfs basically traversed each and every land cell starting #from position (sr,sc)! Now, we check the bool_flag! if(is_subIsland): return 1 else: return 0 #run nested for loop and whenever we encounter unvisited land cell in grid2, bfs starting from there! ans = 0 for i in range(m): for j in range(n): if(grid2[i][j] == 1 and (i, j) not in visited): #bfs helper will return either 0 or 1 depending if the island in grid2 is a sub_island! ans += bfs(i, j) return ans
count-sub-islands
Python3 | Solved Using BFS + Queue O(n*m) Complexity!
JOON1234
0
14
count sub islands
1,905
0.677
Medium
26,955
https://leetcode.com/problems/count-sub-islands/discuss/2285940/Python3-DFS.-short-code
class Solution: def countSubIslands(self, grid1: List[List[int]], grid2: List[List[int]]) -> int: C = len(grid2[0]) R = len(grid2) res = 0 def dfs(i,j): p = 1 if (i>=0 and j>=0 and i<R and j<C and grid2[i][j] == 1): if grid1[i][j] == 1: p = 1 else: p = 0 grid2[i][j] = 0 if i<R-1: p *= dfs(i+1,j) if i>0: p *= dfs(i-1,j) if j<C-1: p *= dfs(i,j+1) if j>0: p *= dfs(i,j-1) return p for i in range(R): for j in range(C): if(grid2[i][j] == 1): res += dfs(i,j) return res
count-sub-islands
Python3 DFS. short code
devmich
0
6
count sub islands
1,905
0.677
Medium
26,956
https://leetcode.com/problems/count-sub-islands/discuss/2245669/Simplest-2.8s-(99)-Speed-Python-Solution
class Solution: def countSubIslands(self, grid1: List[List[int]], grid2: List[List[int]]) -> int: """ Two m x n binary matricies grid1 and grid2. Both contain only 0s for water and 1s for land. Island is a group of 1s that connects vertically and horizontally with other land that is part of it. There are no requirements for size, so even isolated land can be an island. Islands in grid2 are sub-islands iff there is an island in grid1 that contains all cells that make up the island in grid2. Return number of sub-islands in grid2. So the land in the grid2 is split into sub-island land and non-sub-island land. First we need to be able to itemize islands in grid2. Then it is enough to check for each if all their elements are also land in grid1. Finding which elements form together an island requires complexity of at least M * N. To check if the islands are sub-islands compute-efficiently will likely require additional storage of M*N. Keep current island number which starts from 2 to not collide with unmarked land number 1. Iterating element from the top to right and then down. If finding unmarked land, then "floodfill" recurse into all 4 directions from that position, while marking unmarked land with island index. Store indices of found island land. Once we have full island, verify if island elements are sub island. To speed up this, we can verify that on the go during the floodfill. """ island_index = 2 sub_island_count = 0 if len(grid2) == 0 and len(grid2[0]) == 0: return 0 def mark_land(i, j): may_be_sub = True if grid2[i][j] == 1: grid2[i][j] = island_index may_be_sub &amp;= grid1[i][j] == 1 if i < len(grid2) - 1 and grid2[i + 1][j] == 1: may_be_sub &amp;= mark_land(i + 1, j) if j < len(grid2[i]) - 1 and grid2[i][j + 1] == 1: may_be_sub &amp;= mark_land(i, j + 1) if i > 0 and grid2[i - 1][j] == 1: may_be_sub &amp;= mark_land(i - 1, j) if j > 0 and grid2[i][j - 1] == 1: may_be_sub &amp;= mark_land(i, j - 1) return may_be_sub # row for i in range(len(grid2)): # column for j in range(len(grid2[0])): if grid2[i][j] == 1: if mark_land(i, j): sub_island_count += 1 return sub_island_count
count-sub-islands
Simplest 2.8s (99%) Speed Python Solution
vaclavkosar
0
28
count sub islands
1,905
0.677
Medium
26,957
https://leetcode.com/problems/count-sub-islands/discuss/2212179/python-3-or-simple-dfs
class Solution: def countSubIslands(self, grid1: List[List[int]], grid2: List[List[int]]) -> int: m, n = len(grid1), len(grid1[0]) def dfs(i, j): if (i == -1 or i == m or j == -1 or j == n or not grid2[i][j]): return True grid2[i][j] = 0 return (grid1[i][j] &amp; dfs(i - 1, j) &amp; dfs(i + 1, j) &amp; dfs(i, j - 1) &amp; dfs(i, j + 1)) subIslands = 0 for i, row in enumerate(grid2): for j, num in enumerate(row): subIslands += num and dfs(i, j) return subIslands
count-sub-islands
python 3 | simple dfs
dereky4
0
22
count sub islands
1,905
0.677
Medium
26,958
https://leetcode.com/problems/count-sub-islands/discuss/2207291/Python-Straightforward-DFS
class Solution: def countSubIslands(self, grid1: List[List[int]], grid2: List[List[int]]) -> int: m, n = len(grid1), len(grid1[0]) def dfs(i, j): isSubset = True if not grid1[i][j]: isSubset = False for x, y in [[i+1, j], [i-1, j], [i, j+1], [i, j-1]]: if 0 <= x < m and 0 <= y < n and grid2[x][y] == 1: grid2[x][y] = 2 if isSubset: isSubset = dfs(x, y) else: dfs(x, y) return isSubset ans = 0 for i in range(m): for j in range(n): if grid2[i][j] == 1: grid2[i][j] = 2 ans += dfs(i, j) return ans
count-sub-islands
Python Straightforward DFS
lukefall425
0
13
count sub islands
1,905
0.677
Medium
26,959
https://leetcode.com/problems/count-sub-islands/discuss/2165946/Simple-DFS-oror-Easy-Explanation
class Solution: def isSafe(self,i,j,matrix): n = len(matrix) m = len(matrix[0]) if 0 <= i < n and 0 <= j < m: return True else: return False def dfs(self,i,j,matrix, subList): if not self.isSafe(i,j,matrix) or matrix[i][j] != 1: return subList.append([i,j]) matrix[i][j] = 2 self.dfs(i,j-1,matrix,subList) self.dfs(i,j+1,matrix,subList) self.dfs(i-1,j,matrix,subList) self.dfs(i+1,j, matrix,subList) def countSubIslands(self, grid1: List[List[int]], grid2: List[List[int]]) -> int: coordinateList = [] n = len(grid2) m = len(grid2[0]) for i in range(n): for j in range(m): if grid2[i][j] == 1: subList = [] self.dfs(i,j,grid2, subList) coordinateList.append(subList) subIslands = 0 for island in coordinateList: count = 0 islandSize = len(island) for coordinate in island: x = coordinate[0] y = coordinate[1] if grid1[x][y] == 1: count += 1 if count == islandSize: subIslands += 1 return subIslands
count-sub-islands
Simple DFS || Easy Explanation
Vaibhav7860
0
46
count sub islands
1,905
0.677
Medium
26,960
https://leetcode.com/problems/count-sub-islands/discuss/2123869/Python3%3A-O(M*N)-Solution-with-Iterative-DFS-(deque)-%2B-Stack
class Solution: def countSubIslands(self, grid1: List[List[int]], grid2: List[List[int]]) -> int: """ Iterative DFS + Stack: O(M*N) """ # base case if not grid1 or not grid2: return 0 ROWS, COLS = len(grid1), len(grid1[0]) DIRECTIONS = [(0,1), (0,-1), (1,0), (-1,0)] def dfs(x, y): from collections import deque stack = deque([(x,y)]) count = (grid1[x][y]==1) while stack: # O(1) x, y = stack.pop() for dx, dy in DIRECTIONS: dx+=x dy+=y if (dx in range(ROWS) and 0<=dy<COLS # check edges and grid2[dx][dy]==1 # check island ): # grid2 not in grid1 if grid1[dx][dy]==0: count = False # O(1) stack.append((dx,dy)) grid2[x][y] = 0 # fill 0 return int(count) res = 0 # O(M*N) for x in range(ROWS): for y in range(COLS): if grid2[x][y] == 1: res+=dfs(x,y) return res
count-sub-islands
Python3: O(M*N) Solution with Iterative DFS (deque) + Stack
yunglinchang
0
22
count sub islands
1,905
0.677
Medium
26,961
https://leetcode.com/problems/count-sub-islands/discuss/2113387/Python3-or-DFS
class Solution: def countSubIslands(self, grid1: List[List[int]], grid2: List[List[int]]) -> int: db = [] def dfs(grid, i, j, temp): if i<0 or j<0 or i>= len(grid) or j>= len(grid[0]) or grid[i][j] == 0: return if grid[i][j] == 1: temp.append((i,j)) grid[i][j] = 0 dfs(grid,i+1, j, temp) dfs(grid,i, j+1, temp) dfs(grid,i-1, j, temp) dfs(grid,i, j-1, temp) return temp for i in range(len(grid2)): for j in range(len(grid2[0])): if grid2[i][j] == 1: x = dfs(grid2, i, j, []) # print(x) db.append(x) def check(l): for x in l: if grid1[x[0]][x[1]] == 0: return False return True count = 0 for l in db: if check(l): count += 1 return count
count-sub-islands
Python3 | DFS
iamirulofficial
0
30
count sub islands
1,905
0.677
Medium
26,962
https://leetcode.com/problems/count-sub-islands/discuss/1362758/Flood-fill-84-speed
class Solution: def countSubIslands(self, grid1: List[List[int]], grid2: List[List[int]]) -> int: water1 = set() for r, row in enumerate(grid1): for c, val in enumerate(row): if not val: water1.add((r, c)) count = 0 land = set() for r, row in enumerate(grid2): for c, val in enumerate(row): if val: land.add((r, c)) while land: start = land.pop() island = {start} neighbors = {start} while neighbors: new_neighbors = set() for r, c in neighbors: for i, j in [(1, 0), (0, 1), (-1, 0), (0, -1)]: new_cell = (r + i, c + j) if new_cell in land: new_neighbors.add(new_cell) land.remove(new_cell) island.update(new_neighbors) neighbors = new_neighbors if not island &amp; water1: count += 1 return count
count-sub-islands
Flood fill, 84% speed
EvgenySH
0
76
count sub islands
1,905
0.677
Medium
26,963
https://leetcode.com/problems/count-sub-islands/discuss/1284495/Python-Why-would-this-DFS-lead-to-TLE
class Solution: def countSubIslands(self, grid1: List[List[int]], grid2: List[List[int]]) -> int: m, n = len(grid1), len(grid1[0]) count = 0 # This DFS will lead to TLE in some test cases def dfs(i, j): queue = collections.deque([(i, j)]) while queue: (x, y) = queue.popleft() grid2[x][y] = 0 for (nx, ny) in [(x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)]: if 0 <= nx < m and 0 <= ny < n and grid2[nx][ny] == 1: queue.append((nx, ny)) # when this DFS would work fine def dfs_2(i,j): if i<0 or i>=m or j<0 or j>=n or grid2[i][j]==0: return grid2[i][j]=0 dfs(i+1,j) dfs(i,j+1) dfs(i,j-1) dfs(i-1,j) for i in range(m): for j in range(n): if grid2[i][j] == 1 and grid1[i][j] != 1: dfs(i, j) for i in range(m): for j in range(n): if grid2[i][j] == 1: dfs(i, j) count += 1 return count
count-sub-islands
[Python] Why would this DFS lead to TLE?
allegri
0
51
count sub islands
1,905
0.677
Medium
26,964
https://leetcode.com/problems/count-sub-islands/discuss/1284300/Easy-%2B-Straightforward-%2B-Clean-Python-BFS
class Solution: def countSubIslands(self, grid1: List[List[int]], grid2: List[List[int]]) -> int: rows = len(grid1) cols = len(grid1[0]) directions = [(1,0),(-1,0),(0,1),(0,-1)] islands = 0 for row in range(rows): for col in range(cols): if grid2[row][col] == 1 and grid1[row][col] == 1: grid2[row][col] = '#' q = collections.deque([]) q.append((row, col)) is_island = True while q: r, c = q.popleft() for y, x in directions: nr = r + y nc = c + x if 0 <= nr < rows and 0 <= nc < cols and grid2[nr][nc] == 1: if grid1[nr][nc] != 1: is_island = False grid2[nr][nc] = '#' q.append((nr, nc)) if is_island: islands += 1 return islands
count-sub-islands
Easy + Straightforward + Clean Python BFS
Pythagoras_the_3rd
0
81
count sub islands
1,905
0.677
Medium
26,965
https://leetcode.com/problems/minimum-absolute-difference-queries/discuss/1284341/Python3-binary-search
class Solution: def minDifference(self, nums: List[int], queries: List[List[int]]) -> List[int]: loc = {} for i, x in enumerate(nums): loc.setdefault(x, []).append(i) keys = sorted(loc) ans = [] for l, r in queries: prev, val = 0, inf for x in keys: i = bisect_left(loc[x], l) if i < len(loc[x]) and loc[x][i] <= r: if prev: val = min(val, x - prev) prev = x ans.append(val if val < inf else -1) return ans
minimum-absolute-difference-queries
[Python3] binary search
ye15
8
681
minimum absolute difference queries
1,906
0.439
Medium
26,966
https://leetcode.com/problems/remove-one-element-to-make-the-array-strictly-increasing/discuss/1298457/Python3-collect-non-conforming-indices
class Solution: def canBeIncreasing(self, nums: List[int]) -> bool: stack = [] for i in range(1, len(nums)): if nums[i-1] >= nums[i]: stack.append(i) if not stack: return True if len(stack) > 1: return False i = stack[0] return (i == 1 or nums[i-2] < nums[i]) or (i+1 == len(nums) or nums[i-1] < nums[i+1])
remove-one-element-to-make-the-array-strictly-increasing
[Python3] collect non-conforming indices
ye15
15
1,200
remove one element to make the array strictly increasing
1,909
0.26
Easy
26,967
https://leetcode.com/problems/remove-one-element-to-make-the-array-strictly-increasing/discuss/1298457/Python3-collect-non-conforming-indices
class Solution: def canBeIncreasing(self, nums: List[int]) -> bool: prev, seen = -inf, False for i, x in enumerate(nums): if prev < x: prev = x else: if seen: return False seen = True if i == 1 or nums[i-2] < x: prev = x return True
remove-one-element-to-make-the-array-strictly-increasing
[Python3] collect non-conforming indices
ye15
15
1,200
remove one element to make the array strictly increasing
1,909
0.26
Easy
26,968
https://leetcode.com/problems/remove-one-element-to-make-the-array-strictly-increasing/discuss/1913864/Python-easy-solution-for-beginners
class Solution: def canBeIncreasing(self, nums: List[int]) -> bool: for i in range(len(nums)): temp = nums[:i] + nums[i+1:] if sorted(temp) == temp: if len(set(temp)) == len(temp): return True return False
remove-one-element-to-make-the-array-strictly-increasing
Python easy solution for beginners
alishak1999
5
337
remove one element to make the array strictly increasing
1,909
0.26
Easy
26,969
https://leetcode.com/problems/remove-one-element-to-make-the-array-strictly-increasing/discuss/2579194/1909.-Remove-One-Element-to-Make-the-Array-Strictly-Increasing
class Solution: def canBeIncreasing(self, nums: List[int]) -> bool: dnums=nums.copy() #make a copy of the original array <nums> for i in range(len(nums)-1): #traverse the first pointer <i> in the original array <nums> if nums[i]>=nums[i+1]: a=nums.pop(i) break if nums==sorted(set(nums)): #we are checking with the sorted array because there might be duplicate elements after 1 pop instruction return True for j in range(len(dnums)-1,0,-1): #traverse the 2nd pointer <j> in the duplicate array <dnums> if dnums[j]<=dnums[j-1]: a=dnums.pop(j) break if dnums==sorted(set(dnums)): return True return False
remove-one-element-to-make-the-array-strictly-increasing
1909. Remove One Element to Make the Array Strictly Increasing
utsa_gupta
3
252
remove one element to make the array strictly increasing
1,909
0.26
Easy
26,970
https://leetcode.com/problems/remove-one-element-to-make-the-array-strictly-increasing/discuss/1591583/Python-3-97-faster
class Solution: def canBeIncreasing(self, nums: List[int]) -> bool: prev = 0 flag = False nums.append(math.inf) i, n = 0, len(nums) - 1 while i < n: if prev < nums[i] < nums[i+1]: prev = nums[i] else: # nums[i] or nums[i+1] should be removed if flag: return False flag = True if nums[i+1] <= prev: # remove nums[i+1] prev = nums[i] i += 1 i += 1 return True
remove-one-element-to-make-the-array-strictly-increasing
Python 3 97% faster
dereky4
3
634
remove one element to make the array strictly increasing
1,909
0.26
Easy
26,971
https://leetcode.com/problems/remove-one-element-to-make-the-array-strictly-increasing/discuss/1504253/2-line-in-Python-quite-expensive
class Solution: def canBeIncreasing(self, nums: List[int]) -> bool: is_increasing = lambda l: all(x < y for x, y in zip(l, l[1:])) return any(is_increasing(nums[:i] + nums[(i + 1):]) for i in range(len(nums)))
remove-one-element-to-make-the-array-strictly-increasing
2-line in Python, quite expensive
mousun224
3
501
remove one element to make the array strictly increasing
1,909
0.26
Easy
26,972
https://leetcode.com/problems/remove-one-element-to-make-the-array-strictly-increasing/discuss/1303282/Python-or-O(n)-or-Using-pointers
class Solution: def canBeIncreasing(self, nums: List[int]) -> bool: l = 0 r = 1 skipped = -1 while r < len(nums): # Normal case, strictly increasing array if nums[l] < nums[r]: l+=1 if l == skipped: l+=1 r+=1 continue # found non increasing point if skipped >= 0: return False # Corner case # l r # 100 21 100 # dip<<< if r == 1: skipped = 0 l+=1 r+=1 # l-1 l r # 100, 200, 500, 300, 400 # <<<hill>>> elif nums[l-1] < nums[r]: skipped = l l = l-1 # l-1 l r # 100, 300, 500, 200, 400 # >>>dip<<< else: skipped = r r += 1 return True
remove-one-element-to-make-the-array-strictly-increasing
Python | O(n) | Using pointers
sorokinpa
3
475
remove one element to make the array strictly increasing
1,909
0.26
Easy
26,973
https://leetcode.com/problems/remove-one-element-to-make-the-array-strictly-increasing/discuss/2578205/1909.-Remove-One-Element-to-Make-the-Array-Strictly-Increasing
class Solution: def canBeIncreasing(self, nums: List[int]) -> bool: for i in range(len(nums)): a=nums.pop(i) #print(nums) if nums==sorted(set(nums)): return True else: nums.insert(i,a) #i+=1 #print(nums) return False
remove-one-element-to-make-the-array-strictly-increasing
1909. Remove One Element to Make the Array Strictly Increasing
shagun_pandey
2
109
remove one element to make the array strictly increasing
1,909
0.26
Easy
26,974
https://leetcode.com/problems/remove-one-element-to-make-the-array-strictly-increasing/discuss/1298577/Python-Easy%3A-O(n)-Time-and-O(1)-space
class Solution: def canBeIncreasing(self, nums: List[int]) -> bool: min_count = max_count = 0 end = len(nums) - 1 min_no = float('inf') max_no = float('-inf') while end >= 0: if nums[end] < min_no: min_no = nums[end] else: min_count +=1 end -= 1 for i in range(0,len(nums)): if nums[i] > max_no: max_no = nums[i] else: max_count +=1 if min_count > 1 and max_count > 1: return False return True ```
remove-one-element-to-make-the-array-strictly-increasing
Python Easy: O(n) Time and O(1) space
im_ram
2
370
remove one element to make the array strictly increasing
1,909
0.26
Easy
26,975
https://leetcode.com/problems/remove-one-element-to-make-the-array-strictly-increasing/discuss/2249478/Easiest-Solution-Python
class Solution(object): def canBeIncreasing(self, nums): """ :type nums: List[int] :rtype: bool """ def isIncreasing(nums): n = len(nums) for i in range(n-1): if nums[i]>=nums[i+1]: return False return True for i in range(len(nums)): if isIncreasing(nums[:i]+nums[i+1:]): return True return False
remove-one-element-to-make-the-array-strictly-increasing
Easiest Solution Python
Abhi_009
1
257
remove one element to make the array strictly increasing
1,909
0.26
Easy
26,976
https://leetcode.com/problems/remove-one-element-to-make-the-array-strictly-increasing/discuss/2190982/Python-simple-yet-effective-solution
class Solution: def canBeIncreasing(self, nums: List[int]) -> bool: for i in range(len(nums)-1): if nums[i] >= nums[i+1]: if sorted(list(set(nums[:i]+nums[i+1:]))) == nums[:i]+nums[i+1:] or sorted(list(set(nums[:i+1]+nums[i+2:]))) == nums[:i+1]+nums[i+2:]: return True else: return False return sorted(list(set(nums))) == nums
remove-one-element-to-make-the-array-strictly-increasing
Python simple yet effective solution
StikS32
1
173
remove one element to make the array strictly increasing
1,909
0.26
Easy
26,977
https://leetcode.com/problems/remove-one-element-to-make-the-array-strictly-increasing/discuss/2089046/Python3-Two-pass-monotonic-stack-or-O(n)
class Solution: def canBeIncreasing(self, A: List[int]) -> bool: dec1 = 0 stk = [] for i in range(len(A)): while stk and A[stk[-1]]>=A[i]: stk.pop() dec1 += 1 stk.append(i) dec2 = 0 stk = [] for i in reversed(range(len(A))): while stk and A[stk[-1]]<=A[i]: stk.pop() dec2 += 1 stk.append(i) return min(dec1, dec2)<=1
remove-one-element-to-make-the-array-strictly-increasing
[Python3] Two pass monotonic stack | O(n)
zhuzhengyuan824
1
129
remove one element to make the array strictly increasing
1,909
0.26
Easy
26,978
https://leetcode.com/problems/remove-one-element-to-make-the-array-strictly-increasing/discuss/2845238/Python-sum()-%2B-list-comprehension-beats-94.23-runtime-and-98.61-mem-usage
class Solution: def canBeIncreasing(self, nums: List[int]) -> bool: x1 = sum(1 for i in range(1, len(nums)) if nums[i] <= nums[i - 1]) if not 0 <= x1 < 2: return False x2 = sum(1 for i in range(2, len(nums)) if nums[i] <= nums[i - 2]) return 0 <= x1 < 2 and 0 <= x2 < 2
remove-one-element-to-make-the-array-strictly-increasing
Python sum() + list comprehension beats 94.23% runtime & 98.61% mem usage
Molot84
0
1
remove one element to make the array strictly increasing
1,909
0.26
Easy
26,979
https://leetcode.com/problems/remove-one-element-to-make-the-array-strictly-increasing/discuss/2818849/Python-solution-beats-86
class Solution: def canBeIncreasing(self, nums: List[int]) -> bool: # when d is too low, check d - 1 and d + 1 def dPlusOneMinusOne(d): if d == len(nums) - 1: return True return nums[d + 1] > nums[d - 1] # when d - 1 is too high, check d and d - 2 def dDMinusTwo(d): if d == 1: return True return nums[d] > nums[d - 2] flipped = False for i in range(1, len(nums)): if not (nums[i] > nums[i - 1]): if not flipped and (dPlusOneMinusOne(i) or dDMinusTwo(i)): flipped = True else: return False return True
remove-one-element-to-make-the-array-strictly-increasing
Python solution beats 86%
StacyAceIt
0
4
remove one element to make the array strictly increasing
1,909
0.26
Easy
26,980
https://leetcode.com/problems/remove-one-element-to-make-the-array-strictly-increasing/discuss/2768414/Amateur-Programmer
class Solution: def canBeIncreasing(self, nums: List[int]) -> bool: a = Counter(nums) valueList=list(a.values()) lenValueList = len(valueList) Sum = sum(valueList) print( lenValueList,Sum) if lenValueList ==2: return True if lenValueList == Sum-1 : # print("possible") duplicate=list(a.keys())[valueList.index(2)] firstPos=nums.index(duplicate) secondPos=nums.index(duplicate,firstPos+1) print(duplicate,firstPos,nums[firstPos],secondPos,nums[secondPos]) if secondPos == firstPos+1: del nums[secondPos] elif nums[firstPos] < nums[firstPos+1]: del nums[secondPos] else: del nums[firstPos] a=[] a.extend(nums) a.sort() return nums==a elif lenValueList == Sum: for i in range(0,len(nums)-1): if nums[i]>nums[i+1] : # print(i,nums[i]) if i not in [0,lenValueList]: print("min",i,min(nums[:i]),min(nums[i:])) if min(nums[:i]) < min(nums[i:]) and max(nums[:i]) < min(nums[i:]) : del nums[i] else: del nums[i+1] else: del nums[i] break; a=[] a.extend(nums) a.sort() print(nums,a,nums==a) return nums==a else: return False
remove-one-element-to-make-the-array-strictly-increasing
Amateur Programmer
benosambenjamin
0
4
remove one element to make the array strictly increasing
1,909
0.26
Easy
26,981
https://leetcode.com/problems/remove-one-element-to-make-the-array-strictly-increasing/discuss/2746318/Not-the-most-pretty-but-very-space-efficient-a-couple-of-ifs.-(Python)
class Solution: def canBeIncreasing(self, nums: List[int]) -> bool: removed = 0 nums.append(1001) # ignore the need to check edge if nums[0] >= nums[1]: removed = 1 i=1 # I've already checked the first ind while i<len(nums)-2: if nums[i]<nums[i+1]: i+=1 else: if removed == 1: return False else: # This code will run only once, so it can contain two ifs. # there are two options to check if possible. # either I can skip if nums[i-1]<nums[i+1]: i = i+1 removed = 1 # or I need to skip i+1 elif nums[i]< nums[i+2]: i = i+2 removed = 1 else: return False return True
remove-one-element-to-make-the-array-strictly-increasing
Not the most pretty, but very space efficient, a couple of ifs. (Python)
orena1
0
2
remove one element to make the array strictly increasing
1,909
0.26
Easy
26,982
https://leetcode.com/problems/remove-one-element-to-make-the-array-strictly-increasing/discuss/2407263/python-code-with-explanation
class Solution: def canBeIncreasing(self, nums: List[int]) -> bool: #initialise the count variable to 0 count = 0 #iterate over the indexes in nums for i in range(len(nums)): #create another list(arr) for each index after removing the element at current index arr = nums[:i] + nums[i+1:] #iterate over the new list for j in range(len(arr)-1): #check if the current element in the list is less the next element if arr[j] < arr[j+1]: #then increase the count value by 1 count = count + 1 else: #if not break because it is not strictly increasing break #if the arr-->list is strictly increasing #then second for loop will iterate all the elements in the newlist #and count will become equal to it's length if count == len(arr)-1: #then return True return True #after each for loop reset count value to 0 count = 0 #return False because we cannot create the increasing sublist #after deleting one element in list return False
remove-one-element-to-make-the-array-strictly-increasing
python code with explanation
thomanani
0
145
remove one element to make the array strictly increasing
1,909
0.26
Easy
26,983
https://leetcode.com/problems/remove-one-element-to-make-the-array-strictly-increasing/discuss/2376183/Simple-Python3-Solution-With-Clear-Explanation
class Solution: def canBeIncreasing(self, nums: List[int]) -> bool: for i in range(len(nums)): l = nums.copy() l.pop(i) if l == sorted(set(l)): return True else: continue return False
remove-one-element-to-make-the-array-strictly-increasing
Simple Python3 Solution With Clear Explanation
vem5688
0
139
remove one element to make the array strictly increasing
1,909
0.26
Easy
26,984
https://leetcode.com/problems/remove-one-element-to-make-the-array-strictly-increasing/discuss/1949876/Python3-89-faster-(53ms)
class Solution: def canBeIncreasing(self, nums: List[int]) -> bool: cnt = 0 for idx in range(1, len(nums)): if nums[idx] <= nums[idx - 1]: cnt += 1 if idx >= 2 and idx+1<len(nums): if nums[idx] <= nums[idx - 2] and nums[idx+1] <= nums[idx - 1]: return False if cnt > 1: return False return True
remove-one-element-to-make-the-array-strictly-increasing
Python3 89% faster (53ms)
alessiogatto
0
321
remove one element to make the array strictly increasing
1,909
0.26
Easy
26,985
https://leetcode.com/problems/remove-one-element-to-make-the-array-strictly-increasing/discuss/1875146/Python-Solution
class Solution: def canBeIncreasing(self, nums: List[int]) -> bool: def check(num): for i in range(1,len(num)): if num[i] < num[i-1]+1: return False return True num = nums for i in range(len(nums)): num = nums[:i] + nums[i+1:] if num == sorted(num): if check(num): return True return False
remove-one-element-to-make-the-array-strictly-increasing
Python Solution
AakRay
0
126
remove one element to make the array strictly increasing
1,909
0.26
Easy
26,986
https://leetcode.com/problems/remove-one-element-to-make-the-array-strictly-increasing/discuss/1847227/4-Lines-Python-Solution-oror-30-Faster-oror-Memory-less-than-70
class Solution: def canBeIncreasing(self, nums: List[int]) -> bool: for i in range(len(nums)): x = nums[:i]+nums[i+1:] if sorted(x)==x and len(set(x))==len(x): return True return False
remove-one-element-to-make-the-array-strictly-increasing
4-Lines Python Solution || 30% Faster || Memory less than 70%
Taha-C
-1
186
remove one element to make the array strictly increasing
1,909
0.26
Easy
26,987
https://leetcode.com/problems/remove-all-occurrences-of-a-substring/discuss/1298899/Python3-kmp
class Solution: def removeOccurrences(self, s: str, part: str) -> str: lps = [0] k = 0 for i in range(1, len(part)): while k and part[k] != part[i]: k = lps[k-1] if part[k] == part[i]: k += 1 lps.append(k) stack = [("", 0)] for ch in s: k = stack[-1][1] while k and part[k] != ch: k = lps[k-1] if part[k] == ch: k += 1 stack.append((ch, k)) if k == len(part): for _ in range(len(part)): stack.pop() return "".join(x for x, _ in stack)
remove-all-occurrences-of-a-substring
[Python3] kmp
ye15
9
955
remove all occurrences of a substring
1,910
0.742
Medium
26,988
https://leetcode.com/problems/remove-all-occurrences-of-a-substring/discuss/1298489/Python3-stack
class Solution: def removeOccurrences(self, s: str, part: str) -> str: stack = [] for ch in s: stack.append(ch) if "".join(stack[-len(part):]) == part: for _ in range(len(part)): stack.pop() return "".join(stack)
remove-all-occurrences-of-a-substring
[Python3] stack
ye15
9
590
remove all occurrences of a substring
1,910
0.742
Medium
26,989
https://leetcode.com/problems/remove-all-occurrences-of-a-substring/discuss/2289367/Python-Simple-solution-Easy-to-Understand-Python-for-beginners
class Solution: def removeOccurrences(self, s: str, part: str) -> str: l = len(part) while True: for i in range(len(s)-l+1): if s[i:i+l] == part: s = s[:i] + s[i+l:] break if part not in s: return s
remove-all-occurrences-of-a-substring
Python, Simple solution, Easy to Understand, Python for beginners
Nish786
1
104
remove all occurrences of a substring
1,910
0.742
Medium
26,990
https://leetcode.com/problems/remove-all-occurrences-of-a-substring/discuss/1899394/Python-easy-solution-with-memory-less-than-83
class Solution: def removeOccurrences(self, s: str, part: str) -> str: while True: if part in s: s = s.replace(part, '', 1) else: return s
remove-all-occurrences-of-a-substring
Python easy solution with memory less than 83%
alishak1999
1
164
remove all occurrences of a substring
1,910
0.742
Medium
26,991
https://leetcode.com/problems/remove-all-occurrences-of-a-substring/discuss/1877372/Python-4-lines-Solution
class Solution: def removeOccurrences(self, s: str, part: str) -> str: string=s.replace(part,"",1) while part in string: string=string.replace(part,"",1) return string
remove-all-occurrences-of-a-substring
Python 4 lines Solution
amannarayansingh10
1
151
remove all occurrences of a substring
1,910
0.742
Medium
26,992
https://leetcode.com/problems/remove-all-occurrences-of-a-substring/discuss/1512766/python-recursive-solution
class Solution: def removeOccurrences(self, s: str, part: str) -> str: if part not in s: return s start_ind = s.index(part) removed_string = s[:start_ind] + s[(start_ind+len(part)):] return self.removeOccurrences(removed_string, part)
remove-all-occurrences-of-a-substring
python recursive solution
PallabPaul
1
178
remove all occurrences of a substring
1,910
0.742
Medium
26,993
https://leetcode.com/problems/remove-all-occurrences-of-a-substring/discuss/1303658/Easy-and-fast-Python3-3-lines
class Solution: def removeOccurrences(self, s: str, part: str) -> str: while s.count(part)>0: s=s.replace(part,"",1) return s
remove-all-occurrences-of-a-substring
Easy and fast Python3 3 lines
svr300
1
75
remove all occurrences of a substring
1,910
0.742
Medium
26,994
https://leetcode.com/problems/remove-all-occurrences-of-a-substring/discuss/2829203/Python-Solution-Using-Stack-oror-Explained-oror-EASY
class Solution: def removeOccurrences(self, s: str, part: str) -> str: n=len(part) #store length of part if len(s)<n: #if string is short then nothing to remove from it, return as it is return s stack=[] #form stack for i in range(len(s)): #traverse through s #push every element in stack stack.append(s[i]) #if current s[i] is equal to last chracter of part that #means there are the chances of part to be present in stack if s[i]==part[-1] and len(stack)>=n: #convert stack to string and take out substring only equal to the length of part #so that it can be compared from part check="".join(stack)[len(stack)-n:] #if part present in stack if check==part: j=n #pop till the length of pop (as part is present from the right side of stack) while j!=0: stack.pop() j-=1 #this is how operations will take place in every traversal return "".join(stack) #return remaining string
remove-all-occurrences-of-a-substring
Python Solution - Using Stack || Explained || EASY✔
T1n1_B0x1
0
5
remove all occurrences of a substring
1,910
0.742
Medium
26,995
https://leetcode.com/problems/remove-all-occurrences-of-a-substring/discuss/2802264/Python%3A-Easy-Read-Slide-window-solution-with-a-string-to-memorize
class Solution: def removeOccurrences(self, s: str, part: str) -> str: ans = "" n = len(part) for c in s: ans += c n2 = len(ans) if n2 >= n and ans[n2-n:] == part: ans = ans[:n2-n] return ans
remove-all-occurrences-of-a-substring
Python: Easy Read, Slide window solution with a string to memorize
stanleyyuen_pang
0
4
remove all occurrences of a substring
1,910
0.742
Medium
26,996
https://leetcode.com/problems/remove-all-occurrences-of-a-substring/discuss/2694743/Python-Solution-or-Stack
class Solution: def removeOccurrences(self, s: str, part: str) -> str: stack=[] n=len(s) m=len(part) part=list(part) for i in range(n): stack.append(s[i]) # print(stack[-m:]) if len(stack)>=m and stack[-m:]==part: for j in range(m): stack.pop() return ''.join(stack)
remove-all-occurrences-of-a-substring
Python Solution | Stack
Siddharth_singh
0
9
remove all occurrences of a substring
1,910
0.742
Medium
26,997
https://leetcode.com/problems/remove-all-occurrences-of-a-substring/discuss/2687583/92-Accepted-or-Pythonic-Way-or-Two-Liner-or-Easy-to-Understand
class Solution(object): def removeOccurrences(self, s, part): while part in s: s = s.replace(part, "", 1) return s
remove-all-occurrences-of-a-substring
92% Accepted | Pythonic Way | Two Liner | Easy to Understand
its_krish_here
0
5
remove all occurrences of a substring
1,910
0.742
Medium
26,998
https://leetcode.com/problems/remove-all-occurrences-of-a-substring/discuss/2631232/PYTHON-EASY-to-understand-using-Replace
class Solution: def removeOccurrences(self, s: str, part: str) -> str: while part in s: a = s.replace(part,'',1) s = a return s
remove-all-occurrences-of-a-substring
PYTHON, EASY to understand, using Replace
mayank0936
0
12
remove all occurrences of a substring
1,910
0.742
Medium
26,999