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/sort-the-matrix-diagonally/discuss/489833/Python3-simple-solution-using-a-dict() | class Solution:
def diagonalSort(self, mat: List[List[int]]) -> List[List[int]]:
if len(mat) == 1: return mat
m,n,ht = len(mat),len(mat[0]),collections.defaultdict(list)
for i in range(m):
for j in range(n):
ht[i-j].append(mat[i][j])
for key in ht:
ht[key].sort()
for i in range(m):
for j in range(n):
mat[i][j] = ht[i-j].pop(0)
return mat | sort-the-matrix-diagonally | Python3 simple solution using a dict() | jb07 | 1 | 86 | sort the matrix diagonally | 1,329 | 0.836 | Medium | 19,900 |
https://leetcode.com/problems/sort-the-matrix-diagonally/discuss/2496962/Python-Intuitive-Solution | class Solution:
def diagonalSort(self, mat: List[List[int]]) -> List[List[int]]:
col, row = len(mat[0]), len(mat)
mat_storage = [[] for _ in range(col + row - 1)]
for c in range(col):
for r in range(row):
mat_storage[(c - r)].append(mat[r][c])
for i in range(len(mat_storage)):
mat_storage[i] = sorted(mat_storage[i])
ans = [[None for _ in range(col)] for _ in range(row)]
for c2 in range(col):
for r2 in range(row):
if c2 - r2 >= 0:
ans[r2][c2] = mat_storage[c2 - r2][r2]
else:
ans[r2][c2] = mat_storage[c2 - r2][c2]
return ans | sort-the-matrix-diagonally | [Python] Intuitive Solution | AustinHuang823 | 0 | 5 | sort the matrix diagonally | 1,329 | 0.836 | Medium | 19,901 |
https://leetcode.com/problems/sort-the-matrix-diagonally/discuss/2495043/Python3-simple-solution-with-comments | class Solution:
def diagonalSort(self, mat: list[list[int]]) -> list[list[int]]:
# height matrix [1,2,3] ^
# [2,3,4] | - height or len([[1, 2, 3], [2, 3, 4], [3, 4, 5]])
# [3,4,5] |
height = len(mat)
# width matrix [1,2,3]
# [2,3,4]
# [3,4,5]
# ------> - width
width = len(mat[0])
# if width == 1 -> this matrix is [[1], [2], [3] etc]
# just return mat.
if width == 1:
return mat
# this\'s a copy of mat, but it\'s empty.
matrix = [[[] for _ in range(width)] for _ in range(height)]
# 2 lists: for example [1,2,3]
# [2,3,4]
# [3,4,5],
# first = [[], [], []]
# second = [[], []]
first = [[] for _ in range(width)]
second = [[] for _ in range(height - 1)] # -1, because we take the matrix from the first element matrix[1][0]
# loop for second list this is [@1, @2, @3]
# [ 2, @3, @4]
# [ 3, 4, @5]
for i in range(width):
first[i].append(mat[0][i])
for j in range(1, height):
# if index abroad matrix
if i + j >= width:
break
first[i].append(mat[j][j + i])
# loop for second list this is [ 1, 2, 3]
# [@2, 3, 4]
# [@3, @4, 5]
for k in range(1, height):
second[k - 1].append(mat[k][0])
for m in range(1, width):
# if index abroad matrix
if k + m >= height:
break
second[k - 1].append(mat[m + k][m])
# sort all lists in the matrix
sorted_first = [sorted(q) for q in first]
sorted_second = [sorted(q) for q in second]
# filling in the matrix on the right
for e, a in enumerate(sorted_first):
for e2, b in enumerate(a):
matrix[e2][e + e2] = b
# filling in the matrix on the left
for e3, f in enumerate(sorted_second, start=1):
for e4, g in enumerate(f):
matrix[e3 + e4][e4] = g
return matrix | sort-the-matrix-diagonally | Python3 simple solution with comments | vadimchk | 0 | 7 | sort the matrix diagonally | 1,329 | 0.836 | Medium | 19,902 |
https://leetcode.com/problems/sort-the-matrix-diagonally/discuss/2494948/Python3-In-Place-Sorting | class Solution:
def diagonalSort(self, mat: List[List[int]]) -> List[List[int]]:
m, n = len(mat), len(mat[0])
starts = [(0,j) for j in range(n)] + [(i,0) for i in range(1,m)]
for i,j in starts:
diag = []
while i<m and j<n:
diag.append(mat[i][j])
i += 1
j += 1
diag.sort()
i, j = i-1, j-1
while i>=0 and j>=0:
mat[i][j] = diag.pop()
i -= 1
j -= 1
return mat | sort-the-matrix-diagonally | [Python3] In-Place Sorting | ruosengao | 0 | 7 | sort the matrix diagonally | 1,329 | 0.836 | Medium | 19,903 |
https://leetcode.com/problems/sort-the-matrix-diagonally/discuss/2494734/Python-%3A-Priority-queue | class Solution:
def diagonalSort(self, mat: List[List[int]]) -> List[List[int]]:
m, n = len(mat), len(mat[0])
diagonals = defaultdict(list)
for i in range(m):
for j in range(n):
heapq.heappush(diagonals[i - j], mat[i][j])
for i in range(m):
for j in range(n):
mat[i][j] = heapq.heappop(diagonals[i - j])
return mat | sort-the-matrix-diagonally | Python : Priority queue | joshua_mur | 0 | 5 | sort the matrix diagonally | 1,329 | 0.836 | Medium | 19,904 |
https://leetcode.com/problems/sort-the-matrix-diagonally/discuss/2494233/Ezy-heap(Priority-queue)-python3-solution | class Solution:
# O(n*m*log(max(m, n))) time,
# O(n*m) space,
# Approach: heap,
def diagonalSort(self, mat: List[List[int]]) -> List[List[int]]:
n = len(mat)
m = len(mat[0])
diagonals = {}
for i in range(n):
for j in range(m):
diff = i-j
if diff not in diagonals.keys():
diagonals[diff] = []
heapq.heappush(diagonals[diff], mat[i][j])
for i in range(n):
for j in range(m):
diff = i-j
mat[i][j] = heapq.heappop(diagonals[diff])
return mat | sort-the-matrix-diagonally | Ezy heap(Priority queue) python3 solution | destifo | 0 | 3 | sort the matrix diagonally | 1,329 | 0.836 | Medium | 19,905 |
https://leetcode.com/problems/sort-the-matrix-diagonally/discuss/2494134/Python-Easy | class Solution(object):
def diagonalSort(self, mat):
n=len(mat)
m=len(mat[0])
for i in range(n):
j=i
k=0
arr=[]
while j<n and k<m:
arr.append(mat[j][k])
j+=1
k+=1
# print arr
arr.sort()
j=i
k=0
while j<n and k<m:
mat[j][k]=arr[k]
j+=1
k+=1
# print mat
for i in range(m):
j=0
k=i
arr=[]
while j<n and k<m:
arr.append(mat[j][k])
j+=1
k+=1
# print arr
arr.sort()
j=0
k=i
while j<n and k<m:
mat[j][k]=arr[j]
j+=1
k+=1
## return mat | sort-the-matrix-diagonally | Python Easy | singhdiljot2001 | 0 | 12 | sort the matrix diagonally | 1,329 | 0.836 | Medium | 19,906 |
https://leetcode.com/problems/sort-the-matrix-diagonally/discuss/2493806/Python-Solution | class Solution:
def diagonalSort(self, mat: List[List[int]]) -> List[List[int]]:
data = defaultdict(list)
for i in range(len(mat)):
for j in range(len(mat[i])):
data[i - j].append(mat[i][j])
for k in data:
data[k].sort(reverse=True)
for i in range(len(mat)):
for j in range(len(mat[i])):
mat[i][j] = data[i - j].pop()
return mat | sort-the-matrix-diagonally | Python Solution | hgalytoby | 0 | 8 | sort the matrix diagonally | 1,329 | 0.836 | Medium | 19,907 |
https://leetcode.com/problems/sort-the-matrix-diagonally/discuss/2493806/Python-Solution | class Solution:
def diagonalSort(self, mat: List[List[int]]) -> List[List[int]]:
data = defaultdict(list)
for i in range(len(mat)):
for j in range(len(mat[i])):
data[i - j].append(mat[i][j])
for k in data:
for i, num in enumerate(sorted(data[k])):
mat[k + i + max(-k, 0)][i + max(-k, 0)] = num
return mat | sort-the-matrix-diagonally | Python Solution | hgalytoby | 0 | 8 | sort the matrix diagonally | 1,329 | 0.836 | Medium | 19,908 |
https://leetcode.com/problems/sort-the-matrix-diagonally/discuss/2493626/Python-oror-Simple-and-Fast-Approach | class Solution:
def diagonalSort(self, mat: List[List[int]]) -> List[List[int]]:
m = len(mat)
n = len(mat[0])
# for diagonals starting from column 0
j = 0
for i in range(m):
x, y = i, j
hp = []
while x < m and y < n:
hp.append(mat[x][y])
x += 1
y += 1
hp.sort()
x, y = i, j
idx = 0
while x < m and y < n:
mat[x][y] = hp[idx]
x += 1
y += 1
idx += 1
# for diagonals starting from row=0
i = 0
for j in range(1, n):
x, y = i, j
hp = []
while x < m and y < n:
hp.append(mat[x][y])
x += 1
y += 1
hp.sort()
x, y = i, j
idx = 0
while x < m and y < n:
mat[x][y] = hp[idx]
x += 1
y += 1
idx += 1
return mat | sort-the-matrix-diagonally | Python || Simple and Fast Approach | wilspi | 0 | 18 | sort the matrix diagonally | 1,329 | 0.836 | Medium | 19,909 |
https://leetcode.com/problems/sort-the-matrix-diagonally/discuss/2493438/Sort-the-Matrix-Diagonally-Python-Solution | class Solution:
def diagonalSort(self, mat):
m, n, d = len(mat), len(mat[0]), defaultdict(list)
for i in range(m):
for j in range(n):
d[j - i].append(mat[i][j])
for k in d:
for i, num in enumerate(sorted(d[k])):
mat[i + max(-k, 0)][k + i + max(-k, 0)] = num
return mat | sort-the-matrix-diagonally | Sort the Matrix Diagonally [ Python Solution ] | klu_2100031497 | 0 | 15 | sort the matrix diagonally | 1,329 | 0.836 | Medium | 19,910 |
https://leetcode.com/problems/sort-the-matrix-diagonally/discuss/2492700/Python-Intuitive-solution | class Solution:
def diagonalSort(self, mat: List[List[int]]) -> List[List[int]]:
m, n = len(mat), len(mat[0])
for i in range(m):
new_cells = [mat[i+j][j] for j in range(n) if i + j < m]
new_cells.sort()
j = 0
while i + j < m and j < len(new_cells):
mat[i+j][j] = new_cells[j]
j += 1
for j in range(1, n):
new_cells = [mat[i][i+j] for i in range(m) if i + j < n]
new_cells.sort()
i = 0
while i + j < n and i < len(new_cells):
mat[i][i+j] = new_cells[i]
i += 1
return mat | sort-the-matrix-diagonally | Python Intuitive solution | ernstblofeld | 0 | 12 | sort the matrix diagonally | 1,329 | 0.836 | Medium | 19,911 |
https://leetcode.com/problems/sort-the-matrix-diagonally/discuss/2492483/Python-solution | class Solution:
def diagonalSort(self, mat: List[List[int]]) -> List[List[int]]:
rows = len(mat)
cols = len(mat[0])
diagonals = {}
def saveDiagonal(i,j) -> List[int]:
diagonal = []
while i < rows and j < cols:
diagonal.append(mat[i][j])
i+=1
j+=1
diagonal.sort()
return diagonal
def buildDiagonal(i,j,diagonal):
while i < rows and j < cols:
mat[i][j] = diagonal.pop(0)
i+=1
j+=1
for j in range(cols):
i = 0
key = "{}-{}".format(i,j)
diagonals[key] = saveDiagonal(i,j)
for i in range(1,rows):
j = 0
key = "{}-{}".format(i,j)
diagonals[key] = saveDiagonal(i,j)
for diag in diagonals:
i,j = diag.split("-")
i = int(i)
j = int(j)
buildDiagonal(i,j,diagonals[diag])
* return mat | sort-the-matrix-diagonally | Python solution | gurucharandandyala | 0 | 18 | sort the matrix diagonally | 1,329 | 0.836 | Medium | 19,912 |
https://leetcode.com/problems/sort-the-matrix-diagonally/discuss/2492405/Python-one-sort | class Solution:
def diagonalSort(self, mat: List[List[int]]) -> List[List[int]]:
nums = []
for r, row in enumerate(mat):
for c, num in enumerate(row):
nums.append((c-r, num))
nums.sort()
m, n = len(mat), len(mat[0])
r, c = m - 1, 0
for d, num in nums:
if r == m or c == n:
r = max(-d, 0)
c = max(d, 0)
mat[r][c] = num
r += 1
c += 1
return mat | sort-the-matrix-diagonally | Python, one sort | blue_sky5 | 0 | 17 | sort the matrix diagonally | 1,329 | 0.836 | Medium | 19,913 |
https://leetcode.com/problems/sort-the-matrix-diagonally/discuss/2416479/Python-80-Faster | class Solution:
def diagonalSort(self, mat: List[List[int]]) -> List[List[int]]:
temp = []
mapped = defaultdict(list)
for i in range(len(mat)):
for j in range(len(mat[0])):
mapped[i-j].append(mat[i][j])
for key, val in mapped.items():
mapped[key] = sorted(val)
for i in range(len(mat)):
for j in range(len(mat[0])):
mat[i][j] = mapped[i-j][0]
mapped[i-j].pop(0)
return(mat) | sort-the-matrix-diagonally | Python 80% Faster | Abhi_009 | 0 | 45 | sort the matrix diagonally | 1,329 | 0.836 | Medium | 19,914 |
https://leetcode.com/problems/sort-the-matrix-diagonally/discuss/2385143/Python3-or-Modifying-Matrix-in-place! | class Solution:
#T.C = O(n*(2*min(n, m)) + n*min(n, m) + m*(2*min(n, m)) + m*min(n,m)) -> O(n*min(n,m) + m*min(n, m))
#S.C = O(n*min(n,m) + m*min(n, m))
def diagonalSort(self, mat: List[List[int]]) -> List[List[int]]:
#Approach: Basically, have one loop taking care of all top row cells!
#Have another loop taking care of leftmost column cells!
#From each of those cells, record all of the cells along the diagonal spanning from
#each of those cells and append to array! -> Once we go out of bounds, sort the array
#and overwrite each of diagonal cells one by one!
#Return the matrix modified in-place!
m, n = len(mat), len(mat[0])
#top row cells all have row 0!
for a in range(n):
cr, cc = 0, a
diagonal_nums = []
while cr < m and cc < n:
diagonal_nums.append(mat[cr][cc])
#move towards bottom right!
cr += 1
cc += 1
#once we exit while loop, diagonal_nums has all diagonal entries!
diagonal_nums.sort()
cr, cc = 0, a
index = 0
while cr < m and cc < n:
mat[cr][cc] = diagonal_nums[index]
cr += 1
cc += 1
index += 1
#we also have to take care of all leftmost column cells!
#Make sure to exclude top leftmost position on grid since it's already taken care
#of in the previous for loop!
for b in range(1, m, 1):
cr, cc = b, 0
diagonal_nums2 = []
while cr < m and cc < n:
diagonal_nums2.append(mat[cr][cc])
cr += 1
cc += 1
diagonal_nums2.sort()
r2, c2 = b, 0
index2 = 0
while r2 < m and c2 < n:
mat[r2][c2] = diagonal_nums2[index2]
r2 += 1
c2 += 1
index2 += 1
#once we are done with all possible diagonals spanning from topmost row and leftmost
#column cells, our in-place modified matrix has all diagonals in sorted order
#going bottom-right!
return mat | sort-the-matrix-diagonally | Python3 | Modifying Matrix in-place! | JOON1234 | 0 | 24 | sort the matrix diagonally | 1,329 | 0.836 | Medium | 19,915 |
https://leetcode.com/problems/sort-the-matrix-diagonally/discuss/2383834/Python-4-lines | class Solution:
def diagonalSort(self, A: List[List[int]]) -> List[List[int]]:
n, m, d = len(A), len(A[0]), defaultdict(list)
any(d[i - j].append(A[i][j]) for i in range(n) for j in range(m))
any(d[sum_].sort(reverse=1) for sum_ in d)
return [[d[i-j].pop() for j in range(m)] for i in range(n)] | sort-the-matrix-diagonally | Python 4 lines | tq326 | 0 | 36 | sort the matrix diagonally | 1,329 | 0.836 | Medium | 19,916 |
https://leetcode.com/problems/sort-the-matrix-diagonally/discuss/2309275/Python-or-Faster-than-60-or-My-code-is-a-mess | class Solution:
def diagonalSort(self, mat: List[List[int]]) -> List[List[int]]:
rows, columns = len(mat), len(mat[0])
res = []
for i in range(rows - 1, 0, -1):
start = i
curr = 0
c_a = []
while start < rows and curr < columns:
c_a.append(mat[start][curr])
start += 1
curr += 1
res.append(sorted(c_a))
for i in range(columns):
start = 0
curr = i
c_a = []
while start < rows and curr < columns:
c_a.append(mat[start][curr])
start += 1
curr += 1
res.append(sorted(c_a))
out = []
for i in range(len(res)):
j = 0
temp = []
while j < columns and j < len(res):
if res[j] == []:
del res[j]
continue
elem = res[j].pop()
j += 1
temp.append(elem)
if len(temp) > 0:
out.append(temp)
return [i for i in reversed(out)] | sort-the-matrix-diagonally | Python | Faster than 60 | My code is a mess | prameshbajra | 0 | 44 | sort the matrix diagonally | 1,329 | 0.836 | Medium | 19,917 |
https://leetcode.com/problems/sort-the-matrix-diagonally/discuss/2137858/python-88-faster | class Solution:
def diagonalSort(self, mat: List[List[int]]) -> List[List[int]]:
dict = {}
for i,row in enumerate(mat):
for j,val in enumerate(row):
if (i-j) in dict:
dict[i-j].append(val)
else:
dict[i-j] = [val]
for val in dict.values():
val.sort(reverse = True)
for i in range(len(mat)):
for j in range(len(mat[0])):
mat[i][j] = dict[i-j].pop()
return mat | sort-the-matrix-diagonally | python 88% faster | somendrashekhar2199 | 0 | 87 | sort the matrix diagonally | 1,329 | 0.836 | Medium | 19,918 |
https://leetcode.com/problems/sort-the-matrix-diagonally/discuss/2103201/python-3-oror-simple-solution | class Solution:
def diagonalSort(self, mat: List[List[int]]) -> List[List[int]]:
diagonals = collections.defaultdict(list)
for i, row in enumerate(mat):
for j, num in enumerate(row):
diagonals[i - j].append(num)
for diagonal in diagonals.values():
diagonal.sort(reverse=True)
m, n = len(mat), len(mat[0])
for i in range(m):
for j in range(n):
mat[i][j] = diagonals[i - j].pop()
return mat | sort-the-matrix-diagonally | python 3 || simple solution | dereky4 | 0 | 77 | sort the matrix diagonally | 1,329 | 0.836 | Medium | 19,919 |
https://leetcode.com/problems/sort-the-matrix-diagonally/discuss/2086832/Python3-Matrix-to-Sorted-Diagonal-Matrix-back-to-Matrix | class Solution:
def diagonalSort(self, mat: List[List[int]]) -> List[List[int]]:
r, c = len(mat), len(mat[0])
def get_rows(grid):
return [[c for c in r] for r in grid]
def get_cols(grid):
return zip(*grid)
def get_backward_diagonals(grid):
b = [None] * (len(grid) - 1)
grid = [b[i:] + r + b[:i] for i, r in enumerate(get_rows(grid))]
return [sorted(c for c in r if c is not None) for r in get_cols(grid)]
diagonals = get_backward_diagonals(mat)
return [[diag.pop() for diag in diagonals[i:i+c]] for i in range(r)][::-1] | sort-the-matrix-diagonally | Python3 Matrix to Sorted Diagonal Matrix back to Matrix | think989 | 0 | 25 | sort the matrix diagonally | 1,329 | 0.836 | Medium | 19,920 |
https://leetcode.com/problems/sort-the-matrix-diagonally/discuss/1796214/Python-using-only-matrices | class Solution:
def diagonalSort(self, mat: List[List[int]]) -> List[List[int]]:
# def quick_sort(startRow, startCol, mat, endRow, endCol):
def quick_sort(startPos, mat, endPos):
if startPos >= endPos:
return
i = startPos.copy()
j = endPos.copy()
k = 1
while not i == j:
if mat[j[0]][j[1]] < mat[i[0]][i[1]]:
mat[j[0]][j[1]], mat[i[0]][i[1]] = mat[i[0]][i[1]], mat[j[0]][j[1]]
k = -k
if k == 1:
i[0] += 1
i[1] += 1
else:
j[0] -= 1
j[1] -= 1
quick_sort(startPos, mat, [i[0] - 1, i[1] - 1])
quick_sort([i[0] + 1, i[1] + 1], mat, endPos)
for i in range(len(mat)):
# quick_sort(i, 0, mat, len(mat) - 1, len(mat) - i - 1)
quick_sort([i, 0], mat, [min(len(mat) - 1, i - 1+ len(mat[0])), min(len(mat) - i - 1, len(mat[0]) - 1)])
for i in range(1, len(mat[0])):
quick_sort([0, i], mat, [min(len(mat) - 1, len(mat[0]) - 1 - i), min(len(mat[0]) - 1, i - 1 + len(mat))])
return mat | sort-the-matrix-diagonally | Python using only matrices | Swizop | 0 | 130 | sort the matrix diagonally | 1,329 | 0.836 | Medium | 19,921 |
https://leetcode.com/problems/sort-the-matrix-diagonally/discuss/1771991/Faster-than-94 | class Solution:
def diagonalSort(self, mat: List[List[int]]) -> List[List[int]]:
dic = {}
for i in range(len(mat)):
for j in range(len(mat[i])):
if (i-j) not in dic:
dic[i-j] = []
dic[i-j].append(mat[i][j])
for key in dic:
dic[key].sort(reverse=1)
for i in range(len(mat)):
for j in range(len(mat[i])):
mat[i][j] = dic[i-j].pop()
return mat | sort-the-matrix-diagonally | Faster than 94% | blackmishra | 0 | 41 | sort the matrix diagonally | 1,329 | 0.836 | Medium | 19,922 |
https://leetcode.com/problems/sort-the-matrix-diagonally/discuss/1702445/Understandable-code-for-beginners-like-me-in-python-!! | class Solution:
def diagonalSort(self, mat: List[List[int]]) -> List[List[int]]:
def pickDiagonals(row,col,mat,R,C):
diagonal=[]
while(row<R and col<C):
diagonal.append(mat[row][col])
row+=1
col+=1
return diagonal
def arrangeDiagonal(row,col,diagonal,mat,R,C):
while(row<R and col<C):
mat[row][col]=diagonal.pop(0)
row+=1
col+=1
R=len(mat)
C=len(mat[0])
for row in range(R-2,-1,-1):
diagonal=pickDiagonals(row,0,mat,R,C)
diagonal.sort()
arrangeDiagonal(row,0,diagonal,mat,R,C)
for col in range(1,C-1):
diagonal=pickDiagonals(0,col,mat,R,C)
diagonal.sort()
arrangeDiagonal(0,col,diagonal,mat,R,C)
return mat | sort-the-matrix-diagonally | Understandable code for beginners like me in python !! | kabiland | 0 | 115 | sort the matrix diagonally | 1,329 | 0.836 | Medium | 19,923 |
https://leetcode.com/problems/sort-the-matrix-diagonally/discuss/1695396/Concise-ish-Python-solution-using-a-heap | class Solution:
def diagonalSort(self, M: List[List[int]]) -> List[List[int]]:
m, n = len(M), len(M[0])
q = defaultdict(list)
for i in range(m):
for j in range(n):
d = i - j
heapq.heappush(q[d], M[i][j])
for i in range(m):
for j in range(n):
d = i - j
M[i][j] = heapq.heappop(q[d])
return M | sort-the-matrix-diagonally | Concise-ish Python solution using a heap | emwalker | 0 | 59 | sort the matrix diagonally | 1,329 | 0.836 | Medium | 19,924 |
https://leetcode.com/problems/sort-the-matrix-diagonally/discuss/1451560/Python3-Classic-solution | class Solution:
def diagonalSort(self, mat: List[List[int]]) -> List[List[int]]:
d = {}
for i in range(len(mat)):
for j in range(len(mat[i])):
if i - j not in d:
d[i - j] = []
d[i - j].append(mat[i][j])
for key in d:
d[key].sort(reverse=1)
for i in range(len(mat)):
for j in range(len(mat[i])):
mat[i][j] = d[i - j].pop()
return mat | sort-the-matrix-diagonally | [Python3] Classic solution | maosipov11 | 0 | 115 | sort the matrix diagonally | 1,329 | 0.836 | Medium | 19,925 |
https://leetcode.com/problems/sort-the-matrix-diagonally/discuss/1353314/Python-simple-solution-or-Less-space-than-92-Solutions-or-37-faster | class Solution:
def diagonalSort(self, mat: List[List[int]]) -> List[List[int]]:
rows = len(mat)
cols = len(mat[0])
#take all the top and right edges in a list 'starts', these are all points where diagonals start from
starts = [[i,0] for i in range(0,rows)]
starts.extend([[0,i] for i in range(0,cols) if [0,i] not in starts])
#initialise a new matrix where sorted matrix will be stored with zeros
new_mat=[]
for i in range(0,rows):
new_mat.append([0]*cols)
for ele in starts:
ids = [ele]
i=ele[0]
j=ele[1]
vals = [mat[i][j]]
while i<rows-1 and j< cols-1:
i+=1
j+=1
ids.append([i,j])
vals.append(mat[i][j])
sorted_vals = sorted(vals)
for i,idx in enumerate(ids):
new_mat[idx[0]][idx[1]] = sorted_vals[i]
return new_mat | sort-the-matrix-diagonally | Python simple solution | Less space than 92% Solutions | 37% faster | niharikavats97 | 0 | 150 | sort the matrix diagonally | 1,329 | 0.836 | Medium | 19,926 |
https://leetcode.com/problems/sort-the-matrix-diagonally/discuss/1200568/Simple-Python-Sorting-O(n2-logn) | class Solution:
def diagonalSort(self, mat: List[List[int]]) -> List[List[int]]:
rows, cols = len(mat), len(mat[0])
# Diagonals starting from the elements in the first row
for i in range(cols-1, -1, -1):
tempArray = list()
col = i
# Traverse and Store the elements of each diagonal starting from the elements in the first row
for row in range(rows):
if(col>=cols):
break
tempArray.append(mat[row][col])
col += 1
# Sort and store back those elements and we get the sorted elements for this diagonal
tempArray.sort(reverse = True)
col = i
for row in range(rows):
if(col>=cols):
break
mat[row][col] = tempArray.pop()
col += 1
# The same logic follows for all diagonals starting in the first column
# Diagonal starting from 1st column
for i in range(1, rows):
tempArray = list()
row = i
for col in range(cols):
if(row >= rows):
break
tempArray.append(mat[row][col])
row += 1
tempArray.sort(reverse = True)
row = i
for col in range(cols):
if(row >= rows):
break
mat[row][col] = tempArray.pop()
row += 1
return mat | sort-the-matrix-diagonally | Simple Python Sorting O(n^2 logn) | thecoder_elite | 0 | 86 | sort the matrix diagonally | 1,329 | 0.836 | Medium | 19,927 |
https://leetcode.com/problems/sort-the-matrix-diagonally/discuss/1070463/Python-beats-98 | class Solution:
def diagonalSort(self, mat: List[List[int]]) -> List[List[int]]:
diag = {}
m = len(mat)
n = len(mat[0])
for row in range(m):
for col in range(n):
diag.setdefault(col-row, [])
diag[col-row].append(mat[row][col])
for key, val in diag.items():
diag[key] = sorted(val)
for row in range(m):
for col in range(n):
mat[row][col] = diag[col-row].pop(0)
return mat | sort-the-matrix-diagonally | Python beats 98% | IKM98 | 0 | 147 | sort the matrix diagonally | 1,329 | 0.836 | Medium | 19,928 |
https://leetcode.com/problems/reverse-subarray-to-maximize-array-value/discuss/489882/O(n)-Solution-with-explanation | class Solution:
def maxValueAfterReverse(self, nums: List[int]) -> int:
maxi, mini = -math.inf, math.inf
for a, b in zip(nums, nums[1:]):
maxi = max(min(a, b), maxi)
mini = min(max(a, b), mini)
change = max(0, (maxi - mini) * 2)
# solving the boundary situation
for a, b in zip(nums, nums[1:]):
tmp1 = - abs(a - b) + abs(nums[0] - b)
tmp2 = - abs(a - b) + abs(nums[-1] - a)
change = max([tmp1, tmp2, change])
original_value = sum(abs(a - b) for a, b in zip(nums, nums[1:]))
return original_value + change | reverse-subarray-to-maximize-array-value | O(n) Solution with explanation | neal99 | 325 | 7,300 | reverse subarray to maximize array value | 1,330 | 0.401 | Hard | 19,929 |
https://leetcode.com/problems/rank-transform-of-an-array/discuss/2421511/Python-Elegant-and-Short-or-Two-lines-or-HashMap-%2B-Sorting | class Solution:
"""
Time: O(n*log(n))
Memory: O(n)
"""
def arrayRankTransform(self, arr: List[int]) -> List[int]:
ranks = {num: r for r, num in enumerate(sorted(set(arr)), start=1)}
return [ranks[num] for num in arr] | rank-transform-of-an-array | Python Elegant & Short | Two lines | HashMap + Sorting | Kyrylo-Ktl | 2 | 220 | rank transform of an array | 1,331 | 0.591 | Easy | 19,930 |
https://leetcode.com/problems/rank-transform-of-an-array/discuss/1931825/Python-Solutions-%2B-One-Liner-or-Set-Sorted-Enumerate-or-Simple-and-Clean | class Solution:
def arrayRankTransform(self, arr):
ranks = {}
for rank, num in enumerate(sorted(set(arr))):
ranks[num] = rank+1
return [ranks[num] for num in arr] | rank-transform-of-an-array | Python - Solutions + One Liner | Set, Sorted, Enumerate | Simple and Clean | domthedeveloper | 2 | 223 | rank transform of an array | 1,331 | 0.591 | Easy | 19,931 |
https://leetcode.com/problems/rank-transform-of-an-array/discuss/1931825/Python-Solutions-%2B-One-Liner-or-Set-Sorted-Enumerate-or-Simple-and-Clean | class Solution:
def arrayRankTransform(self, arr):
ranks = {num:rank+1 for rank, num in enumerate(sorted(set(arr)))}
return [ranks[num] for num in arr] | rank-transform-of-an-array | Python - Solutions + One Liner | Set, Sorted, Enumerate | Simple and Clean | domthedeveloper | 2 | 223 | rank transform of an array | 1,331 | 0.591 | Easy | 19,932 |
https://leetcode.com/problems/rank-transform-of-an-array/discuss/1931825/Python-Solutions-%2B-One-Liner-or-Set-Sorted-Enumerate-or-Simple-and-Clean | class Solution:
def arrayRankTransform(self, arr):
return map({n:r+1 for r,n in enumerate(sorted(set(arr)))}.get, arr) | rank-transform-of-an-array | Python - Solutions + One Liner | Set, Sorted, Enumerate | Simple and Clean | domthedeveloper | 2 | 223 | rank transform of an array | 1,331 | 0.591 | Easy | 19,933 |
https://leetcode.com/problems/rank-transform-of-an-array/discuss/2823902/Easy-Python-Solutionor-Beats-95-Run-Time | class Solution:
def arrayRankTransform(self, arr: List[int]) -> List[int]:
rank = {}
cnt = 1
for i in sorted(list(set(arr))):
rank[i] = cnt
cnt += 1
#print(rank)
return [rank[i] for i in arr] | rank-transform-of-an-array | Easy Python Solution| Beats 95% Run Time | Lalithkiran | 1 | 34 | rank transform of an array | 1,331 | 0.591 | Easy | 19,934 |
https://leetcode.com/problems/rank-transform-of-an-array/discuss/2287552/Python-Easy-Solution | class Solution:
def arrayRankTransform(self, arr: List[int]) -> List[int]:
arrx = [i for i in set(arr)]
arrx.sort()
hp={}
for i in range(len(arrx)):
if arrx[i] in hp:
continue
else:
hp[arrx[i]] = i+1
print(hp)
for j in range(len(arr)):
arr[j] = hp[arr[j]]
return arr | rank-transform-of-an-array | Python Easy Solution | h2k4082k | 1 | 90 | rank transform of an array | 1,331 | 0.591 | Easy | 19,935 |
https://leetcode.com/problems/rank-transform-of-an-array/discuss/1905432/Python-easy-solution-for-beginners | class Solution:
def arrayRankTransform(self, arr: List[int]) -> List[int]:
ind = [x+1 for x in range(len(arr))]
ranks = dict(zip(sorted(set(arr)), ind))
res = []
for i in arr:
res.append(ranks[i])
return res | rank-transform-of-an-array | Python easy solution for beginners | alishak1999 | 1 | 158 | rank transform of an array | 1,331 | 0.591 | Easy | 19,936 |
https://leetcode.com/problems/rank-transform-of-an-array/discuss/885943/Python%3A-Binary-Search-Solution-using-bisect | class Solution:
def arrayRankTransform(self, arr: List[int]) -> List[int]:
temp = sorted(set(arr))
op = []
for n in arr:
idx = bisect_left(temp, n)
op.append(idx + 1)
return op | rank-transform-of-an-array | Python: Binary Search Solution using bisect | cppygod | 1 | 237 | rank transform of an array | 1,331 | 0.591 | Easy | 19,937 |
https://leetcode.com/problems/rank-transform-of-an-array/discuss/2837994/1331.-Rank-Transform-of-an-Array-or-using-pythonor-beats-95 | class Solution:
def arrayRankTransform(self, arr: List[int]) -> List[int]:
rank = {}
cnt = 1
for i in sorted(list(set(arr))):
rank[i] = cnt
cnt += 1
return [rank[i] for i in arr] | rank-transform-of-an-array | 1331. Rank Transform of an Array | using python| beats 95% | Lalithkiran | 0 | 4 | rank transform of an array | 1,331 | 0.591 | Easy | 19,938 |
https://leetcode.com/problems/rank-transform-of-an-array/discuss/2812400/Super-Easy-Python-or-O(nlogn)-or-Beats-97.96-submissions | class Solution:
def arrayRankTransform(self, arr: List[int]) -> List[int]:
store = {}
sort_arr = sorted(set(arr))
for i in range(len(sort_arr)):
store[sort_arr[i]] = i+1
for i in range(len(arr)):
arr[i] = store[arr[i]]
return arr | rank-transform-of-an-array | Super Easy Python | O(nlogn) | Beats 97.96% submissions | 10samarth | 0 | 54 | rank transform of an array | 1,331 | 0.591 | Easy | 19,939 |
https://leetcode.com/problems/rank-transform-of-an-array/discuss/2808185/Python-or-nlogn | class Solution:
def arrayRankTransform(self, arr: List[int]) -> List[int]:
elems = sorted(list(set(arr)))
m = {elem:i+1 for i,elem in enumerate(elems)}
return [m[n] for n in arr] | rank-transform-of-an-array | Python | nlogn | yllera | 0 | 1 | rank transform of an array | 1,331 | 0.591 | Easy | 19,940 |
https://leetcode.com/problems/rank-transform-of-an-array/discuss/2622721/Easy-Python-solution-for-beginners-faster-than-98 | class Solution:
def arrayRankTransform(self, arr: List[int]) -> List[int]:
helper=sorted(set(arr))
d=defaultdict(int)
for i in range(len(helper)):
d[helper[i]]=i+1
return [d[i] for i in arr] | rank-transform-of-an-array | Easy Python solution for beginners faster than 98% | guneet100 | 0 | 20 | rank transform of an array | 1,331 | 0.591 | Easy | 19,941 |
https://leetcode.com/problems/rank-transform-of-an-array/discuss/2418544/Using-dictionary-and-sorting-in-Python | class Solution:
def arrayRankTransform(self, arr: List[int]) -> List[int]:
nums = arr.copy()
nums.sort()
rank_dict = {}
j = 1
for i in nums:
if i not in rank_dict:
rank_dict[i] = j
j += 1
return [rank_dict[j] for j in arr] | rank-transform-of-an-array | Using dictionary and sorting in Python | ankurbhambri | 0 | 56 | rank transform of an array | 1,331 | 0.591 | Easy | 19,942 |
https://leetcode.com/problems/rank-transform-of-an-array/discuss/2329131/Modular-python3-solution | class Solution:
def arrayRankTransform(self, arr: List[int]) -> List[int]:
copy, hashmap, count = arr.copy(), dict(), 0
copy.sort()
for n in copy:
if n not in hashmap:
hashmap[n] = count + 1
count += 1
return [hashmap[i] for i in arr] | rank-transform-of-an-array | Modular python3 solution | byusuf | 0 | 46 | rank transform of an array | 1,331 | 0.591 | Easy | 19,943 |
https://leetcode.com/problems/rank-transform-of-an-array/discuss/2253230/Python3-or-Per-the-2-hints-given-by-LeetCode | class Solution:
def arrayRankTransform(self, arr: List[int]) -> List[int]:
tmp = sorted(list(set(arr.copy())))
return [bisect_left(tmp, item) + 1 for item in arr] | rank-transform-of-an-array | Python3 | Per the 2 hints given by LeetCode | Ploypaphat | 0 | 94 | rank transform of an array | 1,331 | 0.591 | Easy | 19,944 |
https://leetcode.com/problems/rank-transform-of-an-array/discuss/1812594/3-Lines-Python-Solution-oror-80-Faster-oror-Memory-less-than-90 | class Solution:
def arrayRankTransform(self, arr: List[int]) -> List[int]:
arr_=sorted(set(arr)) ; index=[i for i in range(1,len(arr_)+1)] ; dct=dict(zip(arr_,index))
for i in range(len(arr)): arr[i]=dct[arr[i]]
return arr | rank-transform-of-an-array | 3-Lines Python Solution || 80% Faster || Memory less than 90% | Taha-C | 0 | 198 | rank transform of an array | 1,331 | 0.591 | Easy | 19,945 |
https://leetcode.com/problems/rank-transform-of-an-array/discuss/1741175/Python-sorted-set-and-dictionary-Beats-88.57 | class Solution:
def arrayRankTransform(self, arr: List[int]) -> List[int]:
temp= sorted(set(arr))
hashmap={}
for i in range(len(temp)):
hashmap[temp[i]] = i+1
for i in range(len(arr)):
arr[i]=hashmap[arr[i]]
return arr | rank-transform-of-an-array | Python sorted set and dictionary - Beats 88.57% | hrishakhade | 0 | 171 | rank transform of an array | 1,331 | 0.591 | Easy | 19,946 |
https://leetcode.com/problems/rank-transform-of-an-array/discuss/1735479/Python-dollarolution-(Faster-than-98.5) | class Solution:
def arrayRankTransform(self, arr: List[int]) -> List[int]:
v = sorted(set(arr))
d, l= {}, []
for i in range(1,len(v)+1):
d[v[i-1]] = i
for i in arr:
l.append(d[i])
return l | rank-transform-of-an-array | Python $olution (Faster than 98.5%) | AakRay | 0 | 145 | rank transform of an array | 1,331 | 0.591 | Easy | 19,947 |
https://leetcode.com/problems/rank-transform-of-an-array/discuss/1406700/Easy-Python-Solution | class Solution:
def arrayRankTransform(self, arr: List[int]) -> List[int]:
res =[]
dic={}
arr1=sorted(set(arr))
for i in range(len(arr1)):
if arr1[i] not in dic:
dic[arr1[i]]=i+1
for i in range(len(arr)):
res.append(dic.get(arr[i]))
return res | rank-transform-of-an-array | Easy Python Solution | sangam92 | 0 | 144 | rank transform of an array | 1,331 | 0.591 | Easy | 19,948 |
https://leetcode.com/problems/rank-transform-of-an-array/discuss/1319396/Python-3-faster-than-80.65 | class Solution:
def arrayRankTransform(self, arr: List[int]) -> List[int]:
hashset = set()
for int in arr:
hashset.add(int)
hashset = sorted(hashset)
rank = dict()
for i in range(len(hashset)):
rank[hashset[i]] = i + 1
result = []
for int in arr:
result.append(rank[int])
return result | rank-transform-of-an-array | Python 3 - faster than 80.65% | CC_CheeseCake | 0 | 128 | rank transform of an array | 1,331 | 0.591 | Easy | 19,949 |
https://leetcode.com/problems/rank-transform-of-an-array/discuss/1227775/Functional-Python-3-Solution-One-Liner-(set-sorted-zip-count-map) | class Solution:
def arrayRankTransform(self, arr: List[int]) -> List[int]:
unique_items_sorted = sorted(set(arr)) # O(n + n log n) => O(n log n)
dict_sorted = dict(zip(unique_items_sorted, count(1))) # O(n)
return map(dict_sorted.get, arr) # O(n)
# TOTAL => O(n log n)
# ONE-LINER:
# return map(dict(zip(sorted(set(arr)), count(1))).get, arr) | rank-transform-of-an-array | Functional Python 3 Solution; One-Liner (set, sorted, zip, count, map) | janniks | 0 | 208 | rank transform of an array | 1,331 | 0.591 | Easy | 19,950 |
https://leetcode.com/problems/rank-transform-of-an-array/discuss/1112548/Python3-simple-solution-using-dictionary | class Solution:
def arrayRankTransform(self, A: List[int]) -> List[int]:
d = {j: i+1 for i,j in enumerate(sorted(set(A)))}
return map(d.get, A) | rank-transform-of-an-array | Python3 simple solution using dictionary | EklavyaJoshi | 0 | 98 | rank transform of an array | 1,331 | 0.591 | Easy | 19,951 |
https://leetcode.com/problems/rank-transform-of-an-array/discuss/492985/Python3-Mapping-number-to-rank | class Solution:
def arrayRankTransform(self, arr: List[int]) -> List[int]:
rank = {x:i+1 for i, x in enumerate(sorted(set(arr)))}
return map(rank.get, arr) | rank-transform-of-an-array | [Python3] Mapping number to rank | ye15 | 0 | 41 | rank transform of an array | 1,331 | 0.591 | Easy | 19,952 |
https://leetcode.com/problems/rank-transform-of-an-array/discuss/492985/Python3-Mapping-number-to-rank | class Solution:
def arrayRankTransform(self, arr: List[int]) -> List[int]:
rank = {x:len(arr)-i for i, x in enumerate(sorted(arr, reverse=True))}
return map(rank.get, arr) | rank-transform-of-an-array | [Python3] Mapping number to rank | ye15 | 0 | 41 | rank transform of an array | 1,331 | 0.591 | Easy | 19,953 |
https://leetcode.com/problems/remove-palindromic-subsequences/discuss/2124192/Python-oror-2-Easy-oror-One-liner | class Solution:
def removePalindromeSub(self, s: str) -> int:
return 1 if s == s[::-1] else 2 | remove-palindromic-subsequences | ✅ Python || 2 Easy || One liner | constantine786 | 45 | 3,500 | remove palindromic subsequences | 1,332 | 0.761 | Easy | 19,954 |
https://leetcode.com/problems/remove-palindromic-subsequences/discuss/2124192/Python-oror-2-Easy-oror-One-liner | class Solution:
def removePalindromeSub(self, s: str) -> int:
return int(s==s[::-1]) or 2 | remove-palindromic-subsequences | ✅ Python || 2 Easy || One liner | constantine786 | 45 | 3,500 | remove palindromic subsequences | 1,332 | 0.761 | Easy | 19,955 |
https://leetcode.com/problems/remove-palindromic-subsequences/discuss/2124192/Python-oror-2-Easy-oror-One-liner | class Solution:
def removePalindromeSub(self, s: str) -> int:
def zip_iter():
i,j,n=0,len(s)-1,len(s)//2
while i<=n:
yield (s[i], s[j])
i+=1
j-=1
return 1 if all(x==y for x,y in zip_iter()) else 2 | remove-palindromic-subsequences | ✅ Python || 2 Easy || One liner | constantine786 | 45 | 3,500 | remove palindromic subsequences | 1,332 | 0.761 | Easy | 19,956 |
https://leetcode.com/problems/remove-palindromic-subsequences/discuss/2124192/Python-oror-2-Easy-oror-One-liner | class Solution:
def removePalindromeSub(self, s: str) -> int:
return 2 - all(s[i] == s[~i] for i in range(len(s) // 2)) | remove-palindromic-subsequences | ✅ Python || 2 Easy || One liner | constantine786 | 45 | 3,500 | remove palindromic subsequences | 1,332 | 0.761 | Easy | 19,957 |
https://leetcode.com/problems/remove-palindromic-subsequences/discuss/490902/Python3-sneaky-definition-of-%22subsequence%22 | class Solution:
def removePalindromeSub(self, s: str) -> int:
if not s: return 0 #empty string
if s == s[::-1]: return 1 #palindrome
return 2 #general | remove-palindromic-subsequences | [Python3] sneaky definition of "subsequence" | ye15 | 24 | 1,600 | remove palindromic subsequences | 1,332 | 0.761 | Easy | 19,958 |
https://leetcode.com/problems/remove-palindromic-subsequences/discuss/490317/Python-3-(one-line)-(beats-100) | class Solution:
def removePalindromeSub(self, S: str) -> int:
L = len(S)
if L == 0: return 0
if S == S[::-1]: return 1
else return 2 | remove-palindromic-subsequences | Python 3 (one line) (beats 100%) | junaidmansuri | 7 | 1,100 | remove palindromic subsequences | 1,332 | 0.761 | Easy | 19,959 |
https://leetcode.com/problems/remove-palindromic-subsequences/discuss/490317/Python-3-(one-line)-(beats-100) | class Solution:
def removePalindromeSub(self, S: str) -> int:
return 0 if len(S) == 0 else 1 if S == S[::-1] else 2
- Junaid Mansuri
- Chicago, IL | remove-palindromic-subsequences | Python 3 (one line) (beats 100%) | junaidmansuri | 7 | 1,100 | remove palindromic subsequences | 1,332 | 0.761 | Easy | 19,960 |
https://leetcode.com/problems/remove-palindromic-subsequences/discuss/1099569/Python.-ONE-LINER-amazing-and-easy-solution.-faster-than-98.82 | class Solution:
def removePalindromeSub(self, s: str) -> int:
return 0 if s == "" else 1 if s == s[::-1] else 2 | remove-palindromic-subsequences | Python. ONE-LINER amazing & easy solution. faster than 98.82% | m-d-f | 4 | 328 | remove palindromic subsequences | 1,332 | 0.761 | Easy | 19,961 |
https://leetcode.com/problems/remove-palindromic-subsequences/discuss/1099886/Python3-Remove-Palindromic-Subseqncs-beats-93.92-of-python3-submissions. | class Solution:
def removePalindromeSub(self, s: str) -> int:
if len(s) == 0:
return 0
if s == s[::-1]:
return 1
if "a" not in s or "b" not in s:
return 1
return 2 | remove-palindromic-subsequences | [Python3] Remove Palindromic Subseqncs - beats 93.92 % of python3 submissions. | avEraGeC0der | 3 | 160 | remove palindromic subsequences | 1,332 | 0.761 | Easy | 19,962 |
https://leetcode.com/problems/remove-palindromic-subsequences/discuss/1798122/Python-3-solution-or-99-faster | class Solution:
def removePalindromeSub(self, s: str) -> int:
if s == s[::-1]:
return 1
return 2 | remove-palindromic-subsequences | ✔Python 3 solution | 99% faster | Coding_Tan3 | 2 | 103 | remove palindromic subsequences | 1,332 | 0.761 | Easy | 19,963 |
https://leetcode.com/problems/remove-palindromic-subsequences/discuss/2124869/Python-solution-beats-100-or-two-pointer | class Solution:
def removePalindromeSub(self, s: str) -> int:
i, j = 0, len(s) - 1
while i <= j:
if s[i] != s[j]:
return 2
i += 1
j -= 1
return 1 | remove-palindromic-subsequences | Python solution beats 100% | two pointer | b44hrt | 1 | 126 | remove palindromic subsequences | 1,332 | 0.761 | Easy | 19,964 |
https://leetcode.com/problems/remove-palindromic-subsequences/discuss/2124578/python3-or-easy-to-understand-or-binary-string | class Solution:
def removePalindromeSub(self, s: str) -> int:
if s=='':
return 0
s = list(s)
if self.is_palindrome(s):
return 1
return 2
def is_palindrome(self, s):
l, h = 0, len(s)-1
while l<h:
if s[l] != s[h]:
return False
l+=1
h-=1
return True | remove-palindromic-subsequences | python3 | easy to understand | binary string | H-R-S | 1 | 30 | remove palindromic subsequences | 1,332 | 0.761 | Easy | 19,965 |
https://leetcode.com/problems/remove-palindromic-subsequences/discuss/2072515/Python-or-Two-easy-solution | class Solution:
def removePalindromeSub(self, s: str) -> int:
'''
Since the string contains only two types of char i.e 'a' and 'b. So there are only two
scenerios, either the string is a palindrome (return 1), \
if it isn't a palindrome (check if start and ending chars are different),
the min operations to delete will be at most 2.
'''
# /////// Solution 1 //////////
# ///// TC O(N) /////
if len(s) == 1 or s == s[::-1]:
return 1
l,r = 0,len(s) - 1
while l < r:
if s[l] != s[r]:
return 2 # in worst case we need to delete 2 char
else:
l += 1
r -= 1
return 1
# ///// Solution 2 ///////
if s == s[::-1]:
return 1
return 2 | remove-palindromic-subsequences | Python | Two easy solution | __Asrar | 1 | 84 | remove palindromic subsequences | 1,332 | 0.761 | Easy | 19,966 |
https://leetcode.com/problems/remove-palindromic-subsequences/discuss/1128384/Simple-Python-Solution-or-Faster-than-98 | class Solution:
def removePalindromeSub(self, s: str) -> int:
if s == s[::-1]:
return 1
return 2 | remove-palindromic-subsequences | Simple Python Solution | Faster than 98% | Annushams | 1 | 302 | remove palindromic subsequences | 1,332 | 0.761 | Easy | 19,967 |
https://leetcode.com/problems/remove-palindromic-subsequences/discuss/490306/Python3-simple-solution | class Solution:
def removePalindromeSub(self, s: str) -> int:
if not s: return 0
if self.is_palindrome(s): return 1
return 2
def is_palindrome(self,a):
return a == a[::-1] | remove-palindromic-subsequences | Python3 simple solution | jb07 | 1 | 90 | remove palindromic subsequences | 1,332 | 0.761 | Easy | 19,968 |
https://leetcode.com/problems/remove-palindromic-subsequences/discuss/2833680/Python-solution-97-faster | class Solution:
def removePalindromeSub(self, s: str) -> int:
if s == s[::-1]:
return 1
else:
return 2 | remove-palindromic-subsequences | Python solution, 97% faster | samanehghafouri | 0 | 3 | remove palindromic subsequences | 1,332 | 0.761 | Easy | 19,969 |
https://leetcode.com/problems/remove-palindromic-subsequences/discuss/2660136/Python-Easy-Solution | class Solution:
def removePalindromeSub(self, s: str) -> int:
# as string only has two alphabets, it requires only two steps to make it empty if its not a palindrome, you can try on every string you want it.
if s == "":
return 0
elif s == s[::-1]:
return 1
else:
return 2 | remove-palindromic-subsequences | Python Easy Solution | user6770yv | 0 | 5 | remove palindromic subsequences | 1,332 | 0.761 | Easy | 19,970 |
https://leetcode.com/problems/remove-palindromic-subsequences/discuss/2449566/Easiest-Python-Solution-(-Simple-) | class Solution:
def removePalindromeSub(self, s: str) -> int:
if s == s[::-1]: return 1
else: return 2 | remove-palindromic-subsequences | Easiest Python Solution ( Simple ) | SouravSingh49 | 0 | 58 | remove palindromic subsequences | 1,332 | 0.761 | Easy | 19,971 |
https://leetcode.com/problems/remove-palindromic-subsequences/discuss/2127938/Python-or-Commented-or-Time%3A-O(n)-or-Space%3A-O(1) | # Palindrome Check Solution (Only two characters)
# Time: O(n), Compares first half of string to second half.
# Space: O(1), Constant memory space used.
class Solution:
def isPalindromeString(self, s: str) -> False: # Checks if a string is palindromic.
middle = len(s) // 2 # Get the middle index of string.
if len(s) % 2 == 0: return s[:middle] == s[middle:][::-1] # Checks if an even length string is palindromic.
return s[:middle] == s[middle+1:][::-1] # Checks if an odd length string is palindromic.
def removePalindromeSub(self, s: str) -> int: # Returns number of steps to remove all palindromic subsequences.
return 1 if self.isPalindromeString(s) else 2 # Checks if s is a palindrome (if so only one step is needed).
# Otherwise if s is not palindromic, two steps are needed.
# (One step to remove 'a's, another to remove 'b's). | remove-palindromic-subsequences | Python | Commented | Time: O(n) | Space: O(1) | bensmith0 | 0 | 29 | remove palindromic subsequences | 1,332 | 0.761 | Easy | 19,972 |
https://leetcode.com/problems/remove-palindromic-subsequences/discuss/2127263/Python-or-Easy-and-Understanding-or-Two-Pointer-Solution | class Solution:
def isPalindrome(self,s):
beg=0
end=len(s)-1
while(beg<end):
if(s[beg]!=s[end]):
return 0
beg+=1
end-=1
return 1
def removePalindromeSub(self, s: str) -> int:
if(self.isPalindrome(s)):
return 1
return 2 | remove-palindromic-subsequences | Python | Easy & Understanding | Two Pointer Solution | backpropagator | 0 | 43 | remove palindromic subsequences | 1,332 | 0.761 | Easy | 19,973 |
https://leetcode.com/problems/remove-palindromic-subsequences/discuss/2127066/Python3short-and-efecient-solution | class Solution:
def removePalindromeSub(self, s: str) -> int:
if len(s) == 0:
return 0
return 1 if s[::-1] == s else 2 | remove-palindromic-subsequences | [Python3]short and efecient solution | Bezdarnost | 0 | 10 | remove palindromic subsequences | 1,332 | 0.761 | Easy | 19,974 |
https://leetcode.com/problems/remove-palindromic-subsequences/discuss/2126664/If-else-condition-python | class Solution:
def removePalindromeSub(self, s: str) -> int:
temp = s
if(temp==s[::-1]):
return 1
else:
return 2 | remove-palindromic-subsequences | If else condition python | yashkumarjha | 0 | 14 | remove palindromic subsequences | 1,332 | 0.761 | Easy | 19,975 |
https://leetcode.com/problems/remove-palindromic-subsequences/discuss/2126533/Python3-Solution-easily-explained.-Daily-Challenge-080622 | class Solution:
def removePalindromeSub(self, s: str) -> int:
# if s is empty return 0
# else if check if string is palindrome, return 1
# else worst case if string is not a palindrome, then
# return 2, because our string is only consisted of either
# 'a' or 'b' so that means our s(str) is odd as in s there
# is one extra 'a' or one 'b'. So it takes only 2 steps to
# empty our string.
if not s:
return 0
left, right = 0, len(s) - 1
while left < right:
if s[left] != s[right]: # if they don't match, meaning (iii) e.g. return 2
return 2
left += 1
right -= 1
return 1 # if loop executes meaning the s is plindrome, return 1
# toned down version of upper code
if s==s[::-1]:
return 1
return 2 | remove-palindromic-subsequences | Python3 Solution, easily explained. Daily Challenge 08/06/22 | shubhamdraj | 0 | 12 | remove palindromic subsequences | 1,332 | 0.761 | Easy | 19,976 |
https://leetcode.com/problems/remove-palindromic-subsequences/discuss/2126140/Python-Simple-Python-Solution-or-100-Faster | class Solution:
def removePalindromeSub(self, s: str) -> int:
length = len(s)
if length == 0:
return 0
a = s.count('a')
b = s.count('b')
if s == s[::-1] or a == length or b == length:
return 1
else:
return 2 | remove-palindromic-subsequences | [ Python ] ✅✅ Simple Python Solution | 100% Faster 🥳✌👍 | ASHOK_KUMAR_MEGHVANSHI | 0 | 35 | remove palindromic subsequences | 1,332 | 0.761 | Easy | 19,977 |
https://leetcode.com/problems/remove-palindromic-subsequences/discuss/2125538/java-python-itearative-solution | class Solution:
def removePalindromeSub(self, s: str) -> int:
if len(s) == 0 : return 0
i, j = 0, len(s) - 1
while i < j :
if s[i] != s[j] : return 2
i += 1
j -= 1
return 1 | remove-palindromic-subsequences | java, python - itearative solution | ZX007java | 0 | 19 | remove palindromic subsequences | 1,332 | 0.761 | Easy | 19,978 |
https://leetcode.com/problems/remove-palindromic-subsequences/discuss/2125241/Python-or-Two-easy-approaches-with-comments | class Solution:
def removePalindromeSub(self, s: str) -> int:
'''
Since the string contains only two types of char i.e 'a' and 'b. So there are only two
scenerios, either the string is a palindrome (return 1), \
if its not a palindrome (check if start and ending chars are different),
the min operations to delete will be at most 2.
'''
# /////// Solution 1 //////////
# ///// TC O(N) /////
if len(s) == 1 or s == s[::-1]:
return 1
l,r = 0,len(s) - 1
while l < r:
if s[l] != s[r]:
return 2 # in worst case we need to delete 2 char
else:
l += 1
r -= 1
return 1
# ///// Solution 2 ///////
if s == s[::-1]:
return 1
return 2 | remove-palindromic-subsequences | Python | Two easy approaches with comments | __Asrar | 0 | 20 | remove palindromic subsequences | 1,332 | 0.761 | Easy | 19,979 |
https://leetcode.com/problems/remove-palindromic-subsequences/discuss/2124843/Python-Many-easy-solutions-with-complexities | class Solution:
def removePalindromeSub(self, s: str) -> int:
if s == s[::-1]:
return 1
return 2
# time O(N)
# space O(N) | remove-palindromic-subsequences | [Python] Many easy solutions with complexities | mananiac | 0 | 12 | remove palindromic subsequences | 1,332 | 0.761 | Easy | 19,980 |
https://leetcode.com/problems/remove-palindromic-subsequences/discuss/2124843/Python-Many-easy-solutions-with-complexities | class Solution:
def removePalindromeSub(self, s: str) -> int:
s1 = ''.join(reversed(s))
if s == s1:
return 1
return 2
# time O(N)
# space O(N) | remove-palindromic-subsequences | [Python] Many easy solutions with complexities | mananiac | 0 | 12 | remove palindromic subsequences | 1,332 | 0.761 | Easy | 19,981 |
https://leetcode.com/problems/remove-palindromic-subsequences/discuss/2124843/Python-Many-easy-solutions-with-complexities | class Solution:
def removePalindromeSub(self, s: str) -> int:
s1 = ''
for i in s:
s1 = i + s1
if s == s1:
return 1
return 2
# time O(N)
# space O(N) | remove-palindromic-subsequences | [Python] Many easy solutions with complexities | mananiac | 0 | 12 | remove palindromic subsequences | 1,332 | 0.761 | Easy | 19,982 |
https://leetcode.com/problems/remove-palindromic-subsequences/discuss/2124843/Python-Many-easy-solutions-with-complexities | class Solution:
def removePalindromeSub(self, s: str) -> int:
flag = 1
for i in range(len(s)//2):
if s[i] != s[len(s)-i-1]:
flag = 0
break
if flag == 1:
return 1
else:
return 2
# time O(N)
# space O(1) | remove-palindromic-subsequences | [Python] Many easy solutions with complexities | mananiac | 0 | 12 | remove palindromic subsequences | 1,332 | 0.761 | Easy | 19,983 |
https://leetcode.com/problems/remove-palindromic-subsequences/discuss/2124801/Python-easy-solution-for-beginners | class Solution:
def removePalindromeSub(self, s: str) -> int:
if len(s) == 0:
return 0
if s == s[::-1]:
return 1
return 2 | remove-palindromic-subsequences | Python easy solution for beginners | alishak1999 | 0 | 15 | remove palindromic subsequences | 1,332 | 0.761 | Easy | 19,984 |
https://leetcode.com/problems/remove-palindromic-subsequences/discuss/2124555/python-3-oror-one-liner-oror-O(n)O(1) | class Solution:
def removePalindromeSub(self, s: str) -> int:
return 2 - all(s[i] == s[~i] for i in range(len(s) // 2)) | remove-palindromic-subsequences | python 3 || one liner || O(n)/O(1) | dereky4 | 0 | 19 | remove palindromic subsequences | 1,332 | 0.761 | Easy | 19,985 |
https://leetcode.com/problems/remove-palindromic-subsequences/discuss/2124440/Python-Easy-to-understand. | class Solution(object):
def removePalindromeSub(self, s):
"""
:type s: str
:rtype: int
"""
if len(s) == 0:
return 0
if s == s[::-1]:
return 1
else:
return 2 | remove-palindromic-subsequences | Python Easy to understand. | tushar24081 | 0 | 15 | remove palindromic subsequences | 1,332 | 0.761 | Easy | 19,986 |
https://leetcode.com/problems/remove-palindromic-subsequences/discuss/2124404/Python-oror-Two-pointers | class Solution:
def removePalindromeSub(self, s: str) -> int:
start, end = 0, len(s) - 1
while start < end:
if s[start] != s[end]:
return 2
start += 1
end -= 1
return 1
``` | remove-palindromic-subsequences | Python || Two pointers | narasimharaomeda | 0 | 24 | remove palindromic subsequences | 1,332 | 0.761 | Easy | 19,987 |
https://leetcode.com/problems/remove-palindromic-subsequences/discuss/1846918/Easy-One-Line-Python3-Solution-oror-100-Faster-oror-Easy-to-Understand | class Solution:
def removePalindromeSub(self, s: str) -> int:
if s==s[::-1]:
return 1
else:
return 2 | remove-palindromic-subsequences | Easy One-Line Python3 Solution || 100% Faster || Easy to Understand | RatnaPriya | 0 | 106 | remove palindromic subsequences | 1,332 | 0.761 | Easy | 19,988 |
https://leetcode.com/problems/remove-palindromic-subsequences/discuss/1790030/1-Line-Python-Solution | class Solution:
def removePalindromeSub(self, s: str) -> int:
return 1 if s==s[::-1] else 2
""" 2 possibilities in total:
1) s is palindrome --> return 1
2) s is not palindrome --> return 2 (remove all 'a's then all 'b's) """ | remove-palindromic-subsequences | 1-Line Python Solution | Taha-C | 0 | 53 | remove palindromic subsequences | 1,332 | 0.761 | Easy | 19,989 |
https://leetcode.com/problems/remove-palindromic-subsequences/discuss/1099760/python3-solution-with-easy-understanding. | class Solution:
def removePalindromeSub(self, s: str) -> int:
if s=="":
return 0
i=0
j=len(s)-1
while(i<=j):
if s[i]==s[j]:
i+=1
j-=1
else:
break
if i>j:
return 1
else:
return 2 | remove-palindromic-subsequences | python3 solution with easy understanding. | _Rehan12 | 0 | 62 | remove palindromic subsequences | 1,332 | 0.761 | Easy | 19,990 |
https://leetcode.com/problems/remove-palindromic-subsequences/discuss/1099702/Simple-Python-Solution-Using-If-else | class Solution:
def removePalindromeSub(self, s: str) -> int:
n=len(s)
if not n:
return 0
if s[::-1]==s:
return 1
else:
return 2 | remove-palindromic-subsequences | Simple Python Solution Using If else | aishwaryanathanii | 0 | 44 | remove palindromic subsequences | 1,332 | 0.761 | Easy | 19,991 |
https://leetcode.com/problems/filter-restaurants-by-vegan-friendly-price-and-distance/discuss/1464395/Python3-solution | class Solution:
def filterRestaurants(self, restaurants: List[List[int]], veganFriendly: int, maxPrice: int, maxDistance: int) -> List[int]:
def f(x):
if (veganFriendly == 1 and x[2] == 1 and x[3] <= maxPrice and x[4] <= maxDistance) or (veganFriendly == 0 and x[3] <= maxPrice and x[4] <= maxDistance):
return True
else:
return False
y = list(filter(f,restaurants))
y.sort(key=lambda a:a[0],reverse=True)
y.sort(key=lambda a:a[1],reverse=True)
return [i[0] for i in y] | filter-restaurants-by-vegan-friendly-price-and-distance | Python3 solution | EklavyaJoshi | 3 | 242 | filter restaurants by vegan friendly, price and distance | 1,333 | 0.596 | Medium | 19,992 |
https://leetcode.com/problems/filter-restaurants-by-vegan-friendly-price-and-distance/discuss/676662/Python3-filter-then-sort-Filter-Restaurants-by-Vegan-Friendly-Price-and-Distance | class Solution:
def filterRestaurants(self, restaurants: List[List[int]], veganFriendly: int, maxPrice: int, maxDistance: int) -> List[int]:
fn = lambda x: (x[2] >= veganFriendly and x[3] <= maxPrice and x[4] <= maxDistance)
return [x[0] for x in sorted(filter(fn, restaurants), key=lambda x:(-x[1], -x[0]))] | filter-restaurants-by-vegan-friendly-price-and-distance | Python3 filter then sort - Filter Restaurants by Vegan-Friendly, Price and Distance | r0bertz | 3 | 359 | filter restaurants by vegan friendly, price and distance | 1,333 | 0.596 | Medium | 19,993 |
https://leetcode.com/problems/filter-restaurants-by-vegan-friendly-price-and-distance/discuss/2780529/python-sorting-direct-easy-efficient-solution | class Solution(object):
def filterRestaurants(self, restaurants, veganFriendly, maxPrice, maxDistance):
arr = []
for i in restaurants:
if i[3] <= maxPrice and i[4] <= maxDistance:
if veganFriendly and i[2] == 0:
continue
arr.append(i)
arr.sort(key = lambda x : (-x[1] , -x[0]))
ans = [i[0] for i in arr]
return ans | filter-restaurants-by-vegan-friendly-price-and-distance | python sorting direct easy efficient solution | akashp2001 | 0 | 13 | filter restaurants by vegan friendly, price and distance | 1,333 | 0.596 | Medium | 19,994 |
https://leetcode.com/problems/filter-restaurants-by-vegan-friendly-price-and-distance/discuss/2447051/Simple-Readable-Python-Solution | class Solution:
def filterRestaurants(self, restaurants: List[List[int]], veganFriendly: int, maxPrice: int, maxDistance: int) -> List[int]:
a=[]
for i in restaurants:
if i[2]>=veganFriendly and i[3]<=maxPrice and i[4]<=maxDistance:
a.append((i[1], i[0]))
a = sorted(a, reverse=True)
return [i[1] for i in a]
#Do Upcote if you like it :3 | filter-restaurants-by-vegan-friendly-price-and-distance | Simple Readable Python Solution | sambitpuitandi26 | 0 | 19 | filter restaurants by vegan friendly, price and distance | 1,333 | 0.596 | Medium | 19,995 |
https://leetcode.com/problems/filter-restaurants-by-vegan-friendly-price-and-distance/discuss/770290/Quick-and-Easy-Python-Solution | class Solution:
def filterRestaurants(self, restaurants: List[List[int]], veganFriendly: int, maxPrice: int, maxDistance: int) -> List[int]:
def filter_restaurant(entry: list):
return (veganFriendly == entry[2] or not veganFriendly) and maxPrice >= entry[3] and maxDistance >= entry[4]
def sort_key(entry: list):
return entry[1] * 10**5 + entry[0]
matches = sorted([x for x in restaurants if filter_restaurant(x)], key=sort_key, reverse=True)
return [x[0] for x in matches] | filter-restaurants-by-vegan-friendly-price-and-distance | Quick & Easy Python Solution | corbittbryce | 0 | 64 | filter restaurants by vegan friendly, price and distance | 1,333 | 0.596 | Medium | 19,996 |
https://leetcode.com/problems/filter-restaurants-by-vegan-friendly-price-and-distance/discuss/490981/Python%3A-3-lines-Easy-and-Fast | class Solution:
def filterRestaurants(self, restaurants: List[List[int]], veganFriendly: int, maxPrice: int, maxDistance: int) -> List[int]:
filtered = [(r, i) for i, r, v, p, d in restaurants if
(not veganFriendly or v) and p <= maxPrice and d <= maxDistance]
filtered.sort(reverse=True)
return [i for r, i in filtered] | filter-restaurants-by-vegan-friendly-price-and-distance | Python: 3 lines, Easy and Fast | andnik | 0 | 68 | filter restaurants by vegan friendly, price and distance | 1,333 | 0.596 | Medium | 19,997 |
https://leetcode.com/problems/filter-restaurants-by-vegan-friendly-price-and-distance/discuss/490925/Python3-filter-and-sort | class Solution:
def filterRestaurants(self, restaurants: List[List[int]], veganFriendly: int, maxPrice: int, maxDistance: int) -> List[int]:
ans = [(r, i) for i, r, vf, p, d in restaurants if d <= maxDistance and p <= maxPrice and vf >= veganFriendly]
return [x for _, x in sorted(ans, reverse=True)] | filter-restaurants-by-vegan-friendly-price-and-distance | [Python3] filter & sort | ye15 | 0 | 36 | filter restaurants by vegan friendly, price and distance | 1,333 | 0.596 | Medium | 19,998 |
https://leetcode.com/problems/filter-restaurants-by-vegan-friendly-price-and-distance/discuss/490338/Python-3-(two-lines)-(beats-100) | class Solution:
def filterRestaurants(self, R: List[List[int]], V: int, P: int, D: int) -> List[int]:
R = [[r[1],r[0]] for r in R if r[2] >= V and r[3] <= P and r[4] <= D]
return list(zip(*sorted(R, reverse = True)))[1] if R else []
- Junaid Mansuri
- Chicago, IL | filter-restaurants-by-vegan-friendly-price-and-distance | Python 3 (two lines) (beats 100%) | junaidmansuri | 0 | 116 | filter restaurants by vegan friendly, price and distance | 1,333 | 0.596 | Medium | 19,999 |
Subsets and Splits
Top 2 Solutions by Upvotes
Identifies the top 2 highest upvoted Python solutions for each problem, providing insight into popular approaches.