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/toeplitz-matrix/discuss/2763470/Python!-As-short-as-it-gets!
class Solution: def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool: diag = defaultdict(lambda: None) for x in range(len(matrix)): for y in range(len(matrix[x])): if diag[y - x] is None: diag[y - x] = matrix[x][y] elif diag[y - x] != matrix[x][y]: return False return True
toeplitz-matrix
😎Python! As short as it gets!
aminjun
0
4
toeplitz matrix
766
0.688
Easy
12,500
https://leetcode.com/problems/toeplitz-matrix/discuss/2763262/Python-Solution
class Solution: def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool: rows = len(matrix) cols = len(matrix[0]) for r in range(1, rows): for c in range(1, cols): if matrix[r][c] != matrix[r - 1][c - 1]: return False return True
toeplitz-matrix
Python Solution
mansoorafzal
0
3
toeplitz matrix
766
0.688
Easy
12,501
https://leetcode.com/problems/toeplitz-matrix/discuss/2762914/Python-oror-C%2B%2B-oror-Easily-Understood-oror-Fast-oror-Simple
class Solution: def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool: n = len(matrix)-1 m = len(matrix[0])-1 for i in range(n): for j in range(m): if matrix[i][j] != matrix[i+1][j+1]: return False return True
toeplitz-matrix
✅ Python || C++ || Easily Understood || Fast || Simple 🔥
Marie-99
0
9
toeplitz matrix
766
0.688
Easy
12,502
https://leetcode.com/problems/toeplitz-matrix/discuss/2762878/Superfast-easy-and-mem-efficient-or-Explained-or-Python3
class Solution: def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool: for r in range(len(matrix)): for c in range(len(matrix[0])): i,j=r,c while i+1<len(matrix) and j+1<len(matrix[0]): # go through the diagonal from current element i+=1 # if yes, move to the next element j+=1 if matrix[i][j] != matrix[r][c]: return False # if the next element is not equal to the current element, return False return True
toeplitz-matrix
✅ Superfast, easy and mem-efficient | Explained | Python3
arnavjaiswal149
0
3
toeplitz matrix
766
0.688
Easy
12,503
https://leetcode.com/problems/toeplitz-matrix/discuss/2762772/Simple-Python-Solution-or-Easy-to-understand
class Solution: def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool: r, c = len(matrix), len(matrix[0]) for i in range(r): for j in range(c): if 0<=i+1<r and 0<=j+1<c: if matrix[i+1][j+1] != matrix[i][j]: return False return True
toeplitz-matrix
Simple Python Solution | Easy to understand
shreyans
0
6
toeplitz matrix
766
0.688
Easy
12,504
https://leetcode.com/problems/toeplitz-matrix/discuss/2762688/Python-solution-(double-loops)-less-memory-than-98.45
class Solution: def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool: for i in range(1,len(matrix)): for j in range(1,len(matrix[0])): if matrix[i][j] != matrix[i-1][j-1]: return False return True
toeplitz-matrix
Python solution (double loops) less memory than 98.45%
anandanshul001
0
4
toeplitz matrix
766
0.688
Easy
12,505
https://leetcode.com/problems/toeplitz-matrix/discuss/2762674/Easy-Python-Solution-with-Comments-or-Faster-than-93-Solutions-or-Like-if-you-find-it-beneficial-or
class Solution: def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool: #let initial status be True status = True #iterating through the matrix leaving the last elements and last row #top rightmost and bottom leftmost element will always satisfy the solution #rest all the elements unexplored by loop had been already explored by their diagonal elements for i in range(len(matrix)-1): for j in range(len(matrix[0])-1): #set status to False if the diagonal element is not equal if matrix[i][j]==matrix[i+1][j+1]: continue else: status = False break #check if status is false to break out of the loop and prevent any further proceedings if status == False: break #return the status whether it is Toeplitz Matrix or not return status
toeplitz-matrix
Easy Python Solution with Comments | Faster than 93% Solutions | Like if you find it beneficial |
Yash_A
0
7
toeplitz matrix
766
0.688
Easy
12,506
https://leetcode.com/problems/toeplitz-matrix/discuss/2762659/Python-Simple-Python-Solution
class Solution: def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool: rows = len(matrix) cols = len(matrix[0]) all_diagonals = [] for row in range(rows): r,c = row,0 array = [] while r < rows and c < cols: array.append(matrix[r][c]) r = r + 1 c = c + 1 all_diagonals.append(array) for col in range(1, cols): r,c = 0,col array = [] while r < rows and c < cols: array.append(matrix[r][c]) r = r + 1 c = c + 1 all_diagonals.append(array) for diagonal in all_diagonals: if len(diagonal) != diagonal.count(diagonal[0]): return False return True
toeplitz-matrix
[ Python ] ✅✅ Simple Python Solution 🥳✌👍
ASHOK_KUMAR_MEGHVANSHI
0
8
toeplitz matrix
766
0.688
Easy
12,507
https://leetcode.com/problems/toeplitz-matrix/discuss/2762601/Python-Soln-using-Dictionary-ofSet
class Solution: def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool: diagSet = {} #diagonal:set() for i in range(len(matrix)): for j in range(len(matrix[0])): diagSet[i-j] = set() for i in range(len(matrix)): for j in range(len(matrix[0])): diagSet[i-j].add(matrix[i][j]) for val in diagSet.values(): if len(val) > 1: return False
toeplitz-matrix
Python Soln - using Dictionary ofSet
logeshsrinivasans
0
5
toeplitz matrix
766
0.688
Easy
12,508
https://leetcode.com/problems/toeplitz-matrix/discuss/2762566/Python-easy
class Solution: def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool: def helper(i,j,ele,matrix): if(j >= len(matrix[0]) or i >= len(matrix)): return True return (matrix[i][j]==ele and helper(i+1,j+1,ele,matrix)) for i in range(len(matrix)): if(not(helper(i,0,matrix[i][0],matrix))): return False for i in range(len(matrix[0])): if(not(helper(0,i,matrix[0][i],matrix))): return False return True
toeplitz-matrix
Python easy
Pradyumankannan
0
3
toeplitz matrix
766
0.688
Easy
12,509
https://leetcode.com/problems/toeplitz-matrix/discuss/2762510/Python3-or-Row-by-Row-check
class Solution: def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool: m, n = len(matrix), len(matrix[0]) for i in range(1, m): for j in range(1, n): if matrix[i][j] != matrix[i - 1][j - 1]: return False return True
toeplitz-matrix
Python3 | Row by Row check
joshua_mur
0
9
toeplitz matrix
766
0.688
Easy
12,510
https://leetcode.com/problems/toeplitz-matrix/discuss/2762445/Simple-Python-solution-in-one-loop.
class Solution: def isToeplitzMatrix(self, matrix: list[list[int]]) -> bool: height=len(matrix) # 3 width=len(matrix[0]) # 4 result=True for i in range(1,height): if matrix[i-1][:width-1] != matrix[i][1:width]: result=False return result
toeplitz-matrix
Simple Python solution in one loop.
hbr199320xy
0
3
toeplitz matrix
766
0.688
Easy
12,511
https://leetcode.com/problems/toeplitz-matrix/discuss/2762236/Python-oror-Easy-oror-Beginners-solution
class Solution: def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool: for i in range(len(matrix) - 1): for j in range(len(matrix[0]) - 1): if matrix[i][j] != matrix[i + 1][j + 1]: return False return True
toeplitz-matrix
Python || Easy || Beginners solution
its_iterator
0
4
toeplitz matrix
766
0.688
Easy
12,512
https://leetcode.com/problems/toeplitz-matrix/discuss/2762178/Python3-easy-solution-Daily-solutions-in-python3
class Solution: def isToeplitzMatrix(self, matrix: List[List[int]])->bool: rows,colms = len(matrix),len(matrix[0]) for r in range (1,rows): for c in range (1,colms): if matrix[r][c]!=matrix[r-1][c-1]: return 0 return 1
toeplitz-matrix
Python3 easy solution Daily solutions in python3
rupamkarmakarcr7
0
2
toeplitz matrix
766
0.688
Easy
12,513
https://leetcode.com/problems/toeplitz-matrix/discuss/2762127/python-code-with-explanation
class Solution: def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool: n=len(matrix) #no. of rows m=len(matrix[0]) #no. of elements in a row,i.e.,no. of columns for i in range(n-1): for j in range(m-1): if not(matrix[i][j]==matrix[i+1][j+1]): return False return True
toeplitz-matrix
python code with explanation
ayushigupta2409
0
4
toeplitz matrix
766
0.688
Easy
12,514
https://leetcode.com/problems/toeplitz-matrix/discuss/2762020/Easy-Matrix-Traversal-or-Python-or-99-Faster
class Solution: def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool: n, m = len(matrix), len(matrix[0]) i, j = n-1, 0 while i!=0 or j!=m-1: i1, j1 = i, j res = matrix[i1][j1] while j1>=0 and i1>=0: if matrix[i1][j1]!=res: return False j1-=1; i1-=1 if j<m-1: j+=1 else: i-=1 return True
toeplitz-matrix
Easy Matrix Traversal | Python | 99% Faster
RajatGanguly
0
5
toeplitz matrix
766
0.688
Easy
12,515
https://leetcode.com/problems/toeplitz-matrix/discuss/2761979/Python-only-loop-through-top-left-point
class Solution: def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool: def checkTopLeftToBottomRight(x, y): i, j = x, y while i+1 < len(matrix) and j+1 < len(matrix[0]): i += 1 j += 1 if matrix[i][j] != matrix[x][y]: return False return True for i in range(len(matrix)-1)[::-1]: if not checkTopLeftToBottomRight(i,0): return False for j in range(1, len(matrix[0])-1): if not checkTopLeftToBottomRight(0,j): return False return True
toeplitz-matrix
Python only loop through top left point
zxia545
0
5
toeplitz matrix
766
0.688
Easy
12,516
https://leetcode.com/problems/toeplitz-matrix/discuss/2761973/Beat-91-solution-east-to-understand-using-example
class Solution: def solve(self , matrix ): count = 0 for i in range(len(matrix)): for j in range(len(matrix[0])): if i -1 > -1 and j - 1>-1 and matrix[i - 1][j-1]!=matrix[i][j]: return False return True def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool: return self.solve(matrix)
toeplitz-matrix
Beat 91% solution , east to understand using example
darkgod
0
4
toeplitz matrix
766
0.688
Easy
12,517
https://leetcode.com/problems/toeplitz-matrix/discuss/2761948/Easy-Python-or-Faster-or-4-Liner-or-O(n*m)-Time-or-O(1)-Space
class Solution: def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool: for i in range(1, len(matrix)): for j in range(1, len(matrix[0])): if matrix[i][j]!=matrix[i-1][j-1]: return False return True
toeplitz-matrix
Easy Python | Faster | 4 Liner | O(n*m) Time | O(1) Space
coolakash10
0
1
toeplitz matrix
766
0.688
Easy
12,518
https://leetcode.com/problems/toeplitz-matrix/discuss/2761875/Python-simple-and-most-readable-code
class Solution: def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool: diff = {} for i in range(len(matrix)): for j in range(len(matrix[0])): if(i-j not in diff): diff[i-j] = matrix[i][j] else: if(diff[i-j]!=matrix[i][j]): return False else: continue return True
toeplitz-matrix
Python simple and most readable code
Jayu79
0
5
toeplitz matrix
766
0.688
Easy
12,519
https://leetcode.com/problems/toeplitz-matrix/discuss/2761809/easy-brute-force-solution
class Solution: def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool: #calculating diagonals from the first row for i in range(len(matrix[0])): cur = matrix[0][i] j = i+1 t = 1 while j < len(matrix[0]) and t < len(matrix) : print(matrix[t][j]) if matrix[t][j] != cur: return False j += 1 t += 1 #calculating diagonals from the first column for j in range(1,len(matrix)): cur = matrix[j][0] print(cur) k = j+1 print(k) t = 1 print(t) while k < len(matrix) and t < len(matrix[0]) : if matrix[k][t] != cur: return False k += 1 t += 1 return True
toeplitz-matrix
easy brute force solution
neeshumaini55
0
4
toeplitz matrix
766
0.688
Easy
12,520
https://leetcode.com/problems/toeplitz-matrix/discuss/2761776/easy-python-solutionoror-easy-to-understandororTime-complexityO(n2)
class Solution: def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool: d = {} for i in range(len(matrix)): for j in range(len(matrix[0])): if (i-j) not in d: d[(i-j)] = matrix[i][j] else: if matrix[i][j]!=d[(i-j)]: return False return True
toeplitz-matrix
✅✅easy python solution|| easy to understand||Time complexityO(n2)
chessman_1
0
4
toeplitz matrix
766
0.688
Easy
12,521
https://leetcode.com/problems/toeplitz-matrix/discuss/2761766/Python3-Visually-Explained-Beats-91
class Solution: def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool: nrows,ncols = len(matrix),len(matrix[0]) #given the start of the diagonal, check if its univalue diagonal def unival(start): x,y = start while x<nrows and y<ncols: if matrix[x][y]==matrix[start[0]][start[1]]: x+=1 y+=1 else: return False return True #find all starting points for diagonals #along first row and first column for j in range(ncols): if not unival((0,j)): return False for i in range(nrows): if not unival((i,0)): return False return True
toeplitz-matrix
Python3 Visually Explained Beats 91%
user9611y
0
2
toeplitz matrix
766
0.688
Easy
12,522
https://leetcode.com/problems/toeplitz-matrix/discuss/2761738/FASTER-THAN-99.79-PYTHON-SOLUTION
class Solution: def help(self,matrix,i,j,x,n,m): if i+1>n-1 or j+1>m-1: return True if matrix[i+1][j+1]!=x: return False else: return self.help(matrix,i+1,j+1,x,n,m) return True def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool: n=len(matrix) m=len(matrix[0]) i=0 for j in range(0,m): x=matrix[i][j] if self.help(matrix,i,j,x,n,m): continue else: return False j=0 for i in range(0,n): x=matrix[i][j] if self.help(matrix,i,j,x,n,m): continue else: return False return True
toeplitz-matrix
FASTER THAN 99.79% PYTHON SOLUTION
DG-Problemsolver
0
2
toeplitz matrix
766
0.688
Easy
12,523
https://leetcode.com/problems/toeplitz-matrix/discuss/2761728/Easy-Python-Solution-or-Loops
class Solution: def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool: def answer(r, c): # print(matrix[r][c]) curr = matrix[r][c] while r < len(matrix) and c < len(matrix[0]): if curr != matrix[r][c]: return False r += 1 c += 1 return True r = 0 c = len(matrix[0])-1 while c >= 0: if not answer(r, c): return False c -= 1 c = 0 r += 1 while r < len(matrix): if not answer(r, 0): return False r += 1 return True
toeplitz-matrix
Easy Python Solution | Loops
atharva77
0
1
toeplitz matrix
766
0.688
Easy
12,524
https://leetcode.com/problems/toeplitz-matrix/discuss/2761713/Python3-or-Straight-Forward
class Solution: def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool: n, m = len(matrix), len(matrix[0]) def traverseDiagonal(x, y): i, j = x, y curEle = matrix[i][j] while i < n and j < m: if curEle != matrix[i][j]: return False i += 1 j += 1 return True # top row for r in range(len(matrix[0])): if not traverseDiagonal(0, r): return False # left col for c in range(1, len(matrix)): if not traverseDiagonal(c, 0): return False return True
toeplitz-matrix
Python3 | Straight Forward
vikinam97
0
1
toeplitz matrix
766
0.688
Easy
12,525
https://leetcode.com/problems/toeplitz-matrix/discuss/2761669/Python3-Oneliner
class Solution: def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool: return all(matrix[i][:len(matrix[0])-1] == matrix[i+1][1:] for i in range(len(matrix)-1))
toeplitz-matrix
Python3 Oneliner
anels
0
1
toeplitz matrix
766
0.688
Easy
12,526
https://leetcode.com/problems/toeplitz-matrix/discuss/2761660/Python-or-super-simple-iteration-O(n)-time-O(1)-space
class Solution: def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool: width = len(matrix[0]) height = len(matrix) r, c = height-1, 0 while r < height and c < width: current = matrix[r][c] outer_r, outer_c = r, c r += 1 c += 1 while r < height and c < width: if matrix[r][c] != current: return False r += 1 c += 1 c = outer_c+1 if outer_r==0 else 0 r = outer_r-1 if outer_r-1>=0 else 0 return True
toeplitz-matrix
Python | super simple iteration O(n) time, O(1) space
chienhsiang-hung
0
6
toeplitz matrix
766
0.688
Easy
12,527
https://leetcode.com/problems/toeplitz-matrix/discuss/2761631/Easy-to-understand-Python-code-(not-a-one-liner)
class Solution: def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool: for i in range(len(matrix)-1): for j in range(len(matrix[0])-1): if matrix[i][j]==matrix[i+1][j+1]: continue else: return False else: return True
toeplitz-matrix
Easy to understand Python code (not a one-liner)
sarveshebs
0
2
toeplitz matrix
766
0.688
Easy
12,528
https://leetcode.com/problems/toeplitz-matrix/discuss/2761592/Fast-and-Simple-Solution
class Solution: def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool: for i in range(1 ,len(matrix)): for j in range(1, len(matrix[0])): if matrix[i - 1][j - 1] != matrix[i][j]: return False return True
toeplitz-matrix
Fast and Simple Solution
user6770yv
0
1
toeplitz matrix
766
0.688
Easy
12,529
https://leetcode.com/problems/reorganize-string/discuss/488325/Python-8-Liner-Memory-usage-less-than-100
class Solution: def reorganizeString(self, S: str) -> str: counter = collections.Counter(S) i, res, n = 0, [None] * len(S), len(S) for k in sorted(counter, key = counter.get, reverse = True): if counter[k] > n // 2 + (n % 2): return "" for j in range(counter[k]): if i >= n: i = 1 res[i] = k; i += 2 return "".join(res)
reorganize-string
Python - 8 Liner - Memory usage less than 100%
mmbhatk
9
1,700
reorganize string
767
0.528
Medium
12,530
https://leetcode.com/problems/reorganize-string/discuss/741623/Python-heap-easy-solution-with-comments
class Solution: def reorganizeString(self, S: str) -> str: if not S: return '' heap, last, ans = [], None, '' counts = collections.Counter(S) for ch in counts: heapq.heappush(heap, (-counts[ch], ch)) while heap: count, ch = heapq.heappop(heap) ans += ch if last: heapq.heappush(heap, last) last = (count+1, ch) if count != -1 else None return ans if not last else ''
reorganize-string
Python heap easy solution with comments
sexylol
4
229
reorganize string
767
0.528
Medium
12,531
https://leetcode.com/problems/reorganize-string/discuss/1930450/Python-Easy-Solution-Max-Heap-and-Counter-Hashmap-with-Comments
class Solution: def reorganizeString(self, s: str) -> str: counter = {} for ch in s: if ch in counter: counter[ch] +=1 else: counter[ch] = 1 queue = [] for elem in counter: heapq.heappush(queue, (-1*counter[elem], elem)) result = [] prev_char = None prev_freq = None while(queue): freq, elem = heapq.heappop(queue) result.append(elem) if prev_freq: # it makes sure that character whihc is popped just now is not popped next, i.e. maintains non- adjacent condition heapq.heappush(queue, (prev_freq, prev_char)) prev_char, prev_freq = elem, freq + 1 # +1 is equivalent to -1 as we used max_heap if len(result) == len(s): return "".join(result) return ""
reorganize-string
Python Easy Solution Max Heap and Counter Hashmap with Comments
emerald19
2
175
reorganize string
767
0.528
Medium
12,532
https://leetcode.com/problems/reorganize-string/discuss/1918126/Python-No-Sort-O(N)
class Solution: def reorganizeString(self, s: str) -> str: count = Counter(s) # O(N) most_common_c = max(count.items(), key=itemgetter(1))[0] # O(N) if count[most_common_c] > (len(s)+1)//2: return "" output = ['']*len(s) i = 0 for _ in range(count[most_common_c]): output[i] = most_common_c i += 2 count[most_common_c] = 0 for k, v in count.items(): for _ in range(v): if i >= len(s): i = 1 output[i] = k i += 2 return "".join(output)
reorganize-string
Python, No Sort, O(N)
caseychen008
2
270
reorganize string
767
0.528
Medium
12,533
https://leetcode.com/problems/reorganize-string/discuss/1900082/Python-heap-solution-O(n-log-n)
class Solution: def reorganizeString(self, s: str) -> str: last, amountLast = None, None count = Counter(s) maxHeap = [(-count[char], char) for char in count.keys()] heapq.heapify(maxHeap) res = "" while maxHeap: tmp = heapq.heappop(maxHeap) res += tmp[1] if amountLast: heapq.heappush(maxHeap, (amountLast, last)) last, amountLast = tmp[1], tmp[0] + 1 return res if len(res) == len(s) else ""
reorganize-string
Python, heap solution O(n log n)
bchong123
2
185
reorganize string
767
0.528
Medium
12,534
https://leetcode.com/problems/reorganize-string/discuss/2369932/simple-python-heap
class Solution: def reorganizeString(self, S): h, res, c = [], [], Counter(S) for i in c: heappush(h, (-c[i], i)) p_a, p_b = 0, '' while h: a, b = heapq.heappop(h) res += [b] if p_a < 0: heapq.heappush(h, (p_a, p_b)) a += 1 p_a, p_b = a, b res = ''.join(res) if len(res) != len(S): return "" return res
reorganize-string
simple python heap
gasohel336
1
95
reorganize string
767
0.528
Medium
12,535
https://leetcode.com/problems/reorganize-string/discuss/1843491/Python-easy-to-read-and-understand-or-max-heap
class Solution: def reorganizeString(self, s: str) -> str: d = {} for i in s: d[i] = d.get(i, 0) + 1 pq = [] for key in d: heapq.heappush(pq, (-d[key], key)) res = '' cnt, ch = heapq.heappop(pq) res += ch block = (cnt+1, ch) while len(pq) > 0: cnt, ch = heapq.heappop(pq) res += ch if block[0] < 0: heapq.heappush(pq, block) block = (cnt+1, ch) if len(res) != len(s): return '' else: return res
reorganize-string
Python easy to read and understand | max-heap
sanial2001
1
262
reorganize string
767
0.528
Medium
12,536
https://leetcode.com/problems/reorganize-string/discuss/1437851/Python-solution-98-Using-Dictionary-O(n)
class Solution: def reorganizeString(self, s: str) -> str: arr,res = Counter(s),"" arr = {k:v for k,v in sorted(arr.items(),key = lambda v:v[1], reverse=True)} an = "" m = max(arr.values()) for k,v in arr.items(): an+=k*v #print(an,m) if len(s)%2==0: if m <=len(s)//2: for i,j in zip(an[:len(s)//2],an[len(s)//2:]): res+=i res+=j else: if m <= (len(s)//2) + 1: for i,j in zip(an[:(len(s)//2) + 1],an[(len(s)//2)+1:]): res+=i res+=j res+=an[len(s)//2] #print(res) return "".join(res) # solution By Rajeev Mohan
reorganize-string
Python solution 98% Using Dictionary, O(n)
rstudy211
1
483
reorganize string
767
0.528
Medium
12,537
https://leetcode.com/problems/reorganize-string/discuss/1399898/Python-16ms-faster-than-100
class Solution: def reorganizeString(self, s: str) -> str: # count the character in the string charMap = {} for i in range(len(s)): if s[i] in charMap: charMap[s[i]] += 1 else: charMap[s[i]] = 1 # sort the map by value - the character appears the most is at index 0 charMap = {k: v for k, v in sorted(charMap.items(), key=lambda x: x[1], reverse=True)} firstMap = list(charMap.items())[0] # character appears the most if len(s) <= (firstMap[1]-1)*2: return "" else: # create a string contains of different "phrase" # each character will be distinct in each phrase newstr = [firstMap[0] for _ in range(firstMap[1])] index = 0 charMap.pop(firstMap[0]) # the initialize value already contains the most appeared character for k, v in charMap.items(): for _ in range(v): if index == len(newstr): index = 0 # reset index counter newstr[index] += str(k) index += 1 return "".join(newstr)
reorganize-string
Python 16ms faster than 100%
percy_pham
1
297
reorganize string
767
0.528
Medium
12,538
https://leetcode.com/problems/reorganize-string/discuss/2845254/super-easy-solution-for-beginners-using-hashmap-in-**python**
class Solution: def reorganizeString(self, s: str) -> str: wc = {} lenn = 0 for letter in s: wc[letter] = wc.get(letter,0)+1 lenn += 1 if 2 * max(wc.values()) > sum(wc.values()) + 1: return "" else: # sorting the word counter based on frequency in decending order wc = dict(sorted(wc.items(),key=lambda x:x[1],reverse=True)) bs = ["" for i in range(lenn)] # filling the odd places for i in range(0,lenn,2): for key in wc.keys(): if wc[key]: bs[i] = key wc[key] -= 1 break # filling the even places for i in range(1,lenn,2): for key in wc.keys(): if wc[key]: bs[i] = key wc[key] -= 1 break return "".join(bs)
reorganize-string
super easy solution for beginners using hashmap in **python**
experimentallyf
0
4
reorganize string
767
0.528
Medium
12,539
https://leetcode.com/problems/reorganize-string/discuss/2830013/Python-hash-map-and-max-heap
class Solution: def reorganizeString(self, s: str) -> str: count = Counter(s) maxHeap = [[-freq, c] for c, freq in count.items()] heapq.heapify(maxHeap) prev = None res = "" while maxHeap or prev: if prev and not maxHeap: return "" freq, c = heapq.heappop(maxHeap) res += c freq += 1 if prev: heapq.heappush(maxHeap, prev) prev = None if freq != 0: prev = [freq, c] return res
reorganize-string
Python hash map and max heap
zananpech9
0
4
reorganize string
767
0.528
Medium
12,540
https://leetcode.com/problems/reorganize-string/discuss/2777897/Python%3A-Heap-Sort-(Prority-Queue)-%2B-Hashmap-oror-Time-Complexity-O(nlogn)
class Solution: def reorganizeString(self, s: str) -> str: d={} for i in range(len(s)): curr=s[i] if curr in d.keys(): d[curr]+=1 else: d[curr]=1 m=[] for i,j in d.items(): heapq.heappush(m,[-j,i]) s1="" while (len(m)>=2): a=heapq.heappop(m) b=heapq.heappop(m) s1=s1+a[1]+b[1] a[0]=a[0]+1 b[0]=b[0]+1 if a[0]!=0: heapq.heappush(m,a) if b[0]!=0: heapq.heappush(m,b) if len(m)==1: a=heapq.heappop(m) if (a[0]*-1)>1: return "" else: s1=s1+a[1] return s1
reorganize-string
Python: Heap Sort (Prority Queue) + Hashmap || Time Complexity= O(nlogn)
utsa_gupta
0
13
reorganize string
767
0.528
Medium
12,541
https://leetcode.com/problems/reorganize-string/discuss/2764818/Python3-using-a-dictionary-for-character-frequency-(99)
class Solution: def reorganizeString(self, s: str) -> str: char_dict = {} for c in s: if c not in char_dict: char_dict[c] = 1 else: char_dict[c] += 1 if 2*max(char_dict.values()) > len(s) + 1: return '' char_list = [] max_char_val = 0 old = '' new = '' for _ in s: new = list(char_dict.keys())[list(char_dict.values()).index(max(char_dict.values()))] #get char with max no. of occurrences from dict if old: char_dict[old] = max_char_val - 1 #reset the previous max char's value back to what it should be, minus one for using it max_char_val = char_dict[new] #store the no. occurrences of the char with max occurrences char_dict[new] = 0 #temporary devaluation to prevent repetition char_list.append(new) #add the character to the list old = new rearranged_string = ''.join(char_list) return rearranged_string
reorganize-string
Python3 using a dictionary for character frequency (99%)
Kenpari
0
9
reorganize string
767
0.528
Medium
12,542
https://leetcode.com/problems/reorganize-string/discuss/2704330/Python-O(NlogN)-O(1)
class Solution: def reorganizeString(self, s: str) -> str: counter = collections.Counter(s) heap = [(-counter[c], c) for c in counter] heapq.heapify(heap) res = [] lastOcc, lastChar = 0, "" while heap: tempOcc, tempChar = lastOcc, lastChar lastOcc, lastChar = heapq.heappop(heap) if tempOcc < 0: heapq.heappush(heap, (tempOcc, tempChar)) res.append(lastChar) lastOcc += 1 if lastOcc < 0: return "" return "".join(res)
reorganize-string
Python - O(NlogN), O(1)
Teecha13
0
19
reorganize string
767
0.528
Medium
12,543
https://leetcode.com/problems/reorganize-string/discuss/1825832/Two-methods%3A-python-heapq-and-greedy
class Solution: def reorganizeString(self, s: str) -> str: n = len(s) s = Counter(s) max_l = s.most_common(1)[0][1] # if the number of any letter larger then the haft length (or plus1 when it is even) of the string # impossible to reorganize if (n+1)//2<max_l: return "" # using odd/even insert oddIndex=0 evenIndex=1 out=[""]*n # create slot for k,v in s.most_common(): while v and oddIndex<n: # fill the most letter in all odd places out[oddIndex] = k oddIndex+=2 v-=1 while v: # then fill the remain in evenIndex out[evenIndex] = k evenIndex+=2 v-=1 return "".join(out) # using heapq q = [] out="" for k,v in s.items(): heapq.heappush(q,(-v,k)) while len(q)>1: v,l=heapq.heappop(q) if not len(out): out+=l if v+1<0: heapq.heappush(q,(v+1,l)) elif l!=out[-1]: out+=l if v+1<0: heapq.heappush(q,(v+1,l)) else: v2,l2=heapq.heappop(q) out+=l2 if v2+1<0: heapq.heappush(q,(v2+1,l2)) heapq.heappush(q,(v,l)) if q[0][0]<-1: return "" else: return out+q[0][1]
reorganize-string
Two methods: python heapq and greedy
cooldog6026
0
116
reorganize string
767
0.528
Medium
12,544
https://leetcode.com/problems/reorganize-string/discuss/1771697/Python-no-sort.-Time%3A-O(N).-Space%3A-O(N)
class Solution: def reorganizeString(self, s: str) -> str: h = [(-count, char) for char, count in Counter(s).items()] heapq.heapify(h) if -h[0][0] > (len(s) + 1) // 2: return "" idx = 0 result = [None] * len(s) for count, char in h: for _ in range(-count): result[idx] = char idx += 2 if idx >= len(s): idx = 1 return "".join(result)
reorganize-string
Python, no sort. Time: O(N). Space: O(N)
blue_sky5
0
240
reorganize string
767
0.528
Medium
12,545
https://leetcode.com/problems/reorganize-string/discuss/1687901/Simple-python-solution-with-Counter-API
class Solution: def reorganizeString(self, s: str) -> str: s_counter = Counter(s) def remove(s_counter, char): s_counter[char] -= 1 if s_counter[char] == 0: s_counter.pop(char) def take(s_counter, adj_char): for ch in s_counter.most_common(2): if ch[0][0] == adj_char: continue return ch[0][0] return "" new_s = s_counter.most_common(1)[0][0] remove(s_counter, new_s) for i in range(1, len(s)): new_char = take(s_counter, new_s[-1]) if not new_char: return "" new_s += new_char remove(s_counter, new_char) return new_s
reorganize-string
Simple python solution with Counter API
Arvindn
0
143
reorganize string
767
0.528
Medium
12,546
https://leetcode.com/problems/reorganize-string/discuss/1670521/Using-Max-heap-in-python-with-example
class Solution: import heapq def reorganizeString(self, s: str) -> str: d={} for i in s: if i in d: d[i]+=1 else: d[i]=1 l=[] for i in d: # -ive sign is used beacuse there in no max-heap in python x=[-d[i],i] l.append(x) # l will look like this l=[[-2, a],[-3, b],[-1, c]] heapq.heapify(l) ans="" while len(l)>1: m=heapq.heappop(l) n=heapq.heappop(l) ans+=m[1]+n[1] # I am adding here is same as decreasing the count because the count here is -ive # If the count is 0 than no need to push if m[0]+1!=0: heapq.heappush(l,[m[0]+1,m[1]]) if n[0]+1!=0: heapq.heappush(l,[n[0]+1,n[1]]) if l==[]: return ans # if any character count is more than 1 left than its a not possible case if (l[0][0]*-1)==1: x=l.pop() ans+=x[1] return ans else: return ""
reorganize-string
Using Max-heap in python with example
gamitejpratapsingh998
0
180
reorganize string
767
0.528
Medium
12,547
https://leetcode.com/problems/reorganize-string/discuss/1512760/Python3-Solution-with-using-heap
class Solution: def reorganizeString(self, s: str) -> str: counter = collections.Counter(s) l = [""] * len(s) heap = [] for key in counter: heapq.heappush(heap, [-counter[key], key]) idx = 0 while len(heap) > 0: symb_count, symb = heapq.heappop(heap) symb_count *= -1 while symb_count > 0: l[idx] = symb symb_count -= 1 if idx > 0 and l[idx] == l[idx - 1]: return "" if idx + 2 >= len(l): idx = -1 idx += 2 return "".join(l)
reorganize-string
[Python3] Solution with using heap
maosipov11
0
127
reorganize string
767
0.528
Medium
12,548
https://leetcode.com/problems/reorganize-string/discuss/1193641/queue-based-python-sol
class Solution: def reorganizeString(self, string: str) -> str: n=len(string) dict=Counter(string) dict=sorted(dict.items(),key=lambda x:-x[1]) print(dict) new=[] for i,j in dict: for k in range(j): new.append(i) ans=[0]*n queue=[] for i in range(0,n): queue.append(i) for i in new: l=queue[0] if l==0 and ans[l+1]!=i: ans[queue.pop(0)]=i if queue: queue.append(queue.pop(0)) elif l==n-1 and ans[l-1]!=i: ans[queue.pop(0)]=i if queue: queue.append(queue.pop(0)) elif 0<l<n-1 and ans[l-1]!=i and ans[l+1]!=i: ans[queue.pop(0)]=i if queue: queue.append(queue.pop(0)) else: return "" return "".join(ans)
reorganize-string
queue based python sol
heisenbarg
0
142
reorganize string
767
0.528
Medium
12,549
https://leetcode.com/problems/reorganize-string/discuss/776668/Python-Max-Heap
class Solution: def reorganizeString(self, S: str) -> str: if not S: return "" elif len(S) == 1: return S # Initialize max heap counts, res, heap = Counter(S), [], [] for char in counts: heapq.heappush(heap, (-counts[char], char)) while len(heap) > 1: # Get next two chars... count1, char1 = heapq.heappop(heap) count2, char2 = heapq.heappop(heap) # Update counts count1 += 1 count2 += 1 # Add to result res.extend([char1, char2]) # Add chars back to heap if we have not used them all... if count1 < 0: heapq.heappush(heap, (count1, char1)) if count2 < 0: heapq.heappush(heap, (count2, char2)) # If we cannot alternate this char... if len(heap) > 0 and abs(heap[0][0]) > 1: return "" # Otherwise add last char to result string elif len(heap) > 0: res.append(heap[0][1]) return "".join(res)
reorganize-string
Python Max Heap
zuu
0
108
reorganize string
767
0.528
Medium
12,550
https://leetcode.com/problems/reorganize-string/discuss/760848/Python3-via-heap
class Solution: def reorganizeString(self, S: str) -> str: #frequency table freq = dict() for c in S: freq[c] = 1 + freq.get(c, 0) #max heap hp = [(-v, k) for k, v in freq.items()] heapify(hp) i = 0 ans = [""]*len(S) while hp: v, k = heappop(hp) v = -v if 2*v - 1 > len(S): return "" #impossible for _ in range(v): ans[i] = k i = i+2 if i+2 < len(S) else 1 return "".join(ans)
reorganize-string
[Python3] via heap
ye15
0
72
reorganize string
767
0.528
Medium
12,551
https://leetcode.com/problems/reorganize-string/discuss/760848/Python3-via-heap
class Solution: def reorganizeString(self, S: str) -> str: freq = {} for c in S: freq[c] = 1 +freq.get(c, 0) # frequency table ans = [""]*len(S) i = 0 for k in sorted(freq, reverse=True, key=freq.get): if 2*freq[k] - 1 > len(S): return "" # impossible for _ in range(freq[k]): ans[i] = k i = i+2 if i+2 < len(S) else 1 # reset to 1 return "".join(ans)
reorganize-string
[Python3] via heap
ye15
0
72
reorganize string
767
0.528
Medium
12,552
https://leetcode.com/problems/reorganize-string/discuss/449996/Easy-to-understand-Python3-solution
class Solution: def reorganizeString(self, S: str) -> str: from collections import Counter c=Counter(S) if(len(c.keys())==1): return '' else: l=list(c.keys()) l.sort(key=lambda x:c[x]) v=[c[i] for i in l] s='' for i in range(len(l)-1): x=l[i+1]+l[i] s+=x*v[i] v[i+1]-=v[i] if(v[-1]>0): s+=l[-1] v[-1]-=1 ans='' if(v[-1]>0): for i in range(len(s)): if(s[i]!=l[-1] and v[-1]>0): ans+=(l[-1]+s[i]) v[-1]-=1 continue elif(v[-1]==0): ans+=s[i:] return ans elif(s[i]==l[-1] and v[-1]!=0): return '' return s
reorganize-string
Easy to understand Python3 solution
Banra123
0
138
reorganize string
767
0.528
Medium
12,553
https://leetcode.com/problems/reorganize-string/discuss/425376/Python3-heap-solution-24ms-beat-99
class Solution: def reorganizeString(self, S: str) -> str: counted=collections.Counter(S) heap=[] result=[] last=None #record the last placed node for key in counted: heapq.heappush(heap,[-1*counted[key],key]) #biggest heap with characters ranked by occuring times while(heap): node=heapq.heappop(heap) #take the most occuring cha out and hidding it for one time to avoid be adjacent to itself result.append(node[1]) node[0]+=1 #the occuring times -1 if last and last[0]<0: #put hidded cha back to the heap heapq.heappush(heap,last) last=node # the hidded cha if len(result)==len(S): return "".join(result) else: return ""
reorganize-string
Python3 heap solution 24ms beat 99%
wangzi100
0
127
reorganize string
767
0.528
Medium
12,554
https://leetcode.com/problems/reorganize-string/discuss/405960/Python-3-(beats-~100)-(seven-lines)
class Solution: def reorganizeString(self, S: str) -> str: L, A, m, B = len(S), [0]*len(S), 1-len(S) % 2, [] for k,v in collections.Counter(S).most_common(): B += k*v for i,c in enumerate(B): I = (2*i + (2*i >= L)*m) % L A[I] = c if I != 0 and A[I-1] == c: return '' return "".join(A) - Junaid Mansuri
reorganize-string
Python 3 (beats ~100%) (seven lines)
junaidmansuri
-1
684
reorganize string
767
0.528
Medium
12,555
https://leetcode.com/problems/max-chunks-to-make-sorted-ii/discuss/1498733/Easy-to-Understand-oror-98-faster-oror-Well-Explained
class Solution: def maxChunksToSorted(self, nums: List[int]) -> int: st = [] for n in nums: if len(st)==0 or st[-1]<=n: st.append(n) else: ma = st[-1] while st and st[-1]>n: ma = max(ma,st.pop()) st.append(ma) return len(st)
max-chunks-to-make-sorted-ii
📌📌 Easy-to-Understand || 98% faster || Well-Explained 🐍
abhi9Rai
14
659
max chunks to make sorted ii
768
0.528
Hard
12,556
https://leetcode.com/problems/max-chunks-to-make-sorted-ii/discuss/1419866/Python-Solution-Monotonic-queue-O(N)
class Solution: def maxChunksToSorted(self, arr: List[int]) -> int: S = [] for a in arr: min_i, max_i = a, a while S and a < S[-1][1]: start, end = S.pop() min_i, max_i = min(start, min_i), max(end, max_i) S.append([min_i, max_i]) return len(S)
max-chunks-to-make-sorted-ii
Python Solution - Monotonic queue O(N)
ahujara
1
138
max chunks to make sorted ii
768
0.528
Hard
12,557
https://leetcode.com/problems/max-chunks-to-make-sorted-ii/discuss/1342227/Python3-greedy
class Solution: def maxChunksToSorted(self, arr: List[int]) -> int: mn = [inf]*(1 + len(arr)) for i in reversed(range(len(arr))): mn[i] = min(arr[i], mn[i+1]) ans = mx = 0 for i, x in enumerate(arr): mx = max(mx, x) if mx <= mn[i+1]: ans += 1 return ans
max-chunks-to-make-sorted-ii
[Python3] greedy
ye15
1
115
max chunks to make sorted ii
768
0.528
Hard
12,558
https://leetcode.com/problems/max-chunks-to-make-sorted-ii/discuss/1342227/Python3-greedy
class Solution: def maxChunksToSorted(self, arr: List[int]) -> int: stack = [] for i, x in enumerate(arr): most = x while stack and stack[-1] > x: most = max(most, stack.pop()) stack.append(most) return len(stack)
max-chunks-to-make-sorted-ii
[Python3] greedy
ye15
1
115
max chunks to make sorted ii
768
0.528
Hard
12,559
https://leetcode.com/problems/max-chunks-to-make-sorted-ii/discuss/2833062/Python-solution-using-array-O(n)
class Solution: def maxChunksToSorted(self, arr: list[int]) -> int: max_chunk = 0 min_left_i = [float('inf')]*(len(arr)+1) curr_min = math.inf # find the for i in range(len(arr)-1, -1, -1): if arr[i] < curr_min: curr_min = arr[i] min_left_i[i] = curr_min max_till_i = arr[0] for i in range(len(arr)): if arr[i] > max_till_i: max_till_i = arr[i] # check to verify if there is no element to the right which is lower than the current. if max_till_i <= min_left_i[i+1]: max_chunk += 1 return max_chunk
max-chunks-to-make-sorted-ii
Python solution using array O(n)
runForrest
0
3
max chunks to make sorted ii
768
0.528
Hard
12,560
https://leetcode.com/problems/max-chunks-to-make-sorted-ii/discuss/2515259/Python3-or-Stack-Approach
class Solution: def maxChunksToSorted(self, arr: List[int]) -> int: stack=[] for v in arr: maxVal=-float('inf') while stack and stack[-1]>v: maxVal=max(maxVal,stack.pop()) stack.append(max(v,maxVal)) return len(stack)
max-chunks-to-make-sorted-ii
[Python3] | Stack Approach
swapnilsingh421
0
59
max chunks to make sorted ii
768
0.528
Hard
12,561
https://leetcode.com/problems/max-chunks-to-make-sorted-ii/discuss/2040797/python3-iterate-backwards
class Solution: def maxChunksToSorted(self, arr: List[int]) -> int: n=len(arr) que=[] res=0 for i in range(n-1,-1,-1): if not que or arr[i]<=que[0]: que.insert(0,arr[i]) res+=1 else: a=bisect_left(que,arr[i]) if len(que)-1-a<0: que=que[0:1] res=1 elif a-1!=0: res=len(que)-a+1 que=que[0:1]+que[a:] return res
max-chunks-to-make-sorted-ii
python3 iterate backwards
appleface
0
23
max chunks to make sorted ii
768
0.528
Hard
12,562
https://leetcode.com/problems/max-chunks-to-make-sorted/discuss/1579999/Python3-Solution-with-using-stack
class Solution: def maxChunksToSorted(self, arr: List[int]) -> int: stack = [] for num in arr: lagest = num while stack and num < stack[-1]: lagest = max(lagest, stack.pop()) stack.append(lagest) return len(stack)
max-chunks-to-make-sorted
[Python3] Solution with using stack
maosipov11
1
95
max chunks to make sorted
769
0.582
Medium
12,563
https://leetcode.com/problems/max-chunks-to-make-sorted/discuss/1407579/Python-3-easy-solution
class Solution: def maxChunksToSorted(self, arr: List[int]) -> int: temp_sum, block = 0, 0 for i in range(len(arr)): temp_sum += arr[i] - i if temp_sum == 0: block += 1 return block
max-chunks-to-make-sorted
Python 3 easy solution
Andy_Feng97
1
64
max chunks to make sorted
769
0.582
Medium
12,564
https://leetcode.com/problems/max-chunks-to-make-sorted/discuss/2046530/python-3-oror-greedy-solution-oror-O(n)(1)
class Solution: def maxChunksToSorted(self, nums: List[int]) -> int: chunks = 0 left = 0 n = len(nums) smallest, largest = n, -1 for right, num in enumerate(nums): smallest = min(smallest, num) largest = max(largest, num) if left <= smallest and largest <= right: chunks += 1 left = right + 1 smallest, largest = n, -1 return chunks
max-chunks-to-make-sorted
python 3 || greedy solution || O(n)/(1)
dereky4
0
82
max chunks to make sorted
769
0.582
Medium
12,565
https://leetcode.com/problems/max-chunks-to-make-sorted/discuss/923484/Python3-greedy
class Solution: def maxChunksToSorted(self, arr: List[int]) -> int: ans = prefix = 0 for i, x in enumerate(arr): prefix = max(prefix, x) if i == prefix: ans += 1 return ans
max-chunks-to-make-sorted
[Python3] greedy
ye15
0
71
max chunks to make sorted
769
0.582
Medium
12,566
https://leetcode.com/problems/max-chunks-to-make-sorted/discuss/526573/Python3-20ms-96-solution
class Solution: def maxChunksToSorted(self, arr: List[int]) -> int: start, max_value, chunks = 0, 0, 0 for index, value in enumerate(arr): max_value = max(value, max_value) if max_value - start == index - start: chunks += 1 start = index + 1 return chunks
max-chunks-to-make-sorted
Python3 20ms 96% solution
tjucoder
0
61
max chunks to make sorted
769
0.582
Medium
12,567
https://leetcode.com/problems/max-chunks-to-make-sorted/discuss/1410648/Python-3-oror-Easy-understanding-oror-self-understandable
class Solution: def maxChunksToSorted(self, arr: List[int]) -> int: largest_chunk=0 start=0 for i in range(len(arr)): visited=[False]*len(arr) for j in range(start,i+1): visited[arr[j]]=True if all(visited[start:i+1]): largest_chunk+=1 start=i+1 return largest_chunk
max-chunks-to-make-sorted
Python 3 || Easy-understanding || self-understandable
bug_buster
-2
186
max chunks to make sorted
769
0.582
Medium
12,568
https://leetcode.com/problems/jewels-and-stones/discuss/362196/Solution-in-Python-3-(beats-~94)-(one-line)-(three-solutions)
class Solution: def numJewelsInStones(self, J: str, S: str) -> int: return sum(i in J for i in S) class Solution: def numJewelsInStones(self, J: str, S: str) -> int: return sum(S.count(i) for i in J) from collections import Counter class Solution: def numJewelsInStones(self, J: str, S: str) -> int: return sum(Counter(S)[i] for i in J) - Junaid Mansuri (LeetCode ID)@hotmail.com
jewels-and-stones
Solution in Python 3 (beats ~94%) (one line) (three solutions)
junaidmansuri
28
4,500
jewels and stones
771
0.881
Easy
12,569
https://leetcode.com/problems/jewels-and-stones/discuss/1016607/Easy-and-Clear-Solution-Python-3
class Solution: def numJewelsInStones(self, jewels: str, stones: str) -> int: occ=dict() for i in stones: if i in occ.keys(): occ[i]+=1 else: occ.update({i:1}) res=0 for i in jewels: if i in occ.keys(): res+=occ[i] return res
jewels-and-stones
Easy & Clear Solution Python 3
moazmar
5
432
jewels and stones
771
0.881
Easy
12,570
https://leetcode.com/problems/jewels-and-stones/discuss/1016607/Easy-and-Clear-Solution-Python-3
class Solution: def numJewelsInStones(self, jewels: str, stones: str) -> int: res=0 for i in stones: if i in set(jewels): res+=1 return res
jewels-and-stones
Easy & Clear Solution Python 3
moazmar
5
432
jewels and stones
771
0.881
Easy
12,571
https://leetcode.com/problems/jewels-and-stones/discuss/1804792/Python-3-Simple-solution
class Solution: def numJewelsInStones(self, jewels: str, stones: str) -> int: stones = list(stones) jewels = list(jewels) match = len([i for i in stones if i in jewels]) return match
jewels-and-stones
[Python 3] Simple solution
IvanTsukei
4
147
jewels and stones
771
0.881
Easy
12,572
https://leetcode.com/problems/jewels-and-stones/discuss/1804792/Python-3-Simple-solution
class Solution: def numJewelsInStones(self, jewels: str, stones: str) -> int: return len([i for i in list(stones) if i in list(jewels)])
jewels-and-stones
[Python 3] Simple solution
IvanTsukei
4
147
jewels and stones
771
0.881
Easy
12,573
https://leetcode.com/problems/jewels-and-stones/discuss/1047701/Python-1-liner
class Solution: def numJewelsInStones(self, j: str, s: str) -> int: return sum(i in j for i in s)
jewels-and-stones
Python 1-liner
lokeshsenthilkumar
4
385
jewels and stones
771
0.881
Easy
12,574
https://leetcode.com/problems/jewels-and-stones/discuss/2165889/Python3-O(j%2Bs)-oror-O(1)-Runtime%3A-27ms-97.69-memory%3A-10mb-10.87
class Solution: # O(j+s) where j is jewels and s is stones # memory: O(1) we will english letters. # Runtime: 27ms 97.69% memory: 10mb 10.87% def numJewelsInStones(self, jewels: str, stones: str) -> int: jewelsMap = dict() for i in jewels: jewelsMap[i] = jewelsMap.get(i, 0) + 1 oldSum = sum(jewelsMap.values()) for i in stones: if i in jewelsMap: jewelsMap[i] = jewelsMap.get(i, 0) + 1 return sum(jewelsMap.values()) - oldSum
jewels-and-stones
Python3 O(j+s) || O(1) Runtime: 27ms 97.69% memory: 10mb 10.87%
arshergon
3
124
jewels and stones
771
0.881
Easy
12,575
https://leetcode.com/problems/jewels-and-stones/discuss/1273148/or-One-line-or-Python-3-or-95.69-faster-or-Using-count()-or
class Solution: def numJewelsInStones(self, jewels: str, stones: str) -> int: return sum([stones.count(l) for l in jewels if l in stones])
jewels-and-stones
| One line | Python 3 | 95.69% faster | Using count() |
anotherprogramer
2
125
jewels and stones
771
0.881
Easy
12,576
https://leetcode.com/problems/jewels-and-stones/discuss/1171051/Simple-Python-Solutions%3A-Multiple-Approaches_O(n%2Bm)
class Solution: def numJewelsInStones(self, jewels: str, stones: str) -> int: if len(jewels)==0 or len(stones)==0: return 0 jewels = set(jewels) j_count = 0 for s in stones: if s in jewels: j_count+=1 return j_count
jewels-and-stones
Simple Python Solutions: Multiple Approaches_O(n+m)
smaranjitghose
2
181
jewels and stones
771
0.881
Easy
12,577
https://leetcode.com/problems/jewels-and-stones/discuss/1171051/Simple-Python-Solutions%3A-Multiple-Approaches_O(n%2Bm)
class Solution: def numJewelsInStones(self, jewels: str, stones: str) -> int: if len(jewels)==0 or len(stones)==0: return 0 j_count = 0 for j in jewels: j_count+=stones.count(j) return j_count
jewels-and-stones
Simple Python Solutions: Multiple Approaches_O(n+m)
smaranjitghose
2
181
jewels and stones
771
0.881
Easy
12,578
https://leetcode.com/problems/jewels-and-stones/discuss/1171051/Simple-Python-Solutions%3A-Multiple-Approaches_O(n%2Bm)
class Solution: def numJewelsInStones(self, jewels: str, stones: str) -> int: if len(jewels)==0 or len(stones)==0: return 0 return sum([1 for s in stones if s in jewels])
jewels-and-stones
Simple Python Solutions: Multiple Approaches_O(n+m)
smaranjitghose
2
181
jewels and stones
771
0.881
Easy
12,579
https://leetcode.com/problems/jewels-and-stones/discuss/2752400/Python-or-Runtime-beats-99.00-of-submitted-solutions-or-Explained
class Solution: def numJewelsInStones(self, jewels: str, stones: str) -> int: target = 0 jewels = sorted(jewels) for jewel in jewels: if jewel in stones: target += stones.count(jewel) return target
jewels-and-stones
Python | Runtime beats 99.00 % of submitted solutions | Explained
sahil193101
1
16
jewels and stones
771
0.881
Easy
12,580
https://leetcode.com/problems/jewels-and-stones/discuss/2582286/Pythonoror2-line-codeororList-comprehension
class Solution: def numJewelsInStones(self, jewels: str, stones: str) -> int: st=Counter(stones) return sum([st[j] for j in jewels if j in st])
jewels-and-stones
Python||2-line code||List comprehension
shersam999
1
58
jewels and stones
771
0.881
Easy
12,581
https://leetcode.com/problems/jewels-and-stones/discuss/2148998/hashmap
class Solution: def numJewelsInStones(self, jewels: str, stones: str) -> int: # use a hashmap to map stones to their freq # iterate jewels as keys # add the key loopup to a result # use get to void a KeyError # Time: O(n + m) Space: O(n) d = Counter(stones) res = 0 for k in jewels: res += d.get(k, 0) return res
jewels-and-stones
hashmap
andrewnerdimo
1
50
jewels and stones
771
0.881
Easy
12,582
https://leetcode.com/problems/jewels-and-stones/discuss/1863207/Python-easy-solution-faster-than-95
class Solution: def numJewelsInStones(self, jewels: str, stones: str) -> int: count = 0 for i in jewels: count += stones.count(i) return count
jewels-and-stones
Python easy solution faster than 95%
alishak1999
1
122
jewels and stones
771
0.881
Easy
12,583
https://leetcode.com/problems/jewels-and-stones/discuss/1796626/python-3-or-simple-solution
class Solution: def numJewelsInStones(self, jewels: str, stones: str) -> int: c = 0 for i in stones: if i in jewels: c += 1 return c
jewels-and-stones
✔python 3 | simple solution
Coding_Tan3
1
47
jewels and stones
771
0.881
Easy
12,584
https://leetcode.com/problems/jewels-and-stones/discuss/1733625/771-JEWELS-and-STONES-PYTHON
class Solution(object): def numJewelsInStones(self, jewels, stones): jewel_found = 0 for each in jewels: for stone in stones: if each == stone: jewel_found += 1 return jewel_found
jewels-and-stones
771 JEWELS & STONES PYTHON
ankit61d
1
64
jewels and stones
771
0.881
Easy
12,585
https://leetcode.com/problems/jewels-and-stones/discuss/1212973/Python-Beating-99-in-Time
class Solution: def numJewelsInStones(self, jewels: str, stones: str) -> int: d = {} for i in stones: if i not in d: d[i] = 1 else: d[i]+=1 ans = 0 for i in jewels: if i in d: ans+=d[i] return ans
jewels-and-stones
Python Beating 99% in Time
iamkshitij77
1
95
jewels and stones
771
0.881
Easy
12,586
https://leetcode.com/problems/jewels-and-stones/discuss/1122545/one-liner-28ms-easy
class Solution: def numJewelsInStones(self, jewels: str, stones: str) -> int: return sum([stones.count(i) for i in [j for j in jewels]])
jewels-and-stones
one liner 28ms easy
nuke01
1
100
jewels and stones
771
0.881
Easy
12,587
https://leetcode.com/problems/jewels-and-stones/discuss/1011101/python3-solution-with-list-comprehension
class Solution: def numJewelsInStones(self, jewels: str, stones: str) -> int: return sum([stones.count(item) for item in jewels])
jewels-and-stones
python3 solution with list comprehension
MartenMink
1
133
jewels and stones
771
0.881
Easy
12,588
https://leetcode.com/problems/jewels-and-stones/discuss/998322/Python-or-3-Methods-or-Efficient-Solution
class Solution: def numJewelsInStones(self, jewels: str, stones: str) -> int: res = 0 for i in stones: if i in jewels: res+=1 return res
jewels-and-stones
Python | 3 Methods | Efficient Solution
hritik5102
1
80
jewels and stones
771
0.881
Easy
12,589
https://leetcode.com/problems/jewels-and-stones/discuss/998322/Python-or-3-Methods-or-Efficient-Solution
class Solution: def numJewelsInStones(self, jewels: str, stones: str) -> int: res = 0 d = {} for i in stones: if i in d: d[i]+=1 else: d[i] = 1 for i in jewels: if i in d: res+= d[i] return res
jewels-and-stones
Python | 3 Methods | Efficient Solution
hritik5102
1
80
jewels and stones
771
0.881
Easy
12,590
https://leetcode.com/problems/jewels-and-stones/discuss/998322/Python-or-3-Methods-or-Efficient-Solution
class Solution: def numJewelsInStones(self, jewels: str, stones: str) -> int: res = 0 for i in list(jewels): res+= stones.count(i) return res
jewels-and-stones
Python | 3 Methods | Efficient Solution
hritik5102
1
80
jewels and stones
771
0.881
Easy
12,591
https://leetcode.com/problems/jewels-and-stones/discuss/941811/Python-Easy-Solution
class Solution: def numJewelsInStones(self, J: str, S: str) -> int: return sum(S.count(i) for i in J)
jewels-and-stones
Python Easy Solution
lokeshsenthilkumar
1
212
jewels and stones
771
0.881
Easy
12,592
https://leetcode.com/problems/jewels-and-stones/discuss/941811/Python-Easy-Solution
class Solution: def numJewelsInStones(self, J: str, S: str) -> int: return sum(i in J for i in S)
jewels-and-stones
Python Easy Solution
lokeshsenthilkumar
1
212
jewels and stones
771
0.881
Easy
12,593
https://leetcode.com/problems/jewels-and-stones/discuss/262418/Python3-99-Explanation
class Solution: def numJewelsInStones(self, J: str, S: str) -> int: ss = {} for s in S: ss[s] = ss.get(s, 0) + 1 # if the key is not there, return a default value of 0, then increment by 1 counter = 0 for j in J: counter += ss.get(j, 0) # if that character is not in the dictionary, return 0 return counter
jewels-and-stones
Python3 99% Explanation
Khris
1
177
jewels and stones
771
0.881
Easy
12,594
https://leetcode.com/problems/jewels-and-stones/discuss/2844360/Easy-Python
class Solution: def numJewelsInStones(self, jewels: str, stones: str) -> int: count1 = 0 for i in range(0,len(stones)): if stones[i] in jewels: count1+=1 return count1
jewels-and-stones
Easy Python
khanismail_1
0
1
jewels and stones
771
0.881
Easy
12,595
https://leetcode.com/problems/jewels-and-stones/discuss/2837464/Beginners-PythonCode
class Solution: def numJewelsInStones(self, jewels: str, stones: str) -> int: count = "" for i in range (0, len(jewels)): for j in range(0, len(stones)): if jewels[i]==stones[j]: count += jewels[i] return len(count)
jewels-and-stones
Beginners - PythonCode
bharatvishwa
0
1
jewels and stones
771
0.881
Easy
12,596
https://leetcode.com/problems/jewels-and-stones/discuss/2830949/Basic-Solution-For-Beginners
class Solution: def numJewelsInStones(self, jewels: str, stones: str) -> int: count=0 for i in stones: if i in jewels: count+=1 return count
jewels-and-stones
Basic Solution For Beginners
VidishaPandey
0
1
jewels and stones
771
0.881
Easy
12,597
https://leetcode.com/problems/jewels-and-stones/discuss/2830357/fastest-python-solution
class Solution: def numJewelsInStones(self, jewels: str, stones: str) -> int: jewels = set(jewels) return sum(x in jewels for x in stones)
jewels-and-stones
fastest python solution
TrickyUnicorn
0
2
jewels and stones
771
0.881
Easy
12,598
https://leetcode.com/problems/jewels-and-stones/discuss/2815478/Multiple-Fast-and-Simple-Solutions-Python-(One-Liner-Included)
class Solution: def numJewelsInStones(self, jewels: str, stones: str) -> int: count = 0 for i in stones: if i in jewels: count += 1 return count
jewels-and-stones
Multiple Fast and Simple Solutions - Python (One-Liner Included)
PranavBhatt
0
2
jewels and stones
771
0.881
Easy
12,599