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/minimum-remove-to-make-valid-parentheses/discuss/1850493/Python3-Simple-Stack-and-a-Hashset-solution | class Solution:
def minRemoveToMakeValid(self, s: str) -> str:
st = []
for i,ch in enumerate(s):
if ch == "(":
st.append((i,"("))
elif ch == ")":
st.pop() if st and st[-1][1] == "(" else st.append((i,")"))
invalid_set = set([val[0] for val in st])
res = ''
for i in range(len(s)):
if i not in invalid_set:
res += s[i]
return res | minimum-remove-to-make-valid-parentheses | [Python3] Simple Stack and a Hashset solution | nandhakiran366 | 0 | 8 | minimum remove to make valid parentheses | 1,249 | 0.657 | Medium | 18,700 |
https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/discuss/1850200/Beginner-python3-solution | class Solution:
def minRemoveToMakeValid(self, s: str) -> str:
op = 0
cl = 0
idx=0
s_=''
for i in range(len(s)):
if s[i] == '(':
num = max(i,idx)
for j in range(num,len(s)):
if s[j] == ')':
op +=1
s_+=s[i]
idx = j+1
break
elif s[i] == ")":
cl +=1
if cl<=op:
s_+=s[i]
else:
cl-=1
else:
s_+=s[i]
return s_ | minimum-remove-to-make-valid-parentheses | Beginner python3 solution | sarah757 | 0 | 17 | minimum remove to make valid parentheses | 1,249 | 0.657 | Medium | 18,701 |
https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/discuss/1828876/Python-or-Detailed-Approach-with-Comments-or-O(n)-Time-and-Space | class Solution:
def minRemoveToMakeValid(self, s: str) -> str:
stack = [] #initialize a stack to keep track of the indices with '('
N = len(s) #length of the input
S = list(s) #using the string as a list
for i in range(N):
if S[i] == '(': #if the character is an open bracket
stack.append(i) #append it to the stack
elif S[i] == ')': #if the chracter is a close bracket
if stack: #and if a stack exists
stack.pop() #pop the last pushed open bracket
else: #if there is no stack
S[i] = '' #delete the unbalanced close bracket
for level in stack: #iterate through the unbalanced open brackets
S[level] = '' #and delete them
return "".join(S) #finally join the list and return the string | minimum-remove-to-make-valid-parentheses | Python | Detailed Approach with Comments | O(n) Time and Space | r3d-panda | 0 | 200 | minimum remove to make valid parentheses | 1,249 | 0.657 | Medium | 18,702 |
https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/discuss/1747300/Python3-76-ms-solution-(faster-than-99) | class Solution:
def minRemoveToMakeValid(self, s: str) -> str:
newStr, bal = "", 0
for char in s:
# if open paranthesis, increment balance
if char == "(":
bal += 1
newStr += char
# if closing paranthesis, check if there are excess (
# if there are excess (, then incude it else dicard
elif char == ")":
if bal != 0:
bal -= 1
newStr += char
# its not a paranthesis, so include
else: newStr += char
# start from end of new string and keep going left until balance is reached
i = len(newStr) - 1
while bal > 0:
# if open paranthesis, discard and decrement balance
if newStr[i] == "(": newStr, bal = newStr[:i] + newStr[i + 1:], bal - 1
i -= 1
return newStr | minimum-remove-to-make-valid-parentheses | [Python3] 76 ms solution (faster than 99%) | dayeem | 0 | 36 | minimum remove to make valid parentheses | 1,249 | 0.657 | Medium | 18,703 |
https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/discuss/1692995/Python-using-stack.-O(N)O(N) | class Solution:
def minRemoveToMakeValid(self, s: str) -> str:
bad = []
stack = []
for i, c in enumerate(s):
if c == '(':
stack.append(i)
elif c == ')':
if stack:
stack.pop()
else:
bad.append(i)
bad = set(bad + stack)
return "".join(c for i, c in enumerate(s) if i not in bad) | minimum-remove-to-make-valid-parentheses | Python, using stack. O(N)/O(N) | blue_sky5 | 0 | 41 | minimum remove to make valid parentheses | 1,249 | 0.657 | Medium | 18,704 |
https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/discuss/1682222/Python3-Solution-oror-Faster-than-98.98 | class Solution:
def minRemoveToMakeValid(self, s: str) -> str:
res = []
counter = 0
for letter in s:
if letter == '(':
counter += 1
res.append(letter)
elif letter == ')':
if counter == 0:
continue
else:
counter -= 1
res.append(letter)
else:
res.append(letter)
temp = []
while counter != 0:
letter = res.pop()
if letter == '(':
counter -= 1
else:
temp.append(letter)
while temp:
letter = temp.pop()
res.append(letter)
ans = ''.join(res)
return ans | minimum-remove-to-make-valid-parentheses | Python3 Solution || Faster than 98.98% | jdavidarreola98 | 0 | 39 | minimum remove to make valid parentheses | 1,249 | 0.657 | Medium | 18,705 |
https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/discuss/1673957/Python-Sol.-Faster-than-96.7 | class Solution:
def minRemoveToMakeValid(self, s: str) -> str:
stack = []
s_list = list(s)
for i in range(len(s)):
if s[i] == '(':
stack.append(i)
if s[i] == ')':
if stack:
stack.pop()
else:
s_list[i] = ''
for ind in stack:
s_list[ind] = ''
return "".join(s_list) | minimum-remove-to-make-valid-parentheses | Python Sol. Faster than 96.7% | josejassojr | 0 | 112 | minimum remove to make valid parentheses | 1,249 | 0.657 | Medium | 18,706 |
https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/discuss/1659154/Help-with-Time-and-Space-complexity | class Solution:
def minRemoveToMakeValid(self, s: str) -> str:
stack = [] # ---> O(n) Space
S = list(s) # ---> O(n) Space
for i in range(len(S)):
if S[i] == '(':
stack.append(i)
elif S[i] == ')':
if stack:
stack.pop()
else:
S[i] = ''
for j in stack:
S[j] = ''
return ''.join(S)
# Time: O(n + m)
# Space: O(2n) | minimum-remove-to-make-valid-parentheses | Help with Time & Space complexity | KoalaKeys | 0 | 15 | minimum remove to make valid parentheses | 1,249 | 0.657 | Medium | 18,707 |
https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/discuss/1555677/Simple-Python-solution | class Solution(object):
def minRemoveToMakeValid(self, s):
stack=[]
mismatchRight=set()
for idx,c in enumerate(s):
if c=='(':
stack.append(idx)
elif c==')':
if stack:
stack.pop()
else:
mismatchRight.add(idx)
stack=set(stack)
return "".join(c for idx,c in enumerate(s) if idx not in stack and idx not in mismatchRight ) | minimum-remove-to-make-valid-parentheses | Simple Python 🐍 solution | InjySarhan | 0 | 258 | minimum remove to make valid parentheses | 1,249 | 0.657 | Medium | 18,708 |
https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/discuss/1520048/Python-using-a-set-of-bad-indices.-Time%3A-O(N)-Space%3A-O(N) | class Solution:
def minRemoveToMakeValid(self, s: str) -> str:
opened = []
closed = []
for idx, c in enumerate(s):
if c == '(':
opened.append(idx)
elif c == ')':
if opened:
opened.pop()
else:
closed.append(idx)
bad_indices = set(opened + closed)
return "".join(c for idx, c in enumerate(s) if idx not in bad_indices) | minimum-remove-to-make-valid-parentheses | Python, using a set of bad indices. Time: O(N), Space: O(N) | blue_sky5 | 0 | 41 | minimum remove to make valid parentheses | 1,249 | 0.657 | Medium | 18,709 |
https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/discuss/1520042/Python-O(N)-two-pass | class Solution:
def minRemoveToMakeValid(self, s: str) -> str:
result = []
opened = 0
for ch in s:
if ch == '(':
opened += 1
elif ch == ')':
if opened > 0:
opened -= 1
else:
continue
result.append(ch)
if opened == 0:
return "".join(result)
opened = 0
result2 = []
for ch in reversed(result):
if ch == ')':
opened += 1
elif ch == '(':
if opened > 0:
opened -= 1
else:
continue
result2.append(ch)
return "".join(reversed(result2)) | minimum-remove-to-make-valid-parentheses | Python, O(N) two pass | blue_sky5 | 0 | 38 | minimum remove to make valid parentheses | 1,249 | 0.657 | Medium | 18,710 |
https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/discuss/1509905/python-simple-O(n)-time-O(n)-space-solution-with-stack | class Solution:
def minRemoveToMakeValid(self, s: str) -> str:
n = len(s)
stack = []
h = {}
for i in range(n):
h[i] = s[i]
for i in range(n):
if s[i] == '(' or s[i] == ')':
if stack and h[stack[-1]] == '(' and s[i] == ')':
stack.pop()
else:
stack.append(i)
seen = set(stack)
res = ''
for i in range(n):
if i not in seen:
res += s[i]
return res | minimum-remove-to-make-valid-parentheses | python simple O(n) time, O(n) space solution with stack | byuns9334 | 0 | 187 | minimum remove to make valid parentheses | 1,249 | 0.657 | Medium | 18,711 |
https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/discuss/1453224/PyPy3-Simple-solution-w-comments | class Solution:
def minRemoveToMakeValid(self, s: str) -> str:
# Init
stack = []
mistmatch = []
n = len(s)
# Scan each chars in string
for i in range(n):
# Add index of "(" to stack
if s[i] == "(":
stack.append(i)
# Pop the index of "(" from stack
# if stack is not empty, else there
# is a mistmatch. In case of mismatch
# add the current index to "mistmatch" array.
# These indexes represents unbalanced ")"
# brackets.
elif s[i] == ")":
if stack:
stack.pop()
else:
mistmatch.append(i)
else:
pass
# Add all remaining indexes in stack to
# "mistmatch" array, these indexes represents
# unbalanced "(" brackets. Sort the entire
# "mistmatch" array in reverse order.
# Remove all the character at the indexex in
# "mistmatch" array.
# NOTE: Sorting in reverse order is important
# as we should keep other chars in string intact
# while removing the given index.
mistmatch = sorted(mistmatch + stack, reverse=True)
for i in mistmatch:
s = s[:i] + s[i+1:]
return s | minimum-remove-to-make-valid-parentheses | [Py/Py3] Simple solution w/ comments | ssshukla26 | 0 | 98 | minimum remove to make valid parentheses | 1,249 | 0.657 | Medium | 18,712 |
https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/discuss/1075850/Python-or-99-60ms-No-Stack | class Solution:
def minRemoveToMakeValid(self, s: str) -> str:
left = right = 0
for i in (s):
if i is '(':
left+=1
elif i is ')':
right+=1
if right > left:
s = s.replace(')', "", 1)
right -= 1
while left != right:
idx = s.rindex("(")
s = s[:idx] + s[idx+1:]
left-=1
return s | minimum-remove-to-make-valid-parentheses | Python | 99% 60ms No Stack | D4NDK | 0 | 113 | minimum remove to make valid parentheses | 1,249 | 0.657 | Medium | 18,713 |
https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/discuss/1073817/PythonPython3-Minimum-Remove-to-Make-Valid-Parentheses | class Solution:
def minRemoveToMakeValid(self, s: str) -> str:
# initialize stack where we will store the brackets that need to be removes along with their index
stack = []
# Here we start the iteration and put necessary brackets in and out of stack
for idx, letter in enumerate(s):
# if we get an open bracket we just append that to stack
if letter == '(':
stack.append((letter, idx))
# if we get a closed bracket
elif letter == ')':
# if the stack is non-empty
if stack:
# we check if the last element is the open bracket. If it is then we pop it as we have found a pair of
# open close bracket and that is included in the valid strings
if stack[-1][0] == '(':
stack.pop()
# if the last element in the existing stack is not an open bracket then we just add the closed bracket
# that need to be omitted from the final string
else:
stack.append((letter, idx))
# if the stack is empty then just add the closed bracket with its index to stack
else:
stack.append((letter, idx))
# initialize the final string as empty
final = ''
# if the string is unbalanced then the stack will be non-empty
# and hence we slice the string till the index of the first element of the stack
if stack:
final += s[:stack[0][1]]
# if the string is unbalanced then stack will be non-empty
if stack:
# so we run a for loop to get the
# the strings that are between the indices of the elements of the stack by slicing the original string
for idx in range(1, len(stack)):
start = stack[idx-1][1] # this gives us the position of the unwanted string from where to start
end = stack[idx][1] # this gives us the position of the unwanted string from where to end
final += s[start + 1:end] # this gives us the string that is ok to be included in final string
# this is to take all the elements that are valid and after the last unwanted element
# that is in the stack
final += s[stack[-1][1]+1:]
else:
# if there is no stack then the string is valid and return the string as is
return s
return final | minimum-remove-to-make-valid-parentheses | [Python/Python3] Minimum Remove to Make Valid Parentheses | newborncoder | 0 | 133 | minimum remove to make valid parentheses | 1,249 | 0.657 | Medium | 18,714 |
https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/discuss/1073518/Python-O(n)-No-string-separation-to-letters.-99time-96space | class Solution:
def minRemoveToMakeValid(self, s: str) -> str:
q = []
rem = [-1]
for i, c in enumerate(s):
if c == '(':
q.append(i)
elif c == ')':
if q:
q.pop()
else:
rem.append(i)
rem.extend(q)
res = []
for i in range(1, len(rem)):
res.append(s[rem[i-1]+1: rem[i]])
res.append(s[rem[-1]+1:])
return ''.join(res) | minimum-remove-to-make-valid-parentheses | [Python] O(n) No string separation to letters. 99%time 96%space | yfer | 0 | 37 | minimum remove to make valid parentheses | 1,249 | 0.657 | Medium | 18,715 |
https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/discuss/1073345/python-on-solution | class Solution:
def minRemoveToMakeValid(self, s: str) -> str:
stack = list()
for i in range(len(s)):
char = s[i]
if char == '(':
stack.append((char,i))
elif char == ')':
if stack and stack[-1][0] == '(':
stack.pop()
else:
stack.append((char,i))
if not stack:
return s
else:
output = str()
remove_index_set = set()
for tup in stack:
remove_index_set.add(tup[1])
for i in range(len(s)):
if i not in remove_index_set:
output += s[i]
return output | minimum-remove-to-make-valid-parentheses | python on solution | yingziqing123 | 0 | 26 | minimum remove to make valid parentheses | 1,249 | 0.657 | Medium | 18,716 |
https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/discuss/491136/Python3-simple-solution-using-a-temporary-stack | class Solution:
def minRemoveToMakeValid(self, s: str) -> str:
s,temp = list(s), []
for i in range(len(s)):
if s[i] in ["(",")"]:
if not temp: temp.append((i,s[i]))
elif temp[-1][-1]=="(" and s[i] == ")": temp.pop()
else: temp.append((i,s[i]))
for item in temp: s[item[0]] = None
res = ""
for char in s:
if char is not None: res += char
return res | minimum-remove-to-make-valid-parentheses | Python3 simple solution using a temporary stack | jb07 | 0 | 31 | minimum remove to make valid parentheses | 1,249 | 0.657 | Medium | 18,717 |
https://leetcode.com/problems/check-if-it-is-a-good-array/discuss/1489417/This-problem-is-about-chinese-remainder-theorem. | class Solution:
def isGoodArray(self, nums: List[int]) -> bool:
import math
n = len(nums)
if n ==1:
return nums[0] ==1
d = math.gcd(nums[0], nums[1])
for i in range(n):
d = math.gcd(nums[i], d)
return d ==1 | check-if-it-is-a-good-array | This problem is about chinese remainder theorem. | byuns9334 | 2 | 244 | check if it is a good array | 1,250 | 0.589 | Hard | 18,718 |
https://leetcode.com/problems/check-if-it-is-a-good-array/discuss/2777568/python-easy-solution-using-Euclidean-algorithm | class Solution:
def gcd(self,a,b):
while a%b != 0:
mod = a%b
a = b
b = mod
return b
def isGoodArray(self, nums: List[int]) -> bool:
gc = nums[0]
for i in range(1,len(nums)):
gc = self.gcd(gc,nums[i])
return True if gc == 1 else False | check-if-it-is-a-good-array | python easy solution using Euclidean algorithm | benon | 0 | 8 | check if it is a good array | 1,250 | 0.589 | Hard | 18,719 |
https://leetcode.com/problems/check-if-it-is-a-good-array/discuss/2739714/Python-easy-and-well-explain-solution | class Solution:
def isGoodArray(self, nums: List[int]) -> bool:
#note: math.gcd function only used in Python3
#Using *nums we can pass full array as a argument
if math.gcd(*nums) == 1:
return True
else:
return False | check-if-it-is-a-good-array | Python 🐍 easy and well explain solution | ride-coder | 0 | 4 | check if it is a good array | 1,250 | 0.589 | Hard | 18,720 |
https://leetcode.com/problems/check-if-it-is-a-good-array/discuss/924192/Python3-using-reduce-function-beats-100 | class Solution:
def isGoodArray(self, nums: List[int]) -> bool:
from functools import reduce
def gcd (a,b):
while b:
a, b = b, a%b
return a
from math import gcd
if reduce(gcd, nums) == 1:
return True
else:
return False | check-if-it-is-a-good-array | Python3 using reduce function beats 100% | grayrhino | 0 | 192 | check if it is a good array | 1,250 | 0.589 | Hard | 18,721 |
https://leetcode.com/problems/cells-with-odd-values-in-a-matrix/discuss/1682009/Optimal-O(m%2Bn)-space-or-O(m*n)-time-complexity-solution | class Solution:
def oddCells(self, m: int, n: int, indices: List[List[int]]) -> int:
row_data = [0]*m
col_data = [0]*n
for tup in indices:
row_data[tup[0]] = row_data[tup[0]] + 1
col_data[tup[1]] = col_data[tup[1]] + 1
odd_count = 0
for rowp in range(m):
for colp in range(n):
val = row_data[rowp] + col_data[colp]
if val % 2 != 0:
odd_count+=1
return odd_count | cells-with-odd-values-in-a-matrix | Optimal O(m+n) space | O(m*n) time complexity solution | snagsbybalin | 2 | 172 | cells with odd values in a matrix | 1,252 | 0.786 | Easy | 18,722 |
https://leetcode.com/problems/cells-with-odd-values-in-a-matrix/discuss/1241844/98.51-or-python-or | class Solution:
def oddCells(self, m: int, n: int, indices: List[List[int]]) -> int:
row=[0]*m
col = [0]*n
for x,y in indices:
row[x]+=1
col[y]+=1
ans=0
for i in range(m):
for j in range(n):
if (row[i]+col[j])%2:
ans+=1
return ans | cells-with-odd-values-in-a-matrix | 98.51 | python | | chikushen99 | 2 | 177 | cells with odd values in a matrix | 1,252 | 0.786 | Easy | 18,723 |
https://leetcode.com/problems/cells-with-odd-values-in-a-matrix/discuss/2610558/SIMPLE-PYTHON3-SOLUTION-faster-and-easy-approach | class Solution:
def oddCells(self, m: int, n: int, indices: List[List[int]]) -> int:
matrix = [[0 for _ in range(n)] for _ in range(m)]
for i in range(len(indices)):
for k in range(2):
if k == 0:
for j in range(n):
matrix[indices[i][0]][j] += 1
else:
for j in range(m):
matrix[j][indices[i][1]] += 1
count = 0
for i in range(len(matrix)):
for j in range(len(matrix[i])):
if matrix[i][j] % 2 != 0:
count += 1
return count | cells-with-odd-values-in-a-matrix | ✅✔ SIMPLE PYTHON3 SOLUTION ✅✔ faster and easy approach | rajukommula | 1 | 88 | cells with odd values in a matrix | 1,252 | 0.786 | Easy | 18,724 |
https://leetcode.com/problems/cells-with-odd-values-in-a-matrix/discuss/1595121/Python-3-simple-solution | class Solution:
def oddCells(self, m: int, n: int, indices: List[List[int]]) -> int:
rows = collections.defaultdict(lambda: False)
cols = collections.defaultdict(lambda: False)
for i, j in indices:
rows[i] = not rows[i]
cols[j] = not cols[j]
return sum(rows[i] != cols[j] for i in range(m) for j in range(n)) | cells-with-odd-values-in-a-matrix | Python 3 simple solution | dereky4 | 1 | 283 | cells with odd values in a matrix | 1,252 | 0.786 | Easy | 18,725 |
https://leetcode.com/problems/cells-with-odd-values-in-a-matrix/discuss/425117/Python-3-(With-Explanation)-(five-lines)-(48-ms) | class Solution:
def oddCells(self, n: int, m: int, I: List[List[int]]) -> int:
M = [[0]*m for _ in range(n)]
for x,y in I:
for j in range(m): M[x][j] = 1 - M[x][j]
for i in range(n): M[i][y] = 1 - M[i][y]
return sum(sum(M,[]))
- Junaid Mansuri | cells-with-odd-values-in-a-matrix | Python 3 (With Explanation) (five lines) (48 ms) | junaidmansuri | 1 | 683 | cells with odd values in a matrix | 1,252 | 0.786 | Easy | 18,726 |
https://leetcode.com/problems/cells-with-odd-values-in-a-matrix/discuss/2788286/Python-or-Two-O(m-%2B-n-%2B-I)-solutions | class Solution:
def oddCells(self, m: int, n: int, indices: List[List[int]]) -> int:
rows = [0] * m
cols = [0] * n
odd_rows, odd_cols = 0, 0
ans = 0
for r, c in indices:
if rows[r] & 1:
ans -= n - 2 * odd_cols
odd_rows -= 1
else:
ans += n - 2 * odd_cols
odd_rows += 1
rows[r] += 1
if cols[c] & 1:
ans -= m - 2 * odd_rows
odd_cols -= 1
else:
ans += m - 2 * odd_rows
odd_cols += 1
cols[c] += 1
return ans
def oddCells(self, m: int, n: int, indices: List[List[int]]) -> int:
odd_rows, odd_cols = [False] * m, [False] * n
row_count, col_count = 0, 0
for r, c in indices:
odd_rows[r] ^= True
odd_cols[c] ^= True
row_count += 1 if odd_rows[r] else -1
col_count += 1 if odd_cols[c] else -1
return (n - col_count) * row_count + (m - row_count) * col_count | cells-with-odd-values-in-a-matrix | Python | Two O(m + n + I) solutions | on_danse_encore_on_rit_encore | 0 | 5 | cells with odd values in a matrix | 1,252 | 0.786 | Easy | 18,727 |
https://leetcode.com/problems/cells-with-odd-values-in-a-matrix/discuss/2612679/Python-or-O(n*m%2Bindices)-or-Easy-or-Hashing | class Solution:
def oddCells(self, m: int, n: int, indices: List[List[int]]) -> int:
dict_ = {} #List to keep track of total increase row and column wise
dict_['col'] = [0]*n
dict_['row'] = [0]*m
for idx in range(len(indices)):
dict_['row'][indices[idx][0]] += 1
dict_['col'][indices[idx][1]] += 1
count_odd = 0
for row in range(m):
for col in range(n):
if (dict_['row'][row] + dict_['col'][col])&1 == 1: #if total increase is odd
count_odd += 1
return count_odd | cells-with-odd-values-in-a-matrix | Python | O(n*m+indices) | Easy | Hashing | anurag899 | 0 | 48 | cells with odd values in a matrix | 1,252 | 0.786 | Easy | 18,728 |
https://leetcode.com/problems/cells-with-odd-values-in-a-matrix/discuss/2368476/Python-98.5-speed-99.3-memory | class Solution:
def oddCells(self, row: int, col: int, indices: List[List[int]]) -> int:
rows, cols = [False] * row, [False] * col
for index in indices:
rows[index[0]] = not rows[index[0]]
cols[index[1]] = not cols[index[1]]
count = 0
for i in rows:
for j in cols:
count += i ^ j
return count | cells-with-odd-values-in-a-matrix | Python 98.5 % speed, 99.3 % memory | amaargiru | 0 | 47 | cells with odd values in a matrix | 1,252 | 0.786 | Easy | 18,729 |
https://leetcode.com/problems/cells-with-odd-values-in-a-matrix/discuss/2028934/Python-Clean-and-easy-to-understand-solution | class Solution:
def oddCells(self, m: int, n: int, indices: List[List[int]]) -> int:
# Keep track of all increments to rows, columns in lists(i.e row_val, col_val)
# Get a particular (i,j) cell value by :
# sum of increments of row(i.e row_val[i]) + increments of column(i.e col_val[j])
row_val, col_val = [0]*m, [0]*n
for r,c in indices:
row_val[r] += 1
col_val[c] += 1
count = 0
for i in range(m):
for j in range(n):
#Check a cell value is odd or not
if (row_val[i] + col_val[j]) % 2 == 1:
count += 1
return count | cells-with-odd-values-in-a-matrix | Python Clean and easy to understand solution | firefist07 | 0 | 69 | cells with odd values in a matrix | 1,252 | 0.786 | Easy | 18,730 |
https://leetcode.com/problems/cells-with-odd-values-in-a-matrix/discuss/1794883/6-Lines-Python-Solution-oror-10vFasteroror-Memory-less-than-10 | class Solution:
def oddCells(self, m: int, n: int, indices: List[List[int]]) -> int:
import numpy as np
zeros = np.array([[0 for col in range(n)] for row in range(m)])
for indice in indices:
zeros[indice[0],:] = [x+1 for x in zeros[indice[0],:]]
zeros[:,indice[1]] = [x+1 for x in zeros[:,indice[1]]]
return len([i for lst in zeros.tolist() for i in lst if i%2==1]) | cells-with-odd-values-in-a-matrix | 6-Lines Python Solution || 10%vFaster|| Memory less than 10% | Taha-C | 0 | 98 | cells with odd values in a matrix | 1,252 | 0.786 | Easy | 18,731 |
https://leetcode.com/problems/cells-with-odd-values-in-a-matrix/discuss/1458016/Python3-solution-or-explained-aproach | class Solution:
def oddCells(self, m: int, n: int, indices: List[List[int]]) -> int:
d_row = {} # making a dictionary to store what row is in indices and how many times
d_col = {} # making another dictionary for column
mat = []
for i in range(len(indices)):
if indices[i][0] not in d_row:
d_row[indices[i][0]] = 1
else:
d_row[indices[i][0]] += 1
if indices[i][1] not in d_col:
d_col[indices[i][1]] = 1
else:
d_col[indices[i][1]] += 1
count = 0
for i in range(m):
mat.append([])
for j in range(n):
mat[i].append(0)
if i in d_row:
mat[i][j] += d_row[i]
if j in d_col:
mat[i][j] += d_col[j]
if mat[i][j] % 2 == 1:
count += 1
return count | cells-with-odd-values-in-a-matrix | Python3 solution | explained aproach | FlorinnC1 | 0 | 113 | cells with odd values in a matrix | 1,252 | 0.786 | Easy | 18,732 |
https://leetcode.com/problems/cells-with-odd-values-in-a-matrix/discuss/489973/Simple-Python3-solution | class Solution:
def oddCells(self, n: int, m: int, indices: List[List[int]]) -> int:
# generate the matrix with the given input
res = [[0 for j in range(m)] for i in range(n)]
# loop through the indices and add 1 for the row and column
for i, j in indices:
for k in range(m):
res[i][k] += 1
for k in range(n):
res[k][j] += 1
# count and return the odd numbers in the matrix
return sum([1 for row in res for elem in row if elem%2 != 0]) | cells-with-odd-values-in-a-matrix | Simple Python3 solution | gann0001 | 0 | 283 | cells with odd values in a matrix | 1,252 | 0.786 | Easy | 18,733 |
https://leetcode.com/problems/cells-with-odd-values-in-a-matrix/discuss/425313/Python3-three-line-concise-solution | class Solution:
def oddCells(self, n: int, m: int, indices: List[List[int]]) -> int:
matrix = [[0]*m for _ in range(n)]
for r, c in indices:
for j in range(m): matrix[r][j] ^= 1
for i in range(n): matrix[i][c] ^= 1
return sum(sum(matrix, [])) | cells-with-odd-values-in-a-matrix | Python3 three-line concise solution | ye15 | 0 | 155 | cells with odd values in a matrix | 1,252 | 0.786 | Easy | 18,734 |
https://leetcode.com/problems/cells-with-odd-values-in-a-matrix/discuss/425191/O(len(indices))-Solution | class Solution:
def oddCells(self, n: int, m: int, indices: List[List[int]]) -> int:
row = set()
col = set()
ans = 0
for i, j in indices:
diff = m - 2 * len(col)
ans += diff * (-1) ** (i in row)
row ^= {i}
diff = n - 2 * len(row)
ans += diff * (-1) ** (j in col)
col ^= {j}
return ans | cells-with-odd-values-in-a-matrix | O(len(indices)) Solution | chuan-chih | -1 | 88 | cells with odd values in a matrix | 1,252 | 0.786 | Easy | 18,735 |
https://leetcode.com/problems/reconstruct-a-2-row-binary-matrix/discuss/845641/Python-3-or-Greedy-or-Explanations | class Solution:
def reconstructMatrix(self, upper: int, lower: int, colsum: List[int]) -> List[List[int]]:
s, n = sum(colsum), len(colsum)
if upper + lower != s: return []
u, d = [0] * n, [0] * n
for i in range(n):
if colsum[i] == 2 and upper > 0 and lower > 0:
u[i] = d[i] = 1
upper, lower = upper-1, lower-1
elif colsum[i] == 1:
if upper > 0 and upper >= lower:
u[i], upper = 1, upper-1
elif lower > 0 and lower > upper:
d[i], lower = 1, lower-1
else: return []
elif not colsum[i]: continue
else: return []
return [u, d] | reconstruct-a-2-row-binary-matrix | Python 3 | Greedy | Explanations | idontknoooo | 3 | 399 | reconstruct a 2 row binary matrix | 1,253 | 0.438 | Medium | 18,736 |
https://leetcode.com/problems/reconstruct-a-2-row-binary-matrix/discuss/425246/Python-3-(nine-lines)-(beats-100) | class Solution:
def reconstructMatrix(self, U: int, L: int, C: List[int]) -> List[List[int]]:
M, u = [[0]*len(C) for _ in range(2)], C.count(2)
if U + L != sum(C) or u > min(L,U): return []
for j,s in enumerate(C):
if s == 2: M[0][j] = M[1][j] = 1
for j,s in enumerate(C):
if s == 1:
if u < U: M[0][j], u = 1, u + 1
else: M[1][j] = 1
return M
- Junaid Mansuri | reconstruct-a-2-row-binary-matrix | Python 3 (nine lines) (beats 100%) | junaidmansuri | 1 | 194 | reconstruct a 2 row binary matrix | 1,253 | 0.438 | Medium | 18,737 |
https://leetcode.com/problems/reconstruct-a-2-row-binary-matrix/discuss/2815947/Easy-to-Understand | class Solution:
def reconstructMatrix(self, upper: int, lower: int, colsum: List[int]) -> List[List[int]]:
bm = [[0 for _ in range(len(colsum))] for i in range(2)]
for i in range(len(colsum)):
if colsum[i]==2:
colsum[i]=0
upper-=1
lower-=1
bm[0][i]=1
bm[1][i]=1
for i in range(len(colsum)):
if colsum[i]>0 and upper>0:
bm[0][i]=1
upper-=1
colsum[i]-=1
for i in range(len(colsum)):
if colsum[i]>0 and lower>0:
bm[1][i]=1
lower-=1
colsum[i]-=1
if upper!=0 or lower!=0 or sum(colsum)!=0:
return []
return bm | reconstruct-a-2-row-binary-matrix | Easy to Understand | prateekgoel7248 | 0 | 2 | reconstruct a 2 row binary matrix | 1,253 | 0.438 | Medium | 18,738 |
https://leetcode.com/problems/reconstruct-a-2-row-binary-matrix/discuss/2697470/Python3-Commented-Greedy-Solution | class Solution:
def reconstructMatrix(self, upper: int, lower: int, colsum: List[int]) -> List[List[int]]:
# first set all the ones where there is a two in the col sum
mat = [[0]*len(colsum), [0]*len(colsum)]
# go over the colsums and place the ones
for idx, num in enumerate(colsum):
# we have to place both of them
if num == 2:
mat[0][idx] = 1
mat[1][idx] = 1
upper -= 1
lower -= 1
# we only place one and do that greedily
# by selecting the higher count
elif num == 1:
if lower > upper:
mat[1][idx] = 1
lower -= 1
else:
mat[0][idx] = 1
upper -= 1
# make a check whether we used too much ones
if lower < 0 or upper < 0:
return []
return mat if lower == 0 and upper == 0 else [] | reconstruct-a-2-row-binary-matrix | [Python3] - Commented Greedy Solution | Lucew | 0 | 9 | reconstruct a 2 row binary matrix | 1,253 | 0.438 | Medium | 18,739 |
https://leetcode.com/problems/reconstruct-a-2-row-binary-matrix/discuss/2591994/python-3-greedy-solution-(860-ms-77-faster) | class Solution:
def reconstructMatrix(self, upper: int, lower: int, colsum: List[int]) -> List[List[int]]:
# if upper+lower is not equal to the sum of colsum, return []
if (upper+lower)!=sum(colsum):
return []
# if colsum[j]==2, then both the upper and lower elements need to be 1. However, if the number of 2 in colsum is more than upper or lower, then return []
if colsum.count(2)>upper or colsum.count(2)>lower:
return []
m, n = 2, len(colsum)
A = [[0]*n for i in range(m)]
# for colsum[n]==2, necessarilly to assign 1 and 1 to both upper and lower elements.
for j in range(n):
if colsum[j]==2:
A[0][j], A[1][j] = 1, 1
upper -= 1
lower -= 1
colsum[j] = 0
# the greedy part
for i in range(m):
for j in range(n):
if colsum[j]>0:
if i==0 and upper>0:
A[i][j] = 1
upper -= 1
colsum[j] -= 1
elif i==1 and lower>0:
A[i][j] = 1
lower -= 1
colsum[j] -= 1
return A | reconstruct-a-2-row-binary-matrix | [python 3] greedy solution (860 ms, 77% faster) | hhlinwork | 0 | 8 | reconstruct a 2 row binary matrix | 1,253 | 0.438 | Medium | 18,740 |
https://leetcode.com/problems/reconstruct-a-2-row-binary-matrix/discuss/2382830/PYTHONor-EXPLAINED-WITH-PICTURE-or-DETAILED-CLEAR-SOLUTION-or-LINEAR-TIME-or | class Solution:
def reconstructMatrix(self, upper: int, lower: int, colsum: List[int]) -> List[List[int]]:
n = len(colsum)
matrix = [[0 for i in range(n)] for j in range(2)]
for col,summ in enumerate(colsum):
if summ == 0:
continue
if summ == 2:
matrix[0][col] = matrix[1][col] = 1
upper -= 1
lower -= 1
else:
if upper > lower:
matrix[0][col] = 1
upper -= 1
else:
matrix[1][col] = 1
lower -= 1
if upper < 0 or lower < 0: break
return matrix if upper == lower == 0 else [] | reconstruct-a-2-row-binary-matrix | PYTHON| EXPLAINED WITH PICTURE | DETAILED CLEAR SOLUTION | LINEAR TIME | | reaper_27 | 0 | 19 | reconstruct a 2 row binary matrix | 1,253 | 0.438 | Medium | 18,741 |
https://leetcode.com/problems/reconstruct-a-2-row-binary-matrix/discuss/2000003/python-3-oror-greedy-solution | class Solution:
def reconstructMatrix(self, upper: int, lower: int, colsum: List[int]) -> List[List[int]]:
twos = colsum.count(2)
upper -= twos
lower -= twos
res = [[], []]
for i, s in enumerate(colsum):
if s == 0:
res[0].append(0)
res[1].append(0)
elif s == 1:
if upper:
res[0].append(1)
upper -= 1
res[1].append(0)
else:
res[0].append(0)
res[1].append(1)
lower -= 1
else:
res[0].append(1)
res[1].append(1)
return res if upper == 0 and lower == 0 else [] | reconstruct-a-2-row-binary-matrix | python 3 || greedy solution | dereky4 | 0 | 39 | reconstruct a 2 row binary matrix | 1,253 | 0.438 | Medium | 18,742 |
https://leetcode.com/problems/reconstruct-a-2-row-binary-matrix/discuss/1501158/Python-greedy-O(n)-solution | class Solution(object):
def reconstructMatrix(self, upper, lower, colsum):
"""
:type upper: int
:type lower: int
:type colsum: List[int]
:rtype: List[List[int]]
"""
if sum(colsum) != lower + upper:
return []
n = len(colsum)
if colsum.count(0) > n - max(lower, upper):
return []
res = [[0 for _ in range(n)] for _ in range(2)]
for i in range(n):
if colsum[i] == 0:
res[0][i] = 0
res[1][i] = 0
else: #colsum[i] >= 1
if upper > 0 and lower == 0:
res[0][i] = 1
upper -= 1
colsum[i] -= 1
res[1][i] = 0
elif upper == 0 and lower > 0:
res[0][i] = 0
res[1][i] = 1
lower -= 1
colsum[i] -= 1
elif upper == 0 and lower == 0:
res[0][i] = 0
res[1][i] = 0
else: # upper > 0 and lower > 0
if colsum[i] >= 2:
res[0][i] = 1
res[1][i] = 1
lower -= 1
upper -= 1
else: #colsum[i] == 1
if upper > lower:
res[0][i] = 1
res[1][i] = 0
upper -= 1
elif upper < lower:
res[0][i] = 0
res[1][i] = 1
lower -= 1
else:
res[0][i] = 1
res[1][i] = 0
upper -= 1
return res | reconstruct-a-2-row-binary-matrix | Python greedy O(n) solution | byuns9334 | 0 | 123 | reconstruct a 2 row binary matrix | 1,253 | 0.438 | Medium | 18,743 |
https://leetcode.com/problems/reconstruct-a-2-row-binary-matrix/discuss/1192833/Python3-with-Comments-beats-92-Easy-Approach | class Solution:
def reconstructMatrix(self, upper: int, lower: int, colsum: List[int]) -> List[List[int]]:
#if sum of upper and lower is not equal the sum of elements of colsum, then no such matrix is possible
if not upper+lower == sum(colsum):
return []
#if the number of columns that have 1s in both upper and lower cell is greater than the minimum of upper and lower, no such matrix is possible
cnt_2 = len([num for num in colsum if num==2]) #count occurrences of 2s in colsum
if cnt_2 > min(upper,lower):
return []
res = [[0]*len(colsum) for _ in range(0,2)] #initialize the output binary matrix
upper_row_1 = 0 #to track currently how many 1s are in upper row
lower_row_1 = 0 #to track currently how many 1s are in lower row
#first fill up the columns that have sum 2, as both upper and lower cells will be 1
for i in range(0,len(colsum)):
if colsum[i]==2:
res[0][i]=1
res[1][i]=1
upper_row_1+=1
lower_row_1+=1
#next fill up the columns that have sum 1
for i in range(0,len(colsum)):
if colsum[i]==1:
if upper_row_1 < upper: #in this case we can flip the 0 to 1 in this index
res[0][i]=1
upper_row_1 += 1
else: #otherwise flip the bit of the lower cell
res[1][i]=1
lower_row_1 += 1
return res | reconstruct-a-2-row-binary-matrix | Python3 with Comments, beats 92%, Easy Approach | bPapan | 0 | 103 | reconstruct a 2 row binary matrix | 1,253 | 0.438 | Medium | 18,744 |
https://leetcode.com/problems/reconstruct-a-2-row-binary-matrix/discuss/425342/Python-3-a-concise-implementation | class Solution:
def reconstructMatrix(self, upper: int, lower: int, colsum: List[int]) -> List[List[int]]:
cnt = sum(x==2 for x in colsum)
if upper + lower != sum(colsum) or cnt > upper or cnt > lower : return [] #sanity check
ans = [[0]*len(colsum) for _ in range(2)]
for i, c in enumerate(colsum):
if c == 2: ans[0][i] = ans[1][i] = 1
elif c == 1:
if cnt < upper: #there is capacity in upper
ans[0][i] = 1
cnt += 1
else: ans[1][i] = 1
return ans | reconstruct-a-2-row-binary-matrix | Python 3 a concise implementation | ye15 | 0 | 52 | reconstruct a 2 row binary matrix | 1,253 | 0.438 | Medium | 18,745 |
https://leetcode.com/problems/number-of-closed-islands/discuss/1250335/DFS-oror-Well-explained-oror-93-faster-oror | class Solution:
def closedIsland(self, grid: List[List[int]]) -> int:
def dfs(i,j):
if grid[i][j]==1:
return True
if i<=0 or i>=m-1 or j<=0 or j>=n-1:
return False
grid[i][j]=1
up=dfs(i-1,j)
down=dfs(i+1,j)
left=dfs(i,j-1)
right=dfs(i,j+1)
return left and right and up and down
m,n = len(grid),len(grid[0])
c=0
# iterate through the grid from 1 to length of grid for rows and columns.
# the iteration starts from 1 because if a 0 is present in the 0th column, it can't be a closed island.
for i in range(1,m-1):
for j in range(1,n-1):
# if the item in the grid is 0 and it is surrounded by
# up, down, left, right 1's then increment the count.
if grid[i][j]==0 and dfs(i,j):
c+=1
return c | number-of-closed-islands | 🐍 DFS || Well-explained || 93% faster || | abhi9Rai | 14 | 836 | number of closed islands | 1,254 | 0.642 | Medium | 18,746 |
https://leetcode.com/problems/number-of-closed-islands/discuss/2210229/Python-Easy-to-understand-DFS-solution-95.50-runtime | class Solution:
def closedIsland(self, grid: List[List[int]]) -> int:
result = 0
def dfs(grid, r, c):
if not 0 <= r < len(grid) or not 0 <= c < len(grid[0]):
return False
if grid[r][c] != 0:
return True
grid[r][c] = 2
return all([dfs(grid, r - 1, c),
dfs(grid, r + 1, c),
dfs(grid, r, c - 1),
dfs(grid, r, c + 1)])
for r in range(len(grid)):
for c in range(len(grid[0])):
if grid[r][c] == 0 and dfs(grid, r, c):
result += 1
return result | number-of-closed-islands | ✅ Python, Easy to understand DFS solution, 95.50% runtime | AntonBelski | 2 | 96 | number of closed islands | 1,254 | 0.642 | Medium | 18,747 |
https://leetcode.com/problems/number-of-closed-islands/discuss/2014128/Python-or-DFS-or-Beats-99.7 | class Solution:
def closedIsland(self, grid: List[List[int]]) -> int:
h, w = len(grid), len(grid[0])
directions = [[0, 1], [0, -1], [1, 0], [-1, 0]]
count = 0
def dfs(y, x, state):
grid[y][x] = 1
for dy, dx in directions:
ny, nx = y+dy, x+dx
if ny >= h or ny < 0 or nx >= w or nx < 0:
state = 0
else:
if grid[ny][nx] == 0 and not dfs(ny, nx, state):
state = 0
return state
for j in range(h):
for i in range(w):
if grid[j][i] == 0:
count += dfs(j, i, 1)
return count | number-of-closed-islands | Python | DFS | Beats 99.7% | Muzque | 2 | 58 | number of closed islands | 1,254 | 0.642 | Medium | 18,748 |
https://leetcode.com/problems/number-of-closed-islands/discuss/667340/Python-DFS-faster-than-99.86 | class Solution:
def closedIsland(self, grid: List[List[int]]) -> int:
# check if the input is valid
numOfClosedIslands = 0
if not grid or len(grid) == 0:
return numOfClosedIslands
nr = len(grid)
nc = len(grid[0])
for row in range(1, len(grid)-1):
for column in range(1, len(grid[0])-1):
if grid[row][column] == 0 and self.isClosed(grid, row, column, nr, nc):
numOfClosedIslands += 1
return numOfClosedIslands
def isClosed(self, grid, row, column, nr, nc):
if grid[row][column] == 1:
return True
if row <= 0 or row >= nr-1 or column <= 0 or column >= nc-1:
return False
grid[row][column] = 1
up =self.isClosed(grid, row+1, column, nr, nc)
down = self.isClosed(grid, row-1, column, nr, nc)
left = self.isClosed(grid, row, column-1, nr, nc)
right = self.isClosed(grid, row, column+1, nr, nc)
return up and left and right and down | number-of-closed-islands | Python DFS faster than 99.86% | darshan_22 | 2 | 227 | number of closed islands | 1,254 | 0.642 | Medium | 18,749 |
https://leetcode.com/problems/number-of-closed-islands/discuss/2738474/Python3-Fast-clear-and-commented-DFS | class Solution:
def closedIsland(self, grid: List[List[int]]) -> int:
# go through the grid and make a dfs per island
result = 0
m = len(grid)
n = len(grid[0])
for rx in range(m):
for cx in range(n):
# check whether we found an island
if grid[rx][cx] == 0 and self.islandDfs(rx, cx, grid, m, n):
result += 1
return result
def islandDfs(self, rx, cx, grid, m, n):
# check whether we are out of bounds
if rx < 0 or cx < 0 or rx >= m or cx >=n:
return False
# check whether we are water
if grid[rx][cx] == 1:
return True
# check whether we already visited
if grid[rx][cx] == -1:
return True
# set ourself to visited
grid[rx][cx] = -1
# traverse in all directions
result = True
for rx, cx in [(rx-1, cx), (rx+1, cx), (rx, cx-1), (rx, cx+1)]:
if not self.islandDfs(rx, cx, grid, m, n):
result = False
# check all sourrounding cells
return result | number-of-closed-islands | [Python3] - Fast, clear and commented DFS | Lucew | 1 | 138 | number of closed islands | 1,254 | 0.642 | Medium | 18,750 |
https://leetcode.com/problems/number-of-closed-islands/discuss/2635391/Python-oror-BFS-oror-easy-Solution | class Solution:
def closedIsland(self, grid: List[List[int]]) -> int:
# 4 direct top, right, down, left
self.dX=[0,0,-1,1]
self.dY=[-1,1,0,0]
# O(1) visited
visited = [[False]*len(grid[0]) for i in range(len(grid))]
# check [x][y] is in matrix ?
def inMatrix(x,y,m,n):
if x < 0 or y < 0:
return False
if x >= m or y >= n:
return False
return True
def bfs(grid, visited, start):
queue = [start]
visited[start[0]][start[1]] = True
close = True # flag: is closed islands
while queue:
curr = queue.pop()
# new direct
for i in range(4):
x=curr[0] + self.dX[i]
y=curr[1] + self.dY[i]
# not in matrix = not closed islands
if not inMatrix(x,y,len(grid), len(grid[0])):
close=False
# add land to queue
elif not visited[x][y]:
visited[x][y] = True
if not grid[x][y]: # grid[x][y] == 0
queue.append([x,y])
return close
m = 0
for i in range(len(grid)):
for j in range(len(grid[0])):
if not visited[i][j]:
visited[i][j] = True
if not grid[i][j]:
if bfs(grid, visited, [i,j]):
m+=1
return m | number-of-closed-islands | Python || BFS || easy Solution | LeeTun2k2 | 1 | 139 | number of closed islands | 1,254 | 0.642 | Medium | 18,751 |
https://leetcode.com/problems/number-of-closed-islands/discuss/2556823/Python3-Solution-or-DFS-or-O(nm) | class Solution:
def closedIsland(self, grid):
n, m = len(grid), len(grid[0])
def dfs(i, j):
if not ((0 <= i < n) and (0 <= j < m)): return False;
if grid[i][j]: return True
grid[i][j] = 1
res = dfs(i + 1, j)
res &= dfs(i - 1, j)
res &= dfs(i, j + 1)
res &= dfs(i, j - 1)
return res
return sum(dfs(i, j) for i in range(1, n - 1) for j in range(1, m - 1) if grid[i][j] == 0) | number-of-closed-islands | ✔ Python3 Solution | DFS | O(nm) | satyam2001 | 1 | 53 | number of closed islands | 1,254 | 0.642 | Medium | 18,752 |
https://leetcode.com/problems/number-of-closed-islands/discuss/2362037/Python3-or-Solved-Using-BFS-%2B-Queue | class Solution:
#Time-Complexity: O(0.5*rows*cols*rows*cols), in worst case, we will have to do lot of bfs if we have lot of separated land cells(1/2*rows*cols at most), but bfs in worst case has to run through
#each entry of grid! -> O(rows^2*cols^2)
#Space-Complexity: O(rows*cols + rows*cols) -> O(rows*cols)
#lot of separated 1 cell land cells in our grid!
def closedIsland(self, grid: List[List[int]]) -> int:
#lay out dimension
rows, cols = len(grid), len(grid[0])
visited = set()
four_directions = [[1,0], [-1,0],[0,1],[0,-1]]
#define bfs helper!
def bfs(sr, sc):
nonlocal rows, cols, grid, visited
q = collections.deque()
q.append([sr, sc])
visited.add((sr, sc))
#bool flag
is_closed = True
#as long as queue is not empty!
while q:
cr, cc = q.popleft()
for direction in four_directions:
r_change, c_change = direction
#if neighboring cell is out of bounds, we can immediately turn off bool flag since
#none of land cells on current island won't contribute to overall closed island!
if(cr + r_change not in range(rows) or cc + c_change not in range(cols)):
is_closed = False
continue
#neighboring position is in-bounds but not already visited land cell, we add it
#to the queue to be handled later!
elif(grid[cr+r_change][cc+c_change] == 0 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))
#here the else case handles if neighboring cell is in-bounds water or already visited
#land cell! If land cell is already visited, then we would have already taken account
#of its effect on making island potentially not closed in previous iterations of bfs!
#we simply ignore and move to next neighboring adjacent cell from current cell!
else:
continue
#once queue is empty, bfs on every land cell for current island is visited!
#then, check bool flag!
if(is_closed):
return 1
return 0
closed_islands = 0
#traverse each and every entry of grid and only initiate bfs on land cell not already visited!
for i in range(rows):
for j in range(cols):
if grid[i][j] == 0 and (i, j) not in visited:
closed_islands += bfs(i, j)
return closed_islands | number-of-closed-islands | Python3 | Solved Using BFS + Queue | JOON1234 | 1 | 38 | number of closed islands | 1,254 | 0.642 | Medium | 18,753 |
https://leetcode.com/problems/number-of-closed-islands/discuss/2270323/Python3-DFS-solution | class Solution:
def closedIsland(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
res = 0
def dfs(x, y):
if x in (0, m-1) or y in (0, n-1):
self.isIsland = False
for i, j in ((x+1, y), (x-1, y), (x, y+1), (x, y-1)):
if 0 <= i < m and 0 <= j < n and grid[i][j] == 0:
grid[i][j] = -1
dfs(i, j)
for i in range(m):
for j in range(n):
if grid[i][j] == 0:
self.isIsland = True
dfs(i, j)
res += self.isIsland
return res | number-of-closed-islands | 📌 Python3 DFS solution | Dark_wolf_jss | 1 | 22 | number of closed islands | 1,254 | 0.642 | Medium | 18,754 |
https://leetcode.com/problems/number-of-closed-islands/discuss/1889591/Python-3-or-Beats-96-memory | class Solution:
def closedIsland(self, grid: List[List[int]]) -> int:
ctr=0
for a in range(1,len(grid)-1):
for b in range(1,len(grid[0])-1):
if grid[a][b]==0:
queue=[(a,b)]
flag=False
while queue:
i,j=queue.pop(0)
if i<0 or j<0 or i>len(grid)-1 or j>len(grid[0])-1:
continue
if i==0 or j==0 or i==len(grid)-1 or j==len(grid[0])-1:
if grid[i][j]==0:
flag=True
continue
if grid[i][j]==0:
grid[i][j]='#'
queue.append((i+1,j))
queue.append((i,j-1))
queue.append((i-1,j))
queue.append((i,j+1))
if not flag:
ctr+=1
return ctr | number-of-closed-islands | Python 3 | Beats 96% memory | RickSanchez101 | 1 | 99 | number of closed islands | 1,254 | 0.642 | Medium | 18,755 |
https://leetcode.com/problems/number-of-closed-islands/discuss/1478885/WEEB-DOES-PYTHON-BFS(BEATS-92.42) | class Solution:
def closedIsland(self, grid: List[List[int]]) -> int:
row, col = len(grid), len(grid[0])
queue = deque([(0,i) for i in range(col) if grid[0][i] == 0] +
[(row-1,i) for i in range(col) if grid[row-1][i] == 0] +
[(i, 0) for i in range(1,row-1) if grid[i][0] == 0] +
[(i, col-1) for i in range(1,row-1) if grid[i][col-1] == 0])
self.traverse_border_islands(grid, row, col, queue)
closed = 0
for x in range(row):
for y in range(col):
if grid[x][y] == 0:
queue.append((x,y))
closed += self.traverse_internal_island(grid, row, col, queue)
return closed
def traverse_border_islands(self, grid, row, col, queue):
while queue:
x,y = queue.popleft()
if grid[x][y] == "X": continue
grid[x][y] = "X"
for nx,ny in [[x+1,y],[x-1,y],[x,y+1],[x,y-1]]:
if 0<=nx<row and 0<=ny<col and grid[nx][ny] == 0:
queue.append((nx,ny))
def traverse_internal_island(self, grid, row, col, queue):
while queue:
x,y = queue.popleft()
if grid[x][y] == "Y": continue
grid[x][y] = "Y"
for nx,ny in [[x+1,y],[x-1,y],[x,y+1],[x,y-1]]:
if 0<=nx<row and 0<=ny<col and grid[nx][ny] == 0:
queue.append((nx,ny))
return 1 | number-of-closed-islands | WEEB DOES PYTHON BFS(BEATS 92.42%) | Skywalker5423 | 1 | 127 | number of closed islands | 1,254 | 0.642 | Medium | 18,756 |
https://leetcode.com/problems/number-of-closed-islands/discuss/2843217/ez-python-solution | class Solution:
def closedIsland(self, grid: List[List[int]]) -> int:
ans = 0
queue = []
m = len(grid)
n = len(grid[0])
directions = ((-1,0), (1,0), (0,-1 ), (0,1))
for i in range(m):
for j in range(n):
if grid[i][j] == 0:
queue.append((i,j))
grid[i][j] = 1
isClosed = True
while queue:
cur_i, cur_j = queue.pop()
if cur_i in (0, m-1) or cur_j in (0, n-1):
isClosed = False
for d in directions:
new_i = cur_i + d[0]
new_j = cur_j + d[1]
if 0 <= new_i < m and 0 <= new_j < n and grid[new_i][new_j] == 0:
queue.append((new_i, new_j))
grid[new_i][new_j] = 1
if isClosed:
ans += 1
return ans | number-of-closed-islands | ez python solution | OmCar | 0 | 1 | number of closed islands | 1,254 | 0.642 | Medium | 18,757 |
https://leetcode.com/problems/number-of-closed-islands/discuss/2830248/Easy-python-solution-using-DFS | class Solution:
def closedIsland(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
vis = []
for i in range(m):
temp = []
for i in range(n):
temp.append(False)
vis.append(temp)
for i in range(m):
for j in range(n):
if grid[i][j] == 0 and (i == 0 or i == m-1 or j == 0 or j == n-1):
self.dfs(grid, m, n, i, j, vis)
res = 0
for i in range(1, m-1):
for j in range(1, n-1):
if grid[i][j] == 0 and vis[i][j] == False:
self.dfs(grid, m, n, i, j, vis)
res += 1
return res
def dfs(self, grid, m, n, i, j, vis):
if i < 0 or i >= m or j < 0 or j >= n:
return
if vis[i][j]:
return
if grid[i][j] == 1:
return
vis[i][j] = True
self.dfs(grid, m, n, i-1, j, vis)
self.dfs(grid, m, n, i+1, j, vis)
self.dfs(grid, m, n, i, j-1, vis)
self.dfs(grid, m, n, i, j+1, vis) | number-of-closed-islands | Easy python solution using DFS | i-haque | 0 | 2 | number of closed islands | 1,254 | 0.642 | Medium | 18,758 |
https://leetcode.com/problems/number-of-closed-islands/discuss/2803506/Python3-Faster-than-83-The-sum-of-the-numbers-of-chunks-of-zeros | class Solution:
answer = 0
def closedIsland(self, grid) -> int:
len_row, len_col = len(grid), len(grid[0])
visited = [[0]*len_col for _ in range(len_row)]
# Check 0 <= r <= length of grid and 0 <= c <= length of grid[0]
def is_safe(r, c) -> bool:
return 0 <= r and r <= len_row - 1 and 0 <= c and c <= len_col - 1
# Check this point is above the boundary
def is_boundary(r, c):
return r == len_row - 1 or c == len_col - 1 or r == 0 or c == 0
# Argument "flag" indicates that you have been to the boundary during the DFS process.
def dfs(r, c, flag):
visited[r][c] = 1
for row, col in [(0, -1), (-1, 0), (0, 1), (1, 0)]:
if not is_safe(r+row, c+col) or visited[r+row][c+col] or grid[r+row][c+col]: continue
# When it gets to boundary, if flag is True that means it have never been to the boundary, decreases answer by 1
# and sets flag to False
if is_boundary(r+row, c+col) and flag:
self.answer -= 1
flag = False
flag = dfs(r+row, c+col, flag)
return flag
for row in range(1, len_row - 1):
for col in range(1, len_col - 1):
if visited[row][col] or grid[row][col]: continue
self.answer += 1
dfs(row, col, True)
return self.answer | number-of-closed-islands | Python3 Faster than 83%, The sum of the numbers of chunks of zeros | Coaspe | 0 | 6 | number of closed islands | 1,254 | 0.642 | Medium | 18,759 |
https://leetcode.com/problems/number-of-closed-islands/discuss/2756073/python-dfs-solution | class Solution:
def closedIsland(self, grid: List[List[int]]) -> int:
row = len(grid)
col = len(grid[0])
closed_islands = 0
# Flood fills all non-enclosed islands
for r in range(row):
self.dfs(grid, r, 0)
self.dfs(grid, r, col-1)
for c in range(col):
self.dfs(grid, 0, c)
self.dfs(grid, row-1, c)
# Flood fills all closed islands
for i in range(row):
for j in range(col):
if grid[i][j] == 0:
closed_islands += 1
self.dfs(grid, i, j)
return closed_islands
def dfs(self, grid, i, j):
row = len(grid)
col = len(grid[0])
if i<0 or i>=row or j<0 or j>=col or grid[i][j]==1:
return
grid[i][j] = 1
directions = [[-1,0], [1,0], [0,-1], [0,1]]
for d in directions:
new_r = i+d[0]
new_c = j+d[1]
self.dfs(grid, new_r, new_c) | number-of-closed-islands | python dfs solution | gcheng81 | 0 | 6 | number of closed islands | 1,254 | 0.642 | Medium | 18,760 |
https://leetcode.com/problems/number-of-closed-islands/discuss/2643401/Python-O(NM)-O(NM) | class Solution:
def closedIsland(self, grid: List[List[int]]) -> int:
n, m = len(grid), len(grid[0])
stack = deque()
for i in range(n):
if grid[i][0] == 0:
stack.append((i, 0))
if grid[i][m - 1] == 0:
stack.append((i, m - 1))
for i in range(m):
if grid[0][i] == 0:
stack.append((0, i))
if grid[n - 1][i] == 0:
stack.append((n - 1, i))
while stack:
row, col = stack.popleft()
grid[row][col] = 2
for x, y in [(0, 1), (1, 0), (-1, 0), (0, -1)]:
row_new, col_new = row + x, col + y
if 0 <= row_new < n and 0 <= col_new < m and grid[row_new][col_new] == 0:
stack.append((row_new, col_new))
queue, res = deque(), 0
for i in range(n):
for j in range(m):
if grid[i][j] == 0:
res += 1
queue.append((i, j))
while queue:
row, col = queue.popleft()
for x, y in [(0, 1), (1, 0), (-1, 0), (0, -1)]:
row_new, col_new = row + x, col + y
if 0 <= row_new < n and 0 <= col_new < m and grid[row_new][col_new] == 0:
grid[row_new][col_new] = 2
queue.append((row_new, col_new))
return res | number-of-closed-islands | Python - O(NM), O(NM) | Teecha13 | 0 | 4 | number of closed islands | 1,254 | 0.642 | Medium | 18,761 |
https://leetcode.com/problems/number-of-closed-islands/discuss/2420426/number-of-closed-islands-oror-Python3-oror-DFS-oror-Connected-components | class Solution:
def closedIsland(self, grid: List[List[int]]) -> int:
# Mark all islands visited which are connected to border
dirs = [[1, 0], [0, 1], [-1, 0], [0, -1]]
# For first and last column
for i in range(0, len(grid)):
if(grid[i][0] == 0):
self.dfs(i, 0, grid, dirs)
if(grid[i][len(grid[0]) - 1] == 0):
self.dfs(i, len(grid[0]) - 1, grid, dirs)
# for first and last row
for j in range(0, len(grid[0])):
if(grid[0][j] == 0):
self.dfs(0, j, grid, dirs)
if(grid[len(grid) - 1][j] == 0):
self.dfs(len(grid) - 1, j, grid, dirs)
ans = 0
for i in range(1, len(grid) - 1):
for j in range(1, len(grid[0]) - 1):
if(grid[i][j] == 0):
ans += 1
self.dfs(i, j, grid, dirs)
return ans
def dfs(self, x, y, grid, dirs):
grid[x][y] = -1
for dx, dy in dirs:
nx = x + dx
ny = y + dy
if(nx < 0 or ny < 0 or nx >= len(grid) or ny >= len(grid[0]) or grid[nx][ny] != 0):
continue
self.dfs(nx, ny, grid, dirs) | number-of-closed-islands | number of closed islands || Python3 || DFS || Connected components | vanshika_2507 | 0 | 20 | number of closed islands | 1,254 | 0.642 | Medium | 18,762 |
https://leetcode.com/problems/number-of-closed-islands/discuss/2407714/PYTHON-or-DFS-%2B-HASHMAP-or-EXPLAINED-or-FASTER-THAN-95.98-or | class Solution:
def closedIsland(self, grid: List[List[int]]) -> int:
rows,cols = len(grid),len(grid[0])
def dfs(row,col):
if grid[row][col] == 0:
grid[row][col] = 2
for x,y in ((row+1,col),(row-1,col),(row,col-1),(row,col+1)):
if 0 <= x < rows and 0 <= y < cols and grid[x][y] == 0:
dfs(x,y)
for i in range(rows):
if grid[i][0] == 0: dfs(i,0)
if grid[i][cols - 1] == 0: dfs(i,cols - 1)
for i in range(cols):
if grid[0][i] == 0: dfs(0,i)
if grid[rows - 1][i] == 0: dfs(rows-1,i)
ans = 0
for i in range(1,rows):
for j in range(1,cols):
if grid[i][j] == 0:
dfs(i,j)
ans += 1
return ans | number-of-closed-islands | PYTHON | DFS + HASHMAP | EXPLAINED | FASTER THAN 95.98 % | | reaper_27 | 0 | 26 | number of closed islands | 1,254 | 0.642 | Medium | 18,763 |
https://leetcode.com/problems/number-of-closed-islands/discuss/2296336/Simple-Python-solution-using-DFS | class Solution:
def closedIsland(self, grid: List[List[int]]) -> int:
res = 0
m = len(grid)
n = len(grid[0])
for i in range(m):
self.dfs(grid, i, 0) # drown all left bound islands
self.dfs(grid, i, n-1) # drown all right bound islands
for j in range(n):
self.dfs(grid, 0, j) # drown all upper bound islands
self.dfs(grid, m-1, j) # drown all lower bound islands
for i in range(m):
for j in range(n):
if (grid[i][j] == 0):
res += 1
self.dfs(grid, i, j)
return res
def dfs(self, grid, i, j):
m = len(grid)
n = len(grid[0])
if (i < 0 or j < 0 or i >= m or j >= n): return
if (grid[i][j] == 1): return
grid[i][j] = 1
self.dfs(grid, i-1, j)
self.dfs(grid, i+1, j)
self.dfs(grid, i, j-1)
self.dfs(grid, i, j+1) | number-of-closed-islands | Simple Python solution using DFS | leqinancy | 0 | 26 | number of closed islands | 1,254 | 0.642 | Medium | 18,764 |
https://leetcode.com/problems/number-of-closed-islands/discuss/2106987/Python3-or-100-or-DFS | class Solution:
def closedIsland(self, grid: List[List[int]]) -> int:
def dfs(grid, i, j):
if grid[i][j] == 1:
return True
if i<=0 or j<=0 or i>=len(grid)-1 or j>= len(grid[0])-1:
return False
grid[i][j] = 1
t1 = dfs(grid,i+1,j)
t2 = dfs(grid,i-1,j)
t3 = dfs(grid,i,j+1)
t4 = dfs(grid,i,j-1)
return t1 and t2 and t3 and t4
count = 0
for i in range(1,len(grid)-1):
for j in range(1, len(grid[0])-1):
if grid[i][j] == 0 and dfs(grid,i,j):
count += 1
return count | number-of-closed-islands | Python3 | 100% | DFS | iamirulofficial | 0 | 100 | number of closed islands | 1,254 | 0.642 | Medium | 18,765 |
https://leetcode.com/problems/number-of-closed-islands/discuss/1993611/Using-recursion-DFS | class Solution:
def closedIsland(self, A: List[List[int]]) -> int:
self.visited=set()
d_=[(0,1),(1,0),(-1,0),(0,-1)]
def recur(i,j):
self.visited.add((i,j))
for a,b in d_:
if i+a < 0 or i+a == len(A) or j+b < 0 or j+b == len(A[0]):
self.visited.remove((i,j))
return False
elif 0 <= i+a < len(A) and 0 <= j+b < len(A[0]):
if A[i+a][j+b]==0 and (i+a,j+b) not in self.visited:
z=recur(i+a,j+b)
if not z:
self.visited.remove((i,j))
return False
return True
count=0
for i in range(len(A)):
for j in range(len(A[0])):
if A[i][j]==0 and (i,j) not in self.visited:
z=recur(i,j)
if z:
count+=1
#print(i,j)
return count | number-of-closed-islands | Using recursion, DFS | amit_upadhyay | 0 | 38 | number of closed islands | 1,254 | 0.642 | Medium | 18,766 |
https://leetcode.com/problems/number-of-closed-islands/discuss/1841633/Without-filling-boundary-touching-islands-(no-flood-fill) | class Solution:
def closedIsland(self, grid: List[List[int]]) -> int:
rows = len(grid)
cols = len(grid[0])
visited = [[False for j in range(cols)] for i in range(rows)]
dirs = [(0,1),(1,0),(-1,0),(0,-1)]
def dfs(i, j):
state = True
if 0 <= i < rows and 0 <= j < cols:
if not visited[i][j] and grid[i][j] == 0:
if i in [0, rows - 1] or j in [0, cols - 1]:
return False
visited[i][j] = True
for di, dj in dirs:
state = dfs(i + di, j + dj) and state
return state
return True
count = 0
for i in range(1, rows-1):
for j in range(1, cols-1):
if not visited[i][j] and grid[i][j] == 0:
if dfs(i, j):
count += 1
return count | number-of-closed-islands | Without filling boundary touching islands (no flood fill) | aayushisingh1703 | 0 | 71 | number of closed islands | 1,254 | 0.642 | Medium | 18,767 |
https://leetcode.com/problems/number-of-closed-islands/discuss/1820621/Easy-understanding-DFS-solution-(-Runtime-224ms-and-space-beats-77.4-of-users) | class Solution:
def closedIsland(self, grid: List[List[int]]) -> int:
count =0
def dfs(i,j):
if i<0 or i > len(grid)-1 or j<0 or j> len(grid[0])-1 :
return False
if grid[i][j] == '#' or grid[i][j] == 1:
return True
grid[i][j] ='#'
a = dfs(i-1,j)
b = dfs(i,j-1)
c = dfs(i+1,j)
d = dfs(i,j+1)
return a and b and c and d
for i in range(1,len(grid)):
for j in range(1,len(grid[0])):
if grid[i][j] == 0 and dfs(i,j):
count+=1
return count | number-of-closed-islands | Easy understanding DFS solution ( Runtime 224ms and space beats 77.4% of users) | hackerbb | 0 | 69 | number of closed islands | 1,254 | 0.642 | Medium | 18,768 |
https://leetcode.com/problems/number-of-closed-islands/discuss/1800039/Python-Iterative-BFS | class Solution:
def closedIsland(self, grid: List[List[int]]) -> int:
ROWS, COLS = len(grid), len(grid[0])
directions = ((0, 1), (-1, 0), (0, -1), (1, 0))
count = 0
seen = set()
for i in range(1, ROWS - 1):
for j in range(1, COLS - 1):
if grid[i][j] == 0 and (i, j) not in seen:
if self.bfs(i, j, seen, grid, ROWS, COLS, directions):
count += 1
return count
def bfs(self, i, j, seen, grid, ROWS, COLS, directions):
q = deque([(i, j)])
seen.add((i, j))
falseButContinueExploring = False
'''
The reason why we continue exploring even though the solution is false is because
we want to mark all the incorrect cells as visited so we don't run BFS on them again
as we do not want our algorithm to think the unvisited lands different island.
[1,1,1]
[1,0,0] <- If we return False whenever there is land at first/last column/row then the algorithm
[1,0,1] will determine the unvisited but connected lands as a separate island
[1,0,1] in the upcoming iterations
[1,1,1]
'''
while q:
r, c = q.popleft()
for dr, dc in directions:
dr, dc = dr + r, dc + c
if -1 < dr < ROWS and -1 < dc < COLS and (dr, dc) not in seen and grid[dr][dc] == 0:
if not falseButContinueExploring:
if grid[dr][dc] == 0 and (dr == 0 or dr == ROWS - 1 or dc == 0 or dc == COLS - 1):
falseButContinueExploring = True
q.append((dr, dc))
seen.add((dr, dc))
return False if falseButContinueExploring else True | number-of-closed-islands | Python Iterative BFS | Rush_P | 0 | 70 | number of closed islands | 1,254 | 0.642 | Medium | 18,769 |
https://leetcode.com/problems/number-of-closed-islands/discuss/1385849/Runtime%3A-120-ms-faster-than-97.38-of-Python3-online-submissions | class Solution:
def closedIsland(self, grid: List[List[int]]) -> int:
def helper(i,j,grid):
if grid[i][j]==1:
return True
if i<=0 or i>=(len(grid)-1) or j<=0 or j>=(len(grid[0])-1):
return False
grid[i][j]=1
down=helper(i+1,j,grid)
right=helper(i,j+1,grid)
up=helper(i-1,j,grid)
left=helper(i,j-1,grid)
return up and left and right and down
c=0
for i in range(1,len(grid)-1):
for j in range(1,len(grid[0])-1):
if grid[i][j]==0 and helper(i,j,grid):
c+=1
return c | number-of-closed-islands | Runtime: 120 ms, faster than 97.38% of Python3 online submissions | harshmalviya7 | 0 | 82 | number of closed islands | 1,254 | 0.642 | Medium | 18,770 |
https://leetcode.com/problems/number-of-closed-islands/discuss/924612/Python-solution-with-explanation | class Solution:
def closedIsland(self, a: List[List[int]]) -> int:
LAND, WATER = 0, 1
directions = [[0,1], [0,-1], [1,0], [-1,0]]
def is_boundary(i, j):
if i == 0 or i == m - 1 or j == 0 or j == n - 1:
return True
return False
def dfs(i, j, boundary=False):
v[i][j] = 1
if boundary: a[i][j] = 2
for x, y in directions:
ii, jj = x + i, y + j
if 0 <= ii < m and 0 <= jj < n:
if a[ii][jj] == WATER or v[ii][jj]:
continue
dfs(ii, jj, boundary)
m, n, ans = len(a), len(a[0]), 0
v = [[0] * n for _ in range(m)]
# first step
for i in range(m):
for j in range(n):
if not v[i][j] and a[i][j] == LAND and is_boundary(i, j):
dfs(i, j, True)
# second step
for i in range(1, m-1):
for j in range(1, n-1):
if not v[i][j] and a[i][j] == LAND:
dfs(i, j)
ans += 1
return ans | number-of-closed-islands | Python solution with explanation | dh7 | 0 | 139 | number of closed islands | 1,254 | 0.642 | Medium | 18,771 |
https://leetcode.com/problems/number-of-closed-islands/discuss/783235/Python-3-Recursive-DFS-97.48-faster | class Solution:
def isClosedIsalnd(self, grid, i, j , rows, cols):
# -1 visited
# 0 - land
# 1 - water
if grid[i][j]==-1 or grid[i][j]==1:
return True
# we know we have a 0(land, if we have passed above statement)
if self.isOnPerimeter(i, j, rows, cols):
return False
# mark as visited
grid[i][j]=-1
# check all surroundings
left = self.isClosedIsalnd(grid, i, j-1 , rows, cols)
right = self.isClosedIsalnd(grid, i, j+1 , rows, cols)
top = self.isClosedIsalnd( grid, i-1, j , rows, cols)
bottom = self.isClosedIsalnd( grid, i+1, j , rows, cols)
# True only if surrounded by water on all sides
return top and left and right and bottom
def isOnPerimeter(self,i, j, rows, cols):
if i==0 or i==rows-1 or j==0 or j==cols-1:
return True
def closedIsland(self, grid: List[List[int]]) -> int:
if len(grid)==0:
return 0
closed_islands = 0
rows = len(grid)
cols = len(grid[0])
# we need to iterate over only matrix which are not on perimeter
for i in range(1, rows-1):
for j in range(1, cols-1):
if grid[i][j]==0:
if self.isClosedIsalnd(grid, i, j , rows, cols):
closed_islands+=1
return closed_islands | number-of-closed-islands | Python 3 Recursive DFS - 97.48% faster | tanu91 | 0 | 138 | number of closed islands | 1,254 | 0.642 | Medium | 18,772 |
https://leetcode.com/problems/number-of-closed-islands/discuss/782485/Python-3-DFS-clear-logic | class Solution:
def closedIsland(self, grid: List[List[int]]) -> int:
def dfs(i, j):
grid[i][j] = 1
for di, dj in [[0,1],[0,-1],[1,0],[-1,0]]:
x, y = i+di, j+dj
if 0 <= x < m and 0 <= y < n and grid[x][y] == 0: dfs(x, y)
m, n = len(grid), len(grid[0])
# top & bottom
for j in range(n):
if not grid[0][j]: dfs(0, j)
if not grid[m-1][j]: dfs(m-1, j)
# left & right
for i in range(m):
if not grid[i][0]: dfs(i, 0)
if not grid[i][n-1]: dfs(i, n-1)
# count closed islands
ans = 0
for i in range(1, m-1):
for j in range(1, n-1):
if not grid[i][j]:
ans += 1
dfs(i, j)
return ans | number-of-closed-islands | Python 3 DFS clear logic | idontknoooo | 0 | 227 | number of closed islands | 1,254 | 0.642 | Medium | 18,773 |
https://leetcode.com/problems/number-of-closed-islands/discuss/1458630/Python3-or-Explained-Flood-Fill-Approach | class Solution:
def closedIsland(self, grid: List[List[int]]) -> int:
m=len(grid)
n=len(grid[0])
ans=0
#replacing all 0's to -1
for i in range(m):
for j in range(n):
if grid[i][j]==0:
grid[i][j]=-1
#reconverting -1's at boundaries and -1's connected with -1's at boundary to 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:
self.dfs(i,j,grid,m,n)
#checking for number of closed island.
for i in range(m):
for j in range(n):
if grid[i][j]==-1:
ans+=1
self.dfs(i,j,grid,m,n)
return ans
def dfs(self,row,col,grid,m,n):
grid[row][col]=0
if row-1>=0 and grid[row-1][col]==-1:
self.dfs(row-1,col,grid,m,n)
if row+1<m and grid[row+1][col]==-1:
self.dfs(row+1,col,grid,m,n)
if col-1>=0 and grid[row][col-1]==-1:
self.dfs(row,col-1,grid,m,n)
if col+1<n and grid[row][col+1]==-1:
self.dfs(row,col+1,grid,m,n)
return | number-of-closed-islands | [Python3] | Explained Flood-Fill Approach | swapnilsingh421 | -1 | 52 | number of closed islands | 1,254 | 0.642 | Medium | 18,774 |
https://leetcode.com/problems/maximum-score-words-formed-by-letters/discuss/2407807/PYTHON-SOL-or-RECURSION-%2B-MEMOIZATION-or-EXPLAINED-or-CLEAR-AND-CONSCISE-or | class Solution:
def maxScoreWords(self, words: List[str], letters: List[str], score: List[int]) -> int:
count , n , dp = [0]*26 , len(words) , {}
for c in letters: count[ord(c) - 97] += 1
def recursion(index,count):
if index == n: return 0
tpl = tuple(count)
if (index,tpl) in dp: return dp[(index,tpl)]
ans = recursion(index + 1, count)
flag , tmp , cpy , add = True , defaultdict(int) , count.copy() , 0
for c in words[index]: tmp[c] += 1
for key in tmp:
if tmp[key] <= cpy[ord(key) - 97]:
cpy[ord(key) - 97] -= tmp[key]
add += score[ord(key) - 97] * tmp[key]
else:
flag = False
break
if flag : ans = max(ans, recursion(index + 1, cpy) + add)
dp[(index,tpl)] = ans
return ans
return recursion(0 , count) | maximum-score-words-formed-by-letters | PYTHON SOL | RECURSION + MEMOIZATION | EXPLAINED | CLEAR AND CONSCISE | | reaper_27 | 0 | 42 | maximum score words formed by letters | 1,255 | 0.728 | Hard | 18,775 |
https://leetcode.com/problems/maximum-score-words-formed-by-letters/discuss/2262572/Python3-or-Similar-to-Subsets-Problem | class Solution:
def maxScoreWords(self, words: List[str], letters: List[str], score: List[int]) -> int:
freq=[0 for i in range(26)]
for c in letters:
freq[ord(c)-97]+=1
return self.solve(0,words,letters,freq,score)
def solve(self,ind,words,letters,freq,score):
if ind==len(words):
return 0
# not including
wniScore=0+self.solve(ind+1,words,letters,freq,score)
#including
wiScore,flag,cwScore=[0]*3
for c in words[ind]:
if freq[ord(c)-97]==0:
flag=1
freq[ord(c)-97]-=1
cwScore+=score[ord(c)-97]
if not flag:
wiScore=cwScore+self.solve(ind+1,words,letters,freq,score)
#correcting freq array before backtracking
for c in words[ind]:
freq[ord(c)-97]+=1
return max(wniScore,wiScore) | maximum-score-words-formed-by-letters | [Python3] | Similar to Subsets Problem | swapnilsingh421 | 0 | 12 | maximum score words formed by letters | 1,255 | 0.728 | Hard | 18,776 |
https://leetcode.com/problems/maximum-score-words-formed-by-letters/discuss/1581707/Python3-Backtracking-solution | class Solution:
def __init__(self):
self.res = 0
self.word2score = collections.defaultdict(int)
def is_key_valid(self, key, latters_key):
for k in key:
if k not in latters_key or key[k] > latters_key[k]:
return False
return True
def get_word_score(self, key, score):
cur_score = 0
for k in key:
cur_score += score[ord(k) - 97] * key[k]
return cur_score
def backtracking(self, words, word2key, latters_key, score, cur_sum_score):
for i in range(len(words)):
if self.is_key_valid(word2key[words[i]], latters_key):
if words[i] not in self.word2score:
self.word2score[words[i]] = self.get_word_score(word2key[words[i]], score)
for c in words[i]:
latters_key[c] -= 1
self.backtracking(words[:i] + words[i+1:], word2key, latters_key, score, [cur_sum_score[0] + self.word2score[words[i]]])
for c in words[i]:
latters_key[c] += 1
self.res = max(self.res, cur_sum_score[0])
def maxScoreWords(self, words: List[str], letters: List[str], score: List[int]) -> int:
letters_key = collections.defaultdict(int)
for c in letters:
letters_key[c] += 1
word2key = {}
for word in words:
key = collections.defaultdict(int)
for c in word:
key[c] += 1
word2key[word] = key
self.backtracking(words, word2key, letters_key, score, [0])
return self.res | maximum-score-words-formed-by-letters | [Python3] Backtracking solution | maosipov11 | 0 | 56 | maximum score words formed by letters | 1,255 | 0.728 | Hard | 18,777 |
https://leetcode.com/problems/maximum-score-words-formed-by-letters/discuss/463035/Python-3-(eight-lines)-(100-ms)-(Check-all-Combinations)-(Memoize-those-that-exceed-letter-count) | class Solution:
def maxScoreWords(self, W: List[str], T: List[str], S: List[int]) -> int:
L, CT, D, SL, X, M = len(W), collections.Counter(T), {a:S[i] for i,a in enumerate(string.ascii_lowercase)}, set(''.join(W)), set(), 0
for n in range(1,L+1):
for wc in itertools.combinations(range(L),n):
if any(wc[:i] in X for i in range(1,len(wc)+1)): continue
CC = collections.Counter(''.join([W[i] for i in wc]))
if any(CT[c] < CC[c] for c in SL): X.add(wc)
else: M = max(M,sum(D[i]*CC[i] for i in CC))
return M
- Junaid Mansuri
- Chicago, IL | maximum-score-words-formed-by-letters | Python 3 (eight lines) (100 ms) (Check all Combinations) (Memoize those that exceed letter count) | junaidmansuri | -5 | 258 | maximum score words formed by letters | 1,255 | 0.728 | Hard | 18,778 |
https://leetcode.com/problems/shift-2d-grid/discuss/1935910/Just-Flatten-and-Rotate-the-Array | class Solution:
def rotate(self, nums: List[int], k: int) -> None: # From Leetcode Problem 189. Rotate Array
n = len(nums)
k = k % n
nums[:] = nums[n - k:] + nums[:n - k]
def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:
m, n = len(grid), len(grid[0])
arr = [i for sublist in grid for i in sublist] # Flatten out the array
self.rotate(arr,k) # Rotate the array
grid = [[arr[i*n+j] for j in range(n)] for i in range(m)] # Convert Flattened output to 2d Matrix
return grid # Return 2d Result | shift-2d-grid | ⭐ Just Flatten and Rotate the Array | anCoderr | 5 | 330 | shift 2d grid | 1,260 | 0.68 | Easy | 18,779 |
https://leetcode.com/problems/shift-2d-grid/discuss/1015725/Easy-and-Clear-Solution-Python-3 | class Solution:
def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:
res=[]
m,n=len(grid),len(grid[0])
k=k%(m*n)
for i in grid:
for j in i:
res.append(j)
res=res[m*n-k:]+res[0:m*n-k]
cp=n
aux=[]
ans=[]
for i in res:
aux.append(i)
cp-=1
if cp==0:
ans.append(aux)
aux=[]
cp=n
return ans | shift-2d-grid | Easy & Clear Solution Python 3 | moazmar | 2 | 459 | shift 2d grid | 1,260 | 0.68 | Easy | 18,780 |
https://leetcode.com/problems/shift-2d-grid/discuss/437034/Three-Solutions-in-Python-3-(two-lines)-(beats-~98) | class Solution:
def shiftGrid(self, G: List[List[int]], k: int) -> List[List[int]]:
M, N, P = len(G), len(G[0]), len(G)*len(G[0])
return [[G[i%P//N][i%N] for i in range(P-k+j*N,P-k+N+j*N)] for j in range(M)]
class Solution:
def shiftGrid(self, G: List[List[int]], k: int) -> List[List[int]]:
M, N, H, k = len(G), len(G[0]), sum(G,[]), k % (len(G)*len(G[0]))
I = H[-k:] + H[:-k]
return [I[i*N:(i+1)*N] for i in range(M)]
class Solution:
def shiftGrid(self, G: List[List[int]], k: int) -> List[List[int]]:
M, N, P = len(G), len(G[0]), len(G)*len(G[0])
A = [[0]*N for _ in range(M)]
for i in range(P): A[(i+k)%P//N][((i+k)%P)%N]= G[i//N][i%N]
return A
- Junaid Mansuri | shift-2d-grid | Three Solutions in Python 3 (two lines) (beats ~98%) | junaidmansuri | 2 | 415 | shift 2d grid | 1,260 | 0.68 | Easy | 18,781 |
https://leetcode.com/problems/shift-2d-grid/discuss/1936534/Simple-Python-using-deque | class Solution:
def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:
for x in range(k):
lst=collections.deque()
for i in range(len(grid)):
grid[i]=collections.deque(grid[i])
grid[i].rotate(1)
# print(i)
lst.append(grid[i][0])
# print(grid)
lst.rotate(1)
for i in grid:
a=lst.popleft()
i[0]=a
return grid | shift-2d-grid | Simple Python using deque | amannarayansingh10 | 1 | 39 | shift 2d grid | 1,260 | 0.68 | Easy | 18,782 |
https://leetcode.com/problems/shift-2d-grid/discuss/1936475/Python3-or-Shifting-in-2D-or-Simple | class Solution:
def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:
for j in range(k): # Shifting k times
for i in range(len(grid)): # Shifting without disturbing the structure
if i==len(grid)-1:
a=grid[i].pop()
grid[0].insert(0,a)
else:
a=grid[i].pop()
grid[i+1].insert(0,a)
return grid | shift-2d-grid | Python3 | Shifting in 2D | Simple | hidden1o1 | 1 | 25 | shift 2d grid | 1,260 | 0.68 | Easy | 18,783 |
https://leetcode.com/problems/shift-2d-grid/discuss/1936218/Python-Very-Easy-O(1)-Space | class Solution:
def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:
m = len(grid)
n = len(grid[0])
d = m*n
ans = [[0] * n for _ in range(m)]
start = d - k
for i in range(m):
for j in range(n):
start %= d
r = start // n
c = start % n
ans[i][j] = grid[r][c]
start += 1
return ans | shift-2d-grid | ✅ Python Very Easy O(1) Space | dhananjay79 | 1 | 195 | shift 2d grid | 1,260 | 0.68 | Easy | 18,784 |
https://leetcode.com/problems/shift-2d-grid/discuss/1936218/Python-Very-Easy-O(1)-Space | class Solution:
def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:
def reverse(start, end, n):
while start < end:
grid[start // n][start % n], grid[end // n][end % n] = grid[end // n][end % n], grid[start // n][start % n]
start += 1
end -= 1
n = len(grid[0])
d = len(grid) * n
k = k % d
reverse(0, d - k - 1, n)
reverse(d - k, d - 1, n)
reverse(0, d - 1, n)
return grid | shift-2d-grid | ✅ Python Very Easy O(1) Space | dhananjay79 | 1 | 195 | shift 2d grid | 1,260 | 0.68 | Easy | 18,785 |
https://leetcode.com/problems/shift-2d-grid/discuss/1311885/Python-3-140-ms-faster-than-99.15 | class Solution:
def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:
m, n = len(grid), len(grid[0])
k = k % (m * n)
stack = []
for row in grid:
stack += row
stack = stack[-k:] + stack[:-k]
return [stack[i * n: (i + 1) * n] for i in range(m)] | shift-2d-grid | Python 3, 140 ms, faster than 99.15% | MihailP | 1 | 224 | shift 2d grid | 1,260 | 0.68 | Easy | 18,786 |
https://leetcode.com/problems/shift-2d-grid/discuss/2711951/Python-Simple-solution-with-itertools-and-deque | class Solution:
def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:
rows = len(grid)
cols = len(grid[0])
output = []
temp = collections.deque(itertools.chain(*grid))
temp.rotate(k)
for i in range(rows):
row = []
for j in range(cols):
row.append(temp.popleft())
output.append(row)
return output | shift-2d-grid | Python - Simple solution with itertools and deque | ptegan | 0 | 4 | shift 2d grid | 1,260 | 0.68 | Easy | 18,787 |
https://leetcode.com/problems/shift-2d-grid/discuss/2699656/Easy-or-Python | class Solution:
def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:
n = len(grid)
m = len(grid[0])
temp = float("inf")
for t in range(0,k):
for i in range(0,n):
for j in range(0,m):
if(i == 0 and j == 0 ):
temp = grid[i][j]
else:
t1 = grid[i][j]
grid[i][j] = temp
temp = t1
grid[0][0] = temp
return grid | shift-2d-grid | Easy | Python | pranshuvishnoi85 | 0 | 6 | shift 2d grid | 1,260 | 0.68 | Easy | 18,788 |
https://leetcode.com/problems/shift-2d-grid/discuss/2612605/python-solution-98.10-faster | class Solution:
def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:
if k == len(grid[0]) * len(grid):
return grid
q = []
for row in grid:
for col in row:
q.append(col)
for _ in range(k):
q.insert(0, q[-1])
q.pop()
result = []
while q:
result.append(q[:len(grid[0])])
q = q[len(grid[0]):]
return result | shift-2d-grid | python solution 98.10% faster | samanehghafouri | 0 | 21 | shift 2d grid | 1,260 | 0.68 | Easy | 18,789 |
https://leetcode.com/problems/shift-2d-grid/discuss/2590033/Python3-cyclic-sort-modular-arithmetic-constant-space-O(mn) | class Solution:
def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:
self.cyclic(grid, k, len(grid), len(grid[0]))
self.redact(grid, len(grid), len(grid[0]))
return grid
def cyclic(self, grid: List[List[int]], k: int, rows: int, cols: int):
for r in range(rows):
for c in range(cols):
cell = grid[r][c]
if cell > 1000:
continue
destx, desty = self.calculate(k, r, c, rows, cols)
while not (r == destx and c == desty):
self.swap(grid, r, c, destx, desty)
destx, desty = self.calculate(k, destx, desty, rows, cols)
self.mark(grid, r, c)
def calculate(self, k: int, currx: int, curry: int, rows: int, cols: int) -> Tuple[int, int]:
desty = (curry + k) % cols
destx = (currx + ((curry + k) // cols)) % rows
return destx, desty
def swap(self, m: List[List[int]], fromx: int, fromy: int, tox: int, toy: int):
temp = m[tox][toy]
m[tox][toy] = m[fromx][fromy] + 2001
m[fromx][fromy] = temp
def mark(self, m:List[List[int]], x: int, y: int):
m[x][y] += 2001
def redact(self, m: List[List[int]], rows: int, cols: int):
for r in range(rows):
for c in range(cols):
m[r][c] -= 2001 | shift-2d-grid | [Python3] cyclic sort, modular arithmetic, constant space, O(mn) | DG_stamper | 0 | 13 | shift 2d grid | 1,260 | 0.68 | Easy | 18,790 |
https://leetcode.com/problems/shift-2d-grid/discuss/2371793/Python3-or-S(n)-O(n)-T(n)-O(n)-or-matrix-to-array-greater-rotate-array-greater-array-to-matrix | class Solution:
def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:
m, n = len(grid), len(grid[0])
cache = []
for i in range(m):
for j in range(n):
cache.append(grid[i][j])
k %= len(cache)
new_vals = cache[-k:] + cache[:-k]
cur = 0
for i in range(m):
for j in range(n):
grid[i][j] = new_vals[cur]
cur += 1
return grid | shift-2d-grid | Python3 | S(n) = O(n), T(n) = O(n) | matrix to array -> rotate array -> array to matrix | Ploypaphat | 0 | 35 | shift 2d grid | 1,260 | 0.68 | Easy | 18,791 |
https://leetcode.com/problems/shift-2d-grid/discuss/2312876/Python-2-approaches | class Solution(object):
def shiftGrid(self, grid, k):
rows = len(grid)
cols = len(grid[0])
for _ in range(k):
for i in range(rows):
temp = grid[i][-1]
for j in reversed(range(1,cols)):
grid[i][j] = grid[i][j-1]
grid[i][0] = temp
temp = grid[-1][0]
for i in reversed(range(1,rows)):
grid[i][0] = grid[i-1][0]
grid[0][0] = temp
return grid | shift-2d-grid | Python 2 approaches | Abhi_009 | 0 | 42 | shift 2d grid | 1,260 | 0.68 | Easy | 18,792 |
https://leetcode.com/problems/shift-2d-grid/discuss/2312876/Python-2-approaches | class Solution:
def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:
cols = len(grid[0])
rows = len(grid)
def mat2arr(r,c):
return r*cols+c
def arr2mat(id):
return (id//cols,id%cols)
res = [[0]*cols for i in range(rows)]
for i in range(rows):
for j in range(cols):
newval = (mat2arr(i,j)+k)%(cols*rows)
newR,newC = arr2mat(newval)
res[newR][newC] = grid[i][j]
return res | shift-2d-grid | Python 2 approaches | Abhi_009 | 0 | 42 | shift 2d grid | 1,260 | 0.68 | Easy | 18,793 |
https://leetcode.com/problems/shift-2d-grid/discuss/2124048/Python-Solution-Flatten-In-Grid | class Solution:
def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:
ln, lc, s = len(grid), len(grid[0]), 0
mult = ln * lc
k %= mult
for i in range(ln):
grid.extend(grid[i])
grid = grid[ln:]
for i in range(k):
temp = None
for j in range(1, len(grid) + 1):
if temp is None:
temp = grid[j % mult]
grid[j % mult] = grid[(j - 1) % mult]
else:
grid[j % mult], temp = temp, grid[j % mult]
return [grid[f : f + lc] for f in range(0, ln * lc, lc)] | shift-2d-grid | Python Solution, Flatten In Grid | Hejita | 0 | 53 | shift 2d grid | 1,260 | 0.68 | Easy | 18,794 |
https://leetcode.com/problems/shift-2d-grid/discuss/2077493/Python-Solutions-with-O(M*N)-Time-and-Space-Complexity | class Solution:
def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:
row, col = len(grid), len(grid[0])
matrix = [[0] * col for _ in range(row)]
def coordinateToIndex(r,c):
return (r*col + c)
def indexToCoordinate(val):
return [val//col, val%col]
for r in range(row):
for c in range(col):
index = (coordinateToIndex(r,c) + k) % (row*col)
newR, newC = indexToCoordinate(index)
matrix[newR][newC] = grid[r][c]
return matrix | shift-2d-grid | [Python] Solutions with O(M*N) Time and Space Complexity | rtyagi1 | 0 | 78 | shift 2d grid | 1,260 | 0.68 | Easy | 18,795 |
https://leetcode.com/problems/shift-2d-grid/discuss/2006916/python-3-oror-simple-solution-oror-O(mn)O(mn) | class Solution:
def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:
m, n = len(grid), len(grid[0])
res = [[0] * n for _ in range(m)]
for i, row in enumerate(grid):
for j, num in enumerate(row):
pos = (i*n + j + k) % (m*n)
newI, newJ = divmod(pos, n)
res[newI][newJ] = num
return res | shift-2d-grid | python 3 || simple solution || O(mn)/O(mn) | dereky4 | 0 | 73 | shift 2d grid | 1,260 | 0.68 | Easy | 18,796 |
https://leetcode.com/problems/shift-2d-grid/discuss/1940043/With-documentation-Python-flatten-to-1D-and-then-rotate-and-then-stack-to-2D-(very-fast) | class Solution:
def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:
h = len(grid)
w = len(grid[0])
n = h * w
# Flatten the 2D grid to 1D:
flat_grid = [cell for row in grid for cell in row]
# Cycle of size of n is returning to the same position.
k %= n
# Split and concat the list to be rotated:
# E.g., 123456 → 56 + 1234 → 561234.
rotated_grid = flat_grid[-k:] + flat_grid[:-k]
# Transform a 1D array to 2D grid:
new_grid = [rotated_grid[i*w:i*w+w] for i in range(h)]
return new_grid | shift-2d-grid | With documentation - Python flatten to 1D and then rotate and then stack to 2D (very fast) | sEzio | 0 | 9 | shift 2d grid | 1,260 | 0.68 | Easy | 18,797 |
https://leetcode.com/problems/shift-2d-grid/discuss/1937511/Python-short-functional-programming-O(1)-space-solution | class Solution:
def shiftGrid(self, grid: list[list[int]], k_: int) -> list[list[int]]:
m, n = len(grid), len(grid[0])
t = m * n
k = k_ % t
initial_nums = chain.from_iterable(grid)
shifted_nums = islice(cycle(initial_nums), t - k, t - k + t)
# If asked for inplace (side effects and not FP):
# for i, j in product(range(m), range(n)): grid[i][j] = next(shifted_nums)
# return grid
return [list(islice(shifted_nums, n)) for _ in range(m)] | shift-2d-grid | Python short functional programming, O(1) space solution | itisdarshan | 0 | 19 | shift 2d grid | 1,260 | 0.68 | Easy | 18,798 |
https://leetcode.com/problems/shift-2d-grid/discuss/1937248/Different-Solution-using-modulo | class Solution:
def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:
num_of_rows = len(grid)
num_of_columns = len(grid[0])
remaining = k % num_of_columns
temp = []
if k >= num_of_columns:
for _ in range(k // num_of_columns):
bottom_row = grid.pop(num_of_rows - 1)
grid.insert(0, bottom_row)
for _ in range(remaining):
for i in range(num_of_rows - 1, -1, -1):
temp.append(grid[i].pop(num_of_columns - 1))
grid[0].insert(0, temp.pop(0))
for i in range(num_of_rows - 1, 0, -1):
grid[i].insert(0, temp.pop(0))
return grid | shift-2d-grid | Different Solution using modulo | jaineshster | 0 | 16 | shift 2d grid | 1,260 | 0.68 | Easy | 18,799 |
Subsets and Splits
Top 2 Solutions by Upvotes
Identifies the top 2 highest upvoted Python solutions for each problem, providing insight into popular approaches.