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 ... | 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] == ')':
... | 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... | 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 ... | 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:
... | 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:
con... | 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:
... | 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:
... | 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:
... | 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:
... | 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:
... | 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] == ')':
... | 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] == "(":
... | 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)
... | 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):
# ... | 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)... | 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.p... | 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... | 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 ... | 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
... | 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
... | 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 ... | 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[indic... | 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 su... | 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
... | 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
... | 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:
... | 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])
... | 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]] = [... | 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][... | 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):... | 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)
... | 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:
... | 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):... | 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))... | 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... | 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. ... | 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:
... | 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)
... | 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 colsu... | 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 []
... | 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... | 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=df... | 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]... | 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
... | 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(g... | 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
... | 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... | 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)
... | 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) ... | 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)):
... | 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:
... | 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... | 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:
... | 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):
... | 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... | 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)
... | 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))
... | 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.df... | 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)):
... | 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 ... | 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
... | 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]):
... | 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 <... | 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] ='#'
... | 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):
... | 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,g... | 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
... | 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):
... | 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(g... | 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 a... | 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
... | 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=... | 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
... | 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)... | 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])
... | 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=[]
... | 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]]:
... | 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)
... | 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]... | 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
... | 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
... | 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... | 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 = []
fo... | 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):
... | 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])
... | 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(r... | 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[:... | 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]
... | 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... | 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... | 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):
... | 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, ... | 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 returnin... | 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 ask... | 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):
... | 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.