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/transpose-matrix/discuss/2100222/Python-one-liner-with-detailed-explanation90-less-memory-usage
class Solution: def transpose(self, matrix: List[List[int]]) -> List[List[int]]: return zip(*matrix)
transpose-matrix
Python one-liner with [detailed explanation][90% less memory usage]
steuxnet
0
23
transpose matrix
867
0.635
Easy
14,100
https://leetcode.com/problems/transpose-matrix/discuss/2100176/Python-One-line-solution
class Solution: def transpose(self, matrix: List[List[int]]) -> List[List[int]]: return zip(*matrix)
transpose-matrix
Python - One line solution
dayaniravi123
0
9
transpose matrix
867
0.635
Easy
14,101
https://leetcode.com/problems/transpose-matrix/discuss/1896460/Python-one-liner-with-memory-less-than-94
class Solution: def transpose(self, matrix: List[List[int]]) -> List[List[int]]: return zip(*matrix)
transpose-matrix
Python one liner with memory less than 94%
alishak1999
0
60
transpose matrix
867
0.635
Easy
14,102
https://leetcode.com/problems/transpose-matrix/discuss/1833570/2-Lines-Python-Solution-oror-60-Faster-oror-Memory-less-than-75
class Solution: def transpose(self, M: List[List[int]]) -> List[List[int]]: TM=[] for i in range(len(M[0])): res=[] for j in range(len(M)): res+=[M[j][i]] TM.append(res) return TM
transpose-matrix
2-Lines Python Solution || 60% Faster || Memory less than 75%
Taha-C
0
60
transpose matrix
867
0.635
Easy
14,103
https://leetcode.com/problems/transpose-matrix/discuss/1833570/2-Lines-Python-Solution-oror-60-Faster-oror-Memory-less-than-75
class Solution: def transpose(self, M: List[List[int]]) -> List[List[int]]: import numpy as np return np.array(M).transpose()
transpose-matrix
2-Lines Python Solution || 60% Faster || Memory less than 75%
Taha-C
0
60
transpose matrix
867
0.635
Easy
14,104
https://leetcode.com/problems/transpose-matrix/discuss/1743684/Solution-using-python3
class Solution: def transpose(self, matrix: List[List[int]]) -> List[List[int]]: ans = [] for i in range(len(matrix[0])) : level = [] for j in range(len(matrix)): level.append(matrix[j][i]) ans.append(level) return ans
transpose-matrix
Solution using python3
shakilbabu
0
30
transpose matrix
867
0.635
Easy
14,105
https://leetcode.com/problems/transpose-matrix/discuss/1428180/python-simple-solution
class Solution: def transpose(self, matrix: List[List[int]]) -> List[List[int]]: n, m = len(matrix), len(matrix[0]) transposed = [[None] * n for _ in range(m)] for i, j in product(range(n), range(m)): transposed[j][i] = matrix[i][j] return transposed
transpose-matrix
[python] simple solution
moorissa
0
163
transpose matrix
867
0.635
Easy
14,106
https://leetcode.com/problems/transpose-matrix/discuss/1200510/1-Line-Simple-Python-Solution-or-Beats-96
class Solution: def transpose(self, matrix: List[List[int]]) -> List[List[int]]: return [[matrix[j][i] for j in range(len(matrix))] for i in range(len(matrix[0]))]
transpose-matrix
1 Line Simple Python Solution | Beats 96%
ekagrashukla
0
141
transpose matrix
867
0.635
Easy
14,107
https://leetcode.com/problems/transpose-matrix/discuss/1082334/Python3-simple-solution
class Solution: def transpose(self, matrix: List[List[int]]) -> List[List[int]]: l = [] for i in zip(*matrix): l.append(list(i)) return l
transpose-matrix
Python3 simple solution
EklavyaJoshi
0
99
transpose matrix
867
0.635
Easy
14,108
https://leetcode.com/problems/transpose-matrix/discuss/920094/O(n*m)-No-SumZip-Methods
class Solution: def transpose(self, A: List[List[int]]) -> List[List[int]]: n = len(A) m = len(A[0]) mat = [[0 for i in range(n)] for j in range(m)] for i in range(m): for j in range(n): mat[i][j] = A[j][i] return mat
transpose-matrix
O(n*m) - No Sum/Zip Methods
JuanTheDoggo
0
99
transpose matrix
867
0.635
Easy
14,109
https://leetcode.com/problems/transpose-matrix/discuss/763591/Python-or-One-liner-solution
class Solution: def transpose(self, A: List[List[int]]) -> List[List[int]]: A = list(map(list, zip(*A))) return A
transpose-matrix
Python | One liner solution
geekypandey
0
186
transpose matrix
867
0.635
Easy
14,110
https://leetcode.com/problems/binary-gap/discuss/1306246/Easy-Python-Solution(100)
class Solution: def binaryGap(self, n: int) -> int: if(bin(n).count('1'))==1: return 0 c=0 x=bin(n)[2:] for i in range(len(x)): if(x[i]=='1'): j=i+1 while j<len(x): if(x[j]=='1'): c=max(j-i,c) break j+=1 return c
binary-gap
Easy Python Solution(100%)
Sneh17029
2
204
binary gap
868
0.619
Easy
14,111
https://leetcode.com/problems/binary-gap/discuss/2790637/Python-Simple-Solution-II-O(n)-oror-One-Pass
class Solution: def binaryGap(self, n: int) -> int: binary = bin(n) binary= binary[2:] found = False max_count =0 for i in range(len(binary)): if(binary[i]=='1' and found ==False): start= i found = True elif(binary[i]=='1' and found==True): count = i- start start= i if(count>max_count): max_count= count return max_count
binary-gap
Python Simple Solution II O(n) || One Pass
hasan2599
1
55
binary gap
868
0.619
Easy
14,112
https://leetcode.com/problems/binary-gap/discuss/2836093/python-easy
class Solution: def binaryGap(self, n: int) -> int: t=bin(n).replace('0b','') if t.count('1')<2: m= 0 else: r=[] for i in range(len(t)): if t[i] == '1': r+=[i] m=abs(r[0]-r[1]) for i in range(1,len(r)-1): if m < abs(r[i]-r[i+1]): m=abs(r[i]-r[i+1]) return m
binary-gap
python easy
sarvajnya_18
0
2
binary gap
868
0.619
Easy
14,113
https://leetcode.com/problems/binary-gap/discuss/2817866/Python-Easy
class Solution: def binaryGap(self, n: int) -> int: max_ = 0 num = str(bin(n)[2:]) for i in range(len(num)): for j in range(i + 1, len(num)): if num[i] == "1" and num[j] == "1": max_ = max(max_, j - i) break return max_
binary-gap
Python Easy
lucasschnee
0
4
binary gap
868
0.619
Easy
14,114
https://leetcode.com/problems/binary-gap/discuss/2703499/Simple-Python-solution
class Solution: def binaryGap(self, n: int) -> int: l = [] ans = 0 s = bin(n)[2:] for i in range(len(s)): if s[i] == '1': l.append(i) if len(l)<=1: return 0 if len(l)==2: return l[-1]-l[0] for i in range(1,len(l)): ans = max(ans, l[i]-l[i-1]) return ans
binary-gap
Simple Python solution
imkprakash
0
15
binary gap
868
0.619
Easy
14,115
https://leetcode.com/problems/binary-gap/discuss/2548098/96.36-memory-efficient-using-two-pointer-approach-in-Python
class Solution: def binaryGap(self, n: int) -> int: l, r = 0, 1 nb = bin(n).replace("0b", "") res = 0 while r < len(nb): if nb[l] == '1' and nb[r] == '1': res = max(res, r - l) l = r r += 1 else: r += 1 return res
binary-gap
96.36% memory efficient using two pointer approach in Python
ankurbhambri
0
25
binary gap
868
0.619
Easy
14,116
https://leetcode.com/problems/binary-gap/discuss/2539052/Python-Solution-or-O(logn)-or-Easy-to-Understand
class Solution: def binaryGap(self, n: int) -> int: res = count = 0 while n > 0: if n &amp; 1: res = max(res, count) count = 1 elif count: count += 1 n >>= 1 return res
binary-gap
Python Solution | O(logn) | Easy to Understand
vparandwal042
0
18
binary gap
868
0.619
Easy
14,117
https://leetcode.com/problems/binary-gap/discuss/2037811/Python-Clean-and-Simple!-Bit-Manipulation
class Solution: def binaryGap(self, n): gap = maxGap = -inf while n: gap += 1 if n &amp; 1: maxGap = max(gap, maxGap) gap = 0 n >>= 1 return maxGap if maxGap > 0 else 0
binary-gap
Python - Clean and Simple! Bit Manipulation
domthedeveloper
0
102
binary gap
868
0.619
Easy
14,118
https://leetcode.com/problems/binary-gap/discuss/1853742/PYTHON-BITMASKING-step-by-step-(34ms)
class Solution: def binaryGap(self, n: int) -> int: #Bit mask mask = 1; #Max streak and streak default to zero maxStreak = 0; streak = 0; #Burn through all of the rightmost zeroes #Keep bitshifting n to the right #As long as the rightmost bit is not 1 ( which means its even) while n > 0 and n % 2 != 1: n = n >> 1; #Then we can begin finding our distances while n > 0: #Each iteration, we see if the rightmost bit is 1 isOne = ( mask &amp; n ) == 1; #If it is, we update our max if isOne: maxStreak = max( maxStreak, streak ); #And then increment the streak streak = 1; #If it is a zero, we increment the streak else: streak += 1; #Each time, we bitshift right n = n >> 1; #Note, we will always end at a valid 1 as leading zeros are not #processed and we stop when n == 0 return maxStreak;
binary-gap
PYTHON BITMASKING step-by-step (34ms)
greg_savage
0
21
binary gap
868
0.619
Easy
14,119
https://leetcode.com/problems/binary-gap/discuss/1842188/2-Lines-Python-Solution-oror-50-Faster-oror-Memory-less-than-75
class Solution: def binaryGap(self, n: int) -> int: n=bin(n)[2:] ; L=sorted([i for i,v in enumerate(n) if v=="1"]) return max([L[i+1]-L[i] for i in range(len(L)-1)] or [0])
binary-gap
2-Lines Python Solution || 50% Faster || Memory less than 75%
Taha-C
0
60
binary gap
868
0.619
Easy
14,120
https://leetcode.com/problems/binary-gap/discuss/1555551/Python-Easy-Solution-or-Faster-than-98
class Solution: def binaryGap(self, n: int) -> int: flag = 0 maxDis = 0 dis = 0 while n > 0: if n &amp; 1: flag = 1 maxDis = max(maxDis, dis) dis = 1 elif flag == 1: dis += 1 n >>= 1 return maxDis
binary-gap
Python Easy Solution | Faster than 98%
leet_satyam
0
123
binary gap
868
0.619
Easy
14,121
https://leetcode.com/problems/binary-gap/discuss/1489350/Python-O(logN)-time-O(1)-space
class Solution: def binaryGap(self, n: int) -> int: while n %2 ==0: n = n //2 if n ==1: return 0 # at least two 1's mind = 0 prev = 0 s = 0 while n > 1: n = n //2 s += 1 if n %2 == 1: mind = max(mind, s-prev) prev = s mind = max(mind, s-prev) return mind
binary-gap
Python O(logN) time, O(1) space
byuns9334
0
92
binary gap
868
0.619
Easy
14,122
https://leetcode.com/problems/binary-gap/discuss/1409971/Python3-Faster-Than-83.03-Memory-Less-Than-90.91
class Solution: def binaryGap(self, n: int) -> int: s, mx, v = bin(n)[2:], 0, [] for i in range(len(s)): if s[i] == '1': v.append(i) for i in range(len(v) - 1): mx = max(mx, v[i + 1] - v[i]) return mx
binary-gap
Python3 Faster Than 83.03%, Memory Less Than 90.91%
Hejita
0
59
binary gap
868
0.619
Easy
14,123
https://leetcode.com/problems/binary-gap/discuss/1351054/Python-easy-solution-without-strings
class Solution: def binaryGap(self, n: int) -> int: gap = cur = 0 while n > 0: if n &amp; 1: gap = max(gap, cur) cur = 1 elif cur: cur += 1 n >>= 1 return gap
binary-gap
Python, easy solution without strings
MihailP
0
121
binary gap
868
0.619
Easy
14,124
https://leetcode.com/problems/binary-gap/discuss/1343913/Python3-dollarolution(98-better-memory-usage-slow-tho)
class Solution: def binaryGap(self, n: int) -> int: n = bin(n)[2:] m, v = 0, [] for i in range(len(n)): if n[i] == '1': v.append(i) if len(v) > 1: x = v[-1] - v[-2] if m < x: m = x return m
binary-gap
Python3 $olution(98% better memory usage, slow tho)
AakRay
0
69
binary gap
868
0.619
Easy
14,125
https://leetcode.com/problems/binary-gap/discuss/1244325/Python-Brute-Force
class Solution: def binaryGap(self, n: int) -> int: if n <= 2: return 0 else: converted_binary = bin(n)[2:] binaryGap = 0 firstSpot = False secondSpot = False maxBinaryGap = 1 for i in converted_binary: if i == '1': if firstSpot: maxBinaryGap = max(maxBinaryGap, binaryGap) binaryGap = 1 firstSpot = True secondSpot = True else: firstSpot = True binaryGap += 1 elif firstSpot: binaryGap += 1 if secondSpot: return maxBinaryGap else: return 0
binary-gap
Python Brute Force
dee7
0
47
binary gap
868
0.619
Easy
14,126
https://leetcode.com/problems/binary-gap/discuss/1185172/python-3-easy-solution
class Solution: def binaryGap(self, n: int) -> int: nums=list(map(int,bin(n)[2:])) res=[] for i in range(len(nums)): if nums[i]==1: res.append(i) for i in range(len(res)-1): res[i]=res[i+1]-res[i] if len(res)>1: return max(res[:-1]) else: return 0
binary-gap
python 3 easy solution
janhaviborde23
0
53
binary gap
868
0.619
Easy
14,127
https://leetcode.com/problems/binary-gap/discuss/1089409/Python3-simple-solution
class Solution: def binaryGap(self, n: int) -> int: x = bin(n).replace('0b','') l = [] for i in range(len(x)): if x[i] == '1': l.append(i) if len(l) >= 2: max = 0 for i in range(len(l)-1): z = l[i+1]-l[i] if z > max: max = z return max else: return 0
binary-gap
Python3 simple solution
EklavyaJoshi
0
67
binary gap
868
0.619
Easy
14,128
https://leetcode.com/problems/binary-gap/discuss/642077/O(N)
class Solution: def binaryGap(self, N: int) -> int: s = str("{0:b}".format(N)) l = len(s) d = m = 0 start = False for i in range(l): if s[i] == '1': start = True m = max(m, d) d = 0 if start: d += 1 return m
binary-gap
O(N)
seunggabi
0
32
binary gap
868
0.619
Easy
14,129
https://leetcode.com/problems/binary-gap/discuss/381792/Solution-in-Python-3-(one-line)
class Solution: def binaryGap(self, n: int) -> int: return max((lambda x: [x[i+1]-x[i] for i in range(len(x)-1)])([i for i,j in enumerate(bin(n)) if j == '1']), default = 0) - Junaid Mansuri (LeetCode ID)@hotmail.com
binary-gap
Solution in Python 3 (one line)
junaidmansuri
-1
176
binary gap
868
0.619
Easy
14,130
https://leetcode.com/problems/reordered-power-of-2/discuss/2485025/python-short-and-precise-answer
class Solution: def reorderedPowerOf2(self, n: int) -> bool: for i in range(32): if Counter(str(n))==Counter(str(2**i)): return True return False
reordered-power-of-2
python short and precise answer
benon
3
90
reordered power of 2
869
0.639
Medium
14,131
https://leetcode.com/problems/reordered-power-of-2/discuss/2481061/python3-or-easy-understanding-or-sort
class Solution: def reorderedPowerOf2(self, n: int) -> bool: i, arr = 0, [] v = 2**i while v <= 10**9: arr.append(sorted(str(v))); i+=1; v = 2**i return sorted(str(n)) in arr
reordered-power-of-2
python3 | easy understanding | sort
H-R-S
3
541
reordered power of 2
869
0.639
Medium
14,132
https://leetcode.com/problems/reordered-power-of-2/discuss/2482867/Python-Simple-Python-Solution-Using-Two-Different-Approach
class Solution: def reorderedPowerOf2(self, n: int) -> bool: all_permutations = [] for single_number in itertools.permutations(str(n)): if single_number[0] != '0': num = int(''.join(single_number)) all_permutations.append(num) for i in range(32): if 2**i in all_permutations: return True return False
reordered-power-of-2
[ Python ] ✅✅ Simple Python Solution Using Two Different Approach 🥳✌👍
ASHOK_KUMAR_MEGHVANSHI
2
120
reordered power of 2
869
0.639
Medium
14,133
https://leetcode.com/problems/reordered-power-of-2/discuss/2482867/Python-Simple-Python-Solution-Using-Two-Different-Approach
class Solution: def reorderedPowerOf2(self, n: int) -> bool: num = sorted(str(n)) for i in range(32): current_num = sorted(str(2**i)) if num == current_num: return True return False
reordered-power-of-2
[ Python ] ✅✅ Simple Python Solution Using Two Different Approach 🥳✌👍
ASHOK_KUMAR_MEGHVANSHI
2
120
reordered power of 2
869
0.639
Medium
14,134
https://leetcode.com/problems/reordered-power-of-2/discuss/1120038/python-o64(o1)-hashmap-solution
class Solution: def helper(self,num): char_arr = str(num) table = dict() for char in char_arr: if char not in table: table[char] = 1 else: table[char] += 1 return table def reorderedPowerOf2(self, N: int) -> bool: num_tab = self.helper(N) i = 0 while i < 64: if num_tab == self.helper(pow(2,i)): return True else: i += 1 return False
reordered-power-of-2
python o64(o1) hashmap solution
yingziqing123
2
199
reordered power of 2
869
0.639
Medium
14,135
https://leetcode.com/problems/reordered-power-of-2/discuss/2483557/Python-oror-O(log(n))-time-O(1)-space-oror-Faster-than-100-oror-Explained-and-compared
class Solution: def reorderedPowerOf2(self, n: int) -> bool: # Step #1: Get the digits of `n` and sort them # - Time: O(log(n)*log(log(n))) # - Space: O(log(n)) nStr = str(n) numDigits, sortedDigits = len(nStr), sorted(nStr) # Step #2: Identify the smallest power of 2 that has the same number of digits as `n` # - Time: O(log(n)) # - Space: O(1) minTargetValue = 10 ** (numDigits - 1) powerOf2 = 1 << ceil(log2(minTargetValue)) # Step #3: Out of the powers of 2 that have the same number of digits as `n` (there are maximum four), check if any has the same digits as `n` # For this, we sort the digits and compare to the ones from step #1 # - Time: O(log(n)*log(log(n))) # - Space: O(log(n)) maxTargetValue = 10 * minTargetValue - 1 while powerOf2 <= maxTargetValue: powerOf2Str = str(powerOf2) if sorted(powerOf2Str) == sortedDigits: return True powerOf2 <<= 1 return False
reordered-power-of-2
Python || O(log(n)) time, O(1) space || Faster than 100% || Explained and compared
RegInt
1
115
reordered power of 2
869
0.639
Medium
14,136
https://leetcode.com/problems/reordered-power-of-2/discuss/1339767/python3-Simple-solution-O(log-n)-82-faster
class Solution: def reorderedPowerOf2(self, n: int) -> bool: i = 0 ele = int(''.join(sorted(str(n), reverse=True))) # sort the number in descending order while 2**i <= ele: ele1 = int(''.join(sorted(str(2**i), reverse=True))) if ele1 == ele:return True i += 1 return False
reordered-power-of-2
[python3] Simple solution - O(log n) - 82% faster
Rahul-Krishna
1
143
reordered power of 2
869
0.639
Medium
14,137
https://leetcode.com/problems/reordered-power-of-2/discuss/994712/Python3-enumerate-power-of-2
class Solution: def reorderedPowerOf2(self, N: int) -> bool: ss = str(N) cnt = Counter(ss) k, n = 1, len(ss) while k < 10**n: if k >= 10**(n-1) and Counter(str(k)) == cnt: return True k <<= 1 return False
reordered-power-of-2
[Python3] enumerate power of 2
ye15
1
161
reordered power of 2
869
0.639
Medium
14,138
https://leetcode.com/problems/reordered-power-of-2/discuss/994712/Python3-enumerate-power-of-2
class Solution: def reorderedPowerOf2(self, N: int) -> bool: return any(Counter(str(N)) == Counter(str(1 << i)) for i in range(30))
reordered-power-of-2
[Python3] enumerate power of 2
ye15
1
161
reordered power of 2
869
0.639
Medium
14,139
https://leetcode.com/problems/reordered-power-of-2/discuss/2775309/Python-or-Beats-80-or-Super-easy-or-No-bit-manipulation
class Solution: def reorderedPowerOf2(self, n: int) -> bool: sorted_N_str = sorted(str(n)) maximum = 10 ** 9 i = 1 while i <= maximum: sorted_i_str = sorted(str(i)) if sorted_i_str == sorted_N_str: return True i = i * 2 return False
reordered-power-of-2
Python | Beats 80% | Super easy | No bit manipulation
SpaceJamz
0
4
reordered power of 2
869
0.639
Medium
14,140
https://leetcode.com/problems/reordered-power-of-2/discuss/2503077/Simple-Python-Solution
class Solution: def reorderedPowerOf2(self, n: int) -> bool: map_powerof2 = [[]] countdig_n=[0]*10 k=n while(k): dig=k%10 countdig_n[dig] = countdig_n[dig]+1 k=k//10 i=1 while(i<=10**9): temp=[0]*10 k=i while(k): dig=k%10 temp[dig]=temp[dig]+1 k=k//10 map_powerof2.append(temp) i=i*2 for lst in map_powerof2: if lst == countdig_n: return True return False
reordered-power-of-2
Simple Python Solution
miyachan
0
20
reordered power of 2
869
0.639
Medium
14,141
https://leetcode.com/problems/reordered-power-of-2/discuss/2494410/Python-Easy-5-Lines-Beats-9x-Memory-and-Speed
class Solution: def reorderedPowerOf2(self, n: int) -> bool: k = 1 while k <= 8 * n: if sorted(str(k)) == sorted(str(n)): return True k *= 2 return False
reordered-power-of-2
✔️Python, Easy, 5 Lines, Beats 9x% Memory and Speed
bylin
0
23
reordered power of 2
869
0.639
Medium
14,142
https://leetcode.com/problems/reordered-power-of-2/discuss/2488508/Python-Solution-100-EXPLAINED-SOLUTION
class Solution: def reorderedPowerOf2(self, n: int) -> bool: #any power of 2 can not be 0 (2**n != 0) so return false if n==0: return False #counting all digits of n (by this we can check the permutations #i.e, if any reordering can be power of two or not) a= digits(n) #loop is till 0-29 numbers(means n can lie between 0 to 29 only) bcoz constrains are 10**9 (i.e, only #result of 2**n can be 10 digits long so 10**30 > 10**9 (check from google) and 10**9 >= 10**29 ) for i in range(0,30): #checking total digits in power of 2 and comparing with total digits given in original n (stored in a) #if both array will get equal then return true if digits(2**i)==a: return True #if no power of 2 satisfy the above condition then false means no reordering can give the power of 2 return False #this function is made for counting digits in a number and returning the array after #storing the count of digits in an array (having 0-9 index) def digits(n): array=[0]*10 #having 0-9 index in an array so having length 10 #(if digit not present in number then it is initialised with 0 already) while(n>0): array[n%10]+=1 n=n//10 return array
reordered-power-of-2
Python Solution - 100% EXPLAINED SOLUTION ✔
T1n1_B0x1
0
6
reordered power of 2
869
0.639
Medium
14,143
https://leetcode.com/problems/reordered-power-of-2/discuss/2485588/Python3-100-Solution-(Optimization-Overkill)
class Solution: def reorderedPowerOf2(self, n: int) -> bool: possible_answers = ('1', '2', '4', '8', '16', '23', '46', '128', '256', '125', '0124', '0248', '0469', '1289', '13468', '23678', '35566', '011237', '122446', '224588', '0145678', '0122579', '0134449', '0368888', '11266777', '23334455', '01466788', '112234778', '234455668', '012356789') if "".join(sorted(list(str(n)))) in possible_answers: return True else: return False
reordered-power-of-2
Python3 100% Solution (Optimization Overkill)
drocko
0
5
reordered power of 2
869
0.639
Medium
14,144
https://leetcode.com/problems/reordered-power-of-2/discuss/2485516/Python3-100-Solution-(with-intuition-explanation)
class Solution: def reorderedPowerOf2(self, n: int) -> bool: def SortNumber(val): val_list = list(str(val)) val_list.sort() val_sorted ="".join(val_list) return val_sorted possible_answers = (1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536, 131072, 262144, 524288, 1048576, 2097152, 4194304, 8388608, 16777216, 33554432, 67108864, 134217728, 268435456, 536870912) # Alternative // possible_answers = (2 ** i for i in range(30)) filtered = [] for answer in possible_answers: if len(str(answer)) == len(str(n)): filtered.append(SortNumber(answer)) if SortNumber(n) in filtered: return True else: return False
reordered-power-of-2
Python3 100% Solution (with intuition explanation)
drocko
0
5
reordered power of 2
869
0.639
Medium
14,145
https://leetcode.com/problems/reordered-power-of-2/discuss/2484837/Python-Simple-and-Short-Solution-oror-Documented
class Solution: def reorderedPowerOf2(self, n: int) -> bool: strN = str(n) # string of n nCounter = collections.Counter(strN) # frequency counter of string n for i in range(30): # Limit 10^9 (1000000000) < 2^30 (1073741824) power = str(2**i) # find power of i # if the length and frequency of digits appearing are same, return True if len(power) == len(strN) and nCounter == Counter(power): return True return False
reordered-power-of-2
[Python] Simple and Short Solution || Documented
Buntynara
0
1
reordered power of 2
869
0.639
Medium
14,146
https://leetcode.com/problems/reordered-power-of-2/discuss/2484769/Beats-100-in-space-comp.
class Solution: def reorderedPowerOf2(self, n: int) -> bool: return sorted(str(n)) in [sorted(str(1 << i)) for i in range(30)]
reordered-power-of-2
Beats 100% in space comp.
sayantanmaji2001
0
8
reordered power of 2
869
0.639
Medium
14,147
https://leetcode.com/problems/reordered-power-of-2/discuss/2483629/Python-oror-faster-than-99-oror-simple-and-easy
class Solution: def reorderedPowerOf2(self, n: int) -> bool: two_mul_digit_counts = [ {1: 1}, {2: 1}, {4: 1}, {8: 1}, {6: 1, 1: 1}, {2: 1, 3: 1}, {4: 1, 6: 1}, {8: 1, 2: 1, 1: 1}, {6: 1, 5: 1, 2: 1}, {2: 1, 1: 1, 5: 1}, {4: 1, 2: 1, 0: 1, 1: 1}, {8: 1, 4: 1, 0: 1, 2: 1}, {6: 1, 9: 1, 0: 1, 4: 1}, {2: 1, 9: 1, 1: 1, 8: 1}, {4: 1, 8: 1, 3: 1, 6: 1, 1: 1}, {8: 1, 6: 1, 7: 1, 2: 1, 3: 1}, {6: 2, 3: 1, 5: 2}, {2: 1, 7: 1, 0: 1, 1: 2, 3: 1}, {4: 2, 1: 1, 2: 2, 6: 1}, {8: 2, 2: 2, 4: 1, 5: 1}, {6: 1, 7: 1, 5: 1, 8: 1, 4: 1, 0: 1, 1: 1}, {2: 2, 5: 1, 1: 1, 7: 1, 9: 1, 0: 1}, {4: 3, 0: 1, 3: 1, 9: 1, 1: 1}, {8: 4, 0: 1, 6: 1, 3: 1}, {6: 2, 1: 2, 2: 1, 7: 3}, {2: 1, 3: 3, 4: 2, 5: 2}, {4: 1, 6: 2, 8: 2, 0: 1, 1: 1, 7: 1}, {8: 1, 2: 2, 7: 2, 1: 2, 4: 1, 3: 1}, {6: 2, 5: 2, 4: 2, 3: 1, 8: 1, 2: 1}, {2: 1, 1: 1, 9: 1, 0: 1, 7: 1, 8: 1, 6: 1, 3: 1, 5: 1}, ] digit_count = {} while n > 0: if (n % 10) not in digit_count: digit_count[n % 10] = 0 digit_count[n % 10] += 1 n = n // 10 for i in two_mul_digit_counts: if digit_count == i: return True return False
reordered-power-of-2
Python || faster than 99% 🔥 || simple and easy ✅
wilspi
0
37
reordered power of 2
869
0.639
Medium
14,148
https://leetcode.com/problems/reordered-power-of-2/discuss/2483146/Python3-or-90-faster-or-counting-or-assert
class Solution: def reorderedPowerOf2(self, n: int) -> bool: pof2_list = [x for x in [2 ** x for x in range(35)] if x < 1000000000] pof2_filtered_list = [x for x in pof2_list if len(str(x)) == len(str(n))] for el in pof2_filtered_list: el_q, n_q = sorted(list(str(el))), sorted(list(str(n))) count = 0 while n_q: if n_q[-1] == el_q[-1]: el_q.pop() n_q.pop() count += 1 else: break if count == len(str(el)): return True return False # arg = 1 # assert Solution().reorderedPowerOf2(arg) == True, '1' # arg = 10 # assert Solution().reorderedPowerOf2(arg) == False, '2' # arg = 536870912 # assert Solution().reorderedPowerOf2(arg) == True, '3' # arg = 536870911 # assert Solution().reorderedPowerOf2(arg) == False, '4'
reordered-power-of-2
Python3 | 90% faster | counting | assert
Sergei_Gusev
0
4
reordered power of 2
869
0.639
Medium
14,149
https://leetcode.com/problems/reordered-power-of-2/discuss/2482645/100-python3-solution(Optimized)
class Solution: # O(m) time, m --> number of digits in n # O(m) space, # Approach: hashtable, def reorderedPowerOf2(self, n: int) -> bool: str_n = str(n) n_count = Counter(str_n) start_exp = math.log((10**(len(str_n)-1)), 2) start_exp = int(math.ceil(start_exp)) end_exp = math.log((10**(len(str_n))), 2) end_exp = int(math.ceil(end_exp)) # print(start_exp, end_exp) for exp in range(start_exp, end_exp): num = (2**exp) num_count = Counter(str(num)) if n_count == num_count: return True return False
reordered-power-of-2
100% python3 solution(Optimized)
destifo
0
10
reordered power of 2
869
0.639
Medium
14,150
https://leetcode.com/problems/reordered-power-of-2/discuss/2482614/Python-or-Faster-than-99
class Solution: def reorderedPowerOf2(self, n: int) -> bool: counter_number = Counter(str(n)) i = 1 iteration = 0 while iteration <= 30: iteration += 1 tmp_i = str(i) counter_tmp = Counter(tmp_i) if counter_tmp == counter_number: return True i *= 2 return False
reordered-power-of-2
Python | Faster than 99%
pivovar3al
0
21
reordered power of 2
869
0.639
Medium
14,151
https://leetcode.com/problems/reordered-power-of-2/discuss/2482485/869.-Reordered-Power-of-2
class Solution: def reorderedPowerOf2(self, n: int) -> bool: def sos(n1): return sorted(list(n1)) n1=str(n) s1=sos(n1) for i in range(0,32): a=str(2**i) if sos(a)==s1: if len(a)==len(n1): return True return False
reordered-power-of-2
869. Reordered Power of 2
Revanth_Yanduru
0
14
reordered power of 2
869
0.639
Medium
14,152
https://leetcode.com/problems/reordered-power-of-2/discuss/2481816/Python-easy-solution-for-beginners-using-permutations
class Solution: def reorderedPowerOf2(self, n: int) -> bool: perms = [''.join(x) for x in permutations(str(n))] for i in perms: if i[0] != '0': if math.ceil(math.log10(int(i))/math.log10(2)) == math.floor(math.log10(int(i))/math.log10(2)): return True return False
reordered-power-of-2
Python easy solution for beginners using permutations
alishak1999
0
13
reordered power of 2
869
0.639
Medium
14,153
https://leetcode.com/problems/reordered-power-of-2/discuss/2481765/Python-Easy-Understanding
class Solution: def reorderedPowerOf2(self, n: int) -> bool: i, arr = 0, [] v = 2**i while v <= 10**9: arr.append(sorted(str(v))); i+=1; v = 2**i return sorted(str(n)) in arr
reordered-power-of-2
Python Easy Understanding
creativerahuly
0
19
reordered power of 2
869
0.639
Medium
14,154
https://leetcode.com/problems/reordered-power-of-2/discuss/2481630/Python3-One-line-solution
class Solution: def reorderedPowerOf2(self, n: int) -> bool: return any(Counter(str(n)) == Counter(str(1 << d)) for d in range(31))
reordered-power-of-2
[Python3] One line solution
geka32
0
22
reordered power of 2
869
0.639
Medium
14,155
https://leetcode.com/problems/reordered-power-of-2/discuss/2481508/Python3-Optimal-Solution-oror-Faster-than-89.95-oror-Clean-and-Short-Solution
class Solution: def reorderedPowerOf2(self, n: int) -> bool: count = Counter(str(n)) return any(Counter(str(1 << i)) == count for i in range(30))
reordered-power-of-2
[Python3] Optimal Solution || Faster than 89.95% || Clean and Short Solution
WhiteBeardPirate
0
16
reordered power of 2
869
0.639
Medium
14,156
https://leetcode.com/problems/reordered-power-of-2/discuss/2481122/python-100fast-answer(use-dict)
class Solution: def reorderedPowerOf2(self, n: int) -> bool: def make_dic(x): dic = {} while x: tmp = x % 10 if tmp in dic:dic[tmp] += 1 else: dic[tmp] = 1 x //= 10 return dic if n == 1:return True dic_n = make_dic(n) x = 2 n_l = len(str(n)) while x < 1000000000: x_l = len(str(x)) if x_l == n_l: # because it's impossible equal if different length if dic_n == make_dic(x):return True elif x_l > n_l : return False x *= 2 return False
reordered-power-of-2
python 100%fast answer(use dict)
TUL
0
36
reordered power of 2
869
0.639
Medium
14,157
https://leetcode.com/problems/reordered-power-of-2/discuss/1204851/Python-fast(98%2B)-and-pythonic
class Solution: def reorderedPowerOf2(self, n: int) -> bool: powers_of_two = { 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536, 131072, 262144, 524288, 1048576, 2097152, 4194304, 8388608, 16777216, 33554432, 67108864, 134217728, 268435456, 536870912 } candidates = [i for i in powers_of_two if len(str(i)) == len(str(n))] def _counter(s): digit_counter = {} for i in str(s): digit_counter[i] = digit_counter.get(i, 0) + 1 return digit_counter if candidates: number = _counter(n) for candidate in candidates: if _counter(candidate) == number: return True return False
reordered-power-of-2
[Python] fast(98+) and pythonic
cruim
0
104
reordered power of 2
869
0.639
Medium
14,158
https://leetcode.com/problems/reordered-power-of-2/discuss/1121843/Intuitive-approach-by-exhaustive-method
class Solution: def __init__(self): self.p2_set = set() for i in range(35): num = pow(2, i) self.p2_set.add(self.num2dig(num)) def num2dig(self, num): return tuple(sorted(list(str(num)))) def reorderedPowerOf2(self, N: int) -> bool: return self.num2dig(N) in self.p2_set
reordered-power-of-2
Intuitive approach by exhaustive method
puremonkey2001
0
31
reordered power of 2
869
0.639
Medium
14,159
https://leetcode.com/problems/reordered-power-of-2/discuss/1121268/Optimized-Permutations-Solution.
class Solution: def reorderedPowerOf2(self, N: int) -> bool: toStr=str(N) permutations=[[]] for p in toStr: tmp=[] for perm in permutations: for i in range(len(perm)+1): value=perm[:i]+[p]+perm[i:] if value[0] != "0" and len(value)==len(toStr): check=int("".join(value)) check=math.log10(check) /math.log10(2) if check == int(check): return True tmp.append(value) if i < len(perm) and perm[i]==p: break permutations=tmp
reordered-power-of-2
Optimized Permutations Solution.
hasham
0
48
reordered power of 2
869
0.639
Medium
14,160
https://leetcode.com/problems/reordered-power-of-2/discuss/527536/Python3-simple-set-solution
class Solution: def reorderedPowerOf2(self, N: int) -> bool: pows = set() for i in range(32): num = 1 << i if num > 10**9: break pows.add(self.get_digits(num)) return self.get_digits(N) in pows @classmethod def get_digits(cls, number: int) -> int: digit = 0 while number != 0: digit += 10 ** (number % 10) number //= 10 return digit
reordered-power-of-2
Python3 simple set solution
tjucoder
0
136
reordered power of 2
869
0.639
Medium
14,161
https://leetcode.com/problems/reordered-power-of-2/discuss/515650/Boring-python-solution
class Solution: def reorderedPowerOf2(self, N: int) -> bool: ans= [['1'], ['2'], ['4'], ['8'], ['1', '6'], ['2', '3'], ['4', '6'], ['1', '2', '8'], ['2', '5', '6'], ['1', '2', '5'], ['0', '1', '2', '4'], ['0', '2', '4', '8'], ['0', '4', '6', '9'], ['1', '2', '8', '9'], ['1', '3', '4', '6', '8'], ['2', '3', '6', '7', '8'], ['3', '5', '5', '6', '6'], ['0', '1', '1', '2', '3', '7'], ['1', '2', '2', '4', '4', '6'], ['2', '2', '4', '5', '8', '8'], ['0', '1', '4', '5', '6', '7', '8'], ['0', '1', '2', '2', '5', '7', '9'], ['0', '1', '3', '4', '4', '4', '9'], ['0', '3', '6', '8', '8', '8', '8'], ['1', '1', '2', '6', '6', '7', '7', '7'], ['2', '3', '3', '3', '4', '4', '5', '5'], ['0', '1', '4', '6', '6', '7', '8', '8'], ['1', '1', '2', '2', '3', '4', '7', '7', '8'], ['2', '3', '4', '4', '5', '5', '6', '6', '8'], ['0', '1', '2', '3', '5', '6', '7', '8', '9']] return sorted(str(N)) in ans
reordered-power-of-2
Boring python solution
linHerb
0
117
reordered power of 2
869
0.639
Medium
14,162
https://leetcode.com/problems/reordered-power-of-2/discuss/459353/Python3-simple-solution-using-a-for()-loop
class Solution: def reorderedPowerOf2(self, N: int) -> bool: sn = "".join(sorted(str(N))) for i in range(30): if sn == "".join(sorted(str(2**i))): return True return False
reordered-power-of-2
Python3 simple solution using a for() loop
jb07
0
119
reordered power of 2
869
0.639
Medium
14,163
https://leetcode.com/problems/reordered-power-of-2/discuss/279665/Python3-Solution-without-using-Counter-class
class Solution: def reorderedPowerOf2(self, N: int) -> bool: def str2dict(s): d = {} for i, e in enumerate(s): if e in d: d[e] = d[e] + 1 else: d[e] = 1 return d s = str(N) l = len(s) d = str2dict(s) i = 0 result = False while not result: two_power = 2**i s_two_power = str(two_power) if len(s_two_power) == l: result = str2dict(s_two_power) == d elif len(s_two_power) > l: break i += 1 return result
reordered-power-of-2
Python3 Solution, without using Counter class
KuanHaoHuang
0
142
reordered power of 2
869
0.639
Medium
14,164
https://leetcode.com/problems/advantage-shuffle/discuss/843628/Python-3-or-Greedy-Two-Pointers-or-Explanations
class Solution: def advantageCount(self, A: List[int], B: List[int]) -> List[int]: sorted_a = sorted(A, reverse=True) # descending order sorted_b = sorted(enumerate(B), key=lambda x: (x[1], x[0]), reverse=True) # descending order with original index n, j = len(B), 0 ans = [-1] * n for i, (ori_idx, val) in enumerate(sorted_b): # A greedily tries to cover value in B as large as possible if sorted_a[j] > val: ans[ori_idx], j = sorted_a[j], j+1 for i in range(n): # assign rest value in A to ans if ans[i] == -1: ans[i], j = sorted_a[j], j+1 return ans
advantage-shuffle
Python 3 | Greedy, Two Pointers | Explanations
idontknoooo
3
322
advantage shuffle
870
0.517
Medium
14,165
https://leetcode.com/problems/advantage-shuffle/discuss/2602558/Two-pointer-%2B-Max-Heap-in-Python
class Solution: def advantageCount(self, nums1: List[int], nums2: List[int]) -> List[int]: n = len(nums1) nums2_hq_desc = [] for i, num in enumerate(nums2): # need to negate num to sort in descending order heapq.heappush(nums2_hq_desc, (-num, i)) nums1.sort() res = [0] * n left, right = 0, n-1 # two pointers on the sorted nums1 array while (left <= right): max2 = heapq.heappop(nums2_hq_desc) maxVal2, idx2 = max2 # need to negate again to make num positive maxVal2 = -maxVal2 if (maxVal2 < nums1[right]): # use current num to compete when it's stronger than maxVal2 res[idx2] = nums1[right] right -= 1 else: # use the weakest num to compete when maxVal2 >= nums[right] res[idx2] = nums1[left] left += 1 return res
advantage-shuffle
Two pointer + Max Heap in Python
leqinancy
0
5
advantage shuffle
870
0.517
Medium
14,166
https://leetcode.com/problems/advantage-shuffle/discuss/940919/Python3-greedy-O(NlogN)
class Solution: def advantageCount(self, A: List[int], B: List[int]) -> List[int]: B, key = zip(*sorted(zip(B, list(range(len(B)))))) # sort it ascending adv, rem = [], [] # advantage &amp; remaining i = 0 for x in sorted(A): if x > B[i]: adv.append(x) i += 1 else: rem.append(x) return list(zip(*sorted(zip(key, adv+rem))))[1] # sort it back
advantage-shuffle
[Python3] greedy O(NlogN)
ye15
0
90
advantage shuffle
870
0.517
Medium
14,167
https://leetcode.com/problems/advantage-shuffle/discuss/940919/Python3-greedy-O(NlogN)
class Solution: def advantageCount(self, A: List[int], B: List[int]) -> List[int]: A.sort() take = {} for b in sorted(B, reverse=True): if b < A[-1]: take.setdefault(b, []).append(A.pop()) return [(take.get(b, []) or A).pop() for b in B]
advantage-shuffle
[Python3] greedy O(NlogN)
ye15
0
90
advantage shuffle
870
0.517
Medium
14,168
https://leetcode.com/problems/advantage-shuffle/discuss/940919/Python3-greedy-O(NlogN)
class Solution: def advantageCount(self, A: List[int], B: List[int]) -> List[int]: A.sort() mp = {} for x in sorted(B, reverse=True): if x < A[-1]: mp.setdefault(x, []).append(A.pop()) ans = [] for x in B: if x in mp and mp[x]: ans.append(mp[x].pop()) else: ans.append(A.pop()) return ans
advantage-shuffle
[Python3] greedy O(NlogN)
ye15
0
90
advantage shuffle
870
0.517
Medium
14,169
https://leetcode.com/problems/minimum-number-of-refueling-stops/discuss/2454099/Python3-oror-10-lines-heap-wexplanation-oror-TM%3A-90-98
class Solution: # Here's the plan: # # 1) We only need to be concerned with two quantities: the dist traveled (pos) # and the fuel acquired (fuel). We have to refuel before pos > fuel. # # 2) Because we have an infinite capacity tank, we only have to plan where to acquire # fuel before pos > fuel, and common sense says to stop at the station within range # with the most fuel. # # 3) And that's a job for a heap. we heappush the stations that are within range of present # fuel, and heappop the best choice if and when we need fuel. # # 4) We are finished when a) we have acquired sufficient fuel such that fuel >= target # (return # of fuelings), or b) fuel < target and the heap is empty (return -1). def minRefuelStops(self, target: int, startFuel: int, stations: List[List[int]]) -> int: fuel, heap, count = startFuel, [], 0 # <-- initialize some stuff stations.append([target, 0]) # <-- this handles the "stations = []" test while stations: if fuel >= target: return count # <-- 4) while stations and stations[0][0] <= fuel: # <-- 3) _, liters = stations.pop(0) heappush(heap,-liters) if not heap: return -1 # <-- 4) fuel-= heappop(heap) count+= 1
minimum-number-of-refueling-stops
Python3 || 10 lines, heap, w/explanation || T/M: 90%/ 98%
warrenruud
3
140
minimum number of refueling stops
871
0.398
Hard
14,170
https://leetcode.com/problems/minimum-number-of-refueling-stops/discuss/1268153/py-dp-solution
class Solution: def minRefuelStops(self, target: int, startFuel: int, stations: List[List[int]]) -> int: if not stations: if startFuel >= target: return 0 else: return -1 dp = [0] * (len(stations) + 1) dp[0] = startFuel # utilize index as stop number for i in range(len(stations)): for j in range(i,-1,-1): if dp[j] >= stations[i][0]: dp[j+1] = max(dp[j+1], dp[j] + stations[i][1]) for i in range(len(dp)): if dp[i] >= target: return i return -1
minimum-number-of-refueling-stops
py dp solution
yingziqing123
1
133
minimum number of refueling stops
871
0.398
Hard
14,171
https://leetcode.com/problems/minimum-number-of-refueling-stops/discuss/1267151/PythonPython3-solution-in-DP-and-Greedy
class Solution: def minRefuelStops(self, target: int, startFuel: int, stations: List[List[int]]) -> int: dp = [startFuel]+[0]*len(stations) for i, (loc,cap) in enumerate(stations): for j in range(i,-1,-1): if dp[j] >= loc: dp[j + 1] = max(dp[j+1],dp[j]+cap) for i,val in enumerate(dp): if val >= target: return i return -1
minimum-number-of-refueling-stops
Python/Python3 solution in DP and Greedy
prasanthksp1009
1
339
minimum number of refueling stops
871
0.398
Hard
14,172
https://leetcode.com/problems/minimum-number-of-refueling-stops/discuss/1267151/PythonPython3-solution-in-DP-and-Greedy
class Solution: def minRefuelStops(self, target: int, startFuel: int, stations: List[List[int]]) -> int: priorityQ = [] ans, i = 0, 0 while startFuel < target: while i < len(stations) and stations[i][0] <= startFuel: heapq.heappush(priorityQ,-stations[i][1]) i += 1 if not priorityQ: return -1 startFuel += -heapq.heappop(priorityQ) ans += 1 return ans
minimum-number-of-refueling-stops
Python/Python3 solution in DP and Greedy
prasanthksp1009
1
339
minimum number of refueling stops
871
0.398
Hard
14,173
https://leetcode.com/problems/minimum-number-of-refueling-stops/discuss/1266570/NO-DP..-A-Heap-based-Solution(Python3)
class Solution: def minRefuelStops(self, target: int, start_fuel: int, stations: List[List[int]]) -> int: hp, ans, can_reach = [], 0, start_fuel heapq.heapify(hp) for pos, fuel in stations: if can_reach >= target: return ans elif pos <= can_reach: heapq.heappush(hp, -fuel) else: while len(hp) > 0: bigger = -heapq.heappop(hp) can_reach += bigger ans += 1 if can_reach >= pos: break if can_reach < pos: return -1 heapq.heappush(hp, -fuel) if can_reach >= target: return ans while len(hp) > 0: bigger = -heapq.heappop(hp) can_reach += bigger ans += 1 if can_reach >= target: break if can_reach < target: return -1 return ans
minimum-number-of-refueling-stops
NO DP.. A Heap based Solution(Python3)
chocostick
1
124
minimum number of refueling stops
871
0.398
Hard
14,174
https://leetcode.com/problems/minimum-number-of-refueling-stops/discuss/2466700/Python3-Solution-Easy-to-Understand
class Solution: def minRefuelStops(self, target: int, startFuel: int, stations: List[List[int]]) -> int: # Special easy-to-tell cases if startFuel >= target: return 0 if stations and startFuel < stations[0][0]: return -1 if not stations: if startFuel < target: return -1 else: return 0 # To list idx of all stations sorting with descending fuel amount (there must be better way to do it...) n = len(stations) s = [0] for ii in range(1,n): f = stations[ii][1] l, r = 0, len(s)-1 lf, rf = stations[s[l]][1], stations[s[r]][1] if f >= lf: s.insert(0,ii) elif f <= rf: s.append(ii) else: while r - l > 1: m = (l+r)//2 mf = stations[s[m]][1] if f > mf: r, rf = m, mf elif f < mf: l, lf = m, mf else: r = m s.insert(r, ii) # Start to go through every station from high to low fuel, until reach target rt = 0 fuel = startFuel rest = target dist = 0 crr = -1 while fuel < rest: if not s: return -1 stAvailable = False for ii in range(len(s)): if s[ii] < crr: # the 2nd case mentioned above fuel += stations[s[ii]][1] rt += 1 s.pop(ii) stAvailable = True break if fuel >= stations[s[ii]][0] - dist and s[ii] > crr: # the 1st case mentioned above, the 3rd case will skip this one but go to the 2nd case next loop fuel = fuel - (stations[s[ii]][0] - dist) + stations[s[ii]][1] dist = stations[s[ii]][0] rest = target - dist crr = s.pop(ii) rt += 1 stAvailable = True break if not stAvailable: return -1 return rt
minimum-number-of-refueling-stops
Python3 Solution Easy to Understand
wwwhhh1988
0
15
minimum number of refueling stops
871
0.398
Hard
14,175
https://leetcode.com/problems/minimum-number-of-refueling-stops/discuss/2455064/Easy-solution-with-help-of-heap-and-indexes
class Solution: def minRefuelStops(self, target: int, startFuel: int, stations: List[List[int]]) -> int: count = 0 heap = [] heapify(heap) l,r = 0,bisect_right(stations,startFuel,key=lambda i:i[0]) if(startFuel>=target): return 0 if(r==0): return -1 while(startFuel<target): count+=1 for i in range(l,r): heappush(heap,-1*stations[i][1]) if(len(heap)==0 and startFuel<target): return -1 l = r startFuel+=(heappop(heap)*-1) r = bisect_right(stations,startFuel,key=lambda i:i[0]) if(startFuel<target): return -1 return count
minimum-number-of-refueling-stops
Easy solution with help of heap and indexes
onkarhanchate14
0
8
minimum number of refueling stops
871
0.398
Hard
14,176
https://leetcode.com/problems/minimum-number-of-refueling-stops/discuss/2454874/Python-Beats-99-Faster-Solution-using-MaxHeap-oror-Documented
class Solution: # TC is O(N log N) and SC is O(N) where N = number of stations # Note the negate sign while push and pop in heap, it is need to convert the min-heap to max-heap def minRefuelStops(self, target: int, startFuel: int, stations: List[List[int]]) -> int: max_heap = [] # max heap to store the amount of fuel in prior stations stations.append([target, 0]) # append the destination into stations with 0 fuel available curFuel = startFuel # current fuel in the tank result = 0 # count of refueling prevLoc = 0 # initially previous location/position will be 0 for location, capacity in stations: curFuel -= location - prevLoc # reduce fuel consumed to reach the location from previous one while max_heap and curFuel < 0: # if out of gas, we need to refuel in prior gas stations curFuel += -heapq.heappop(max_heap) # refuel from the one that provides maximum fuel result += 1 # increment count of refueling if curFuel < 0: # if still out of gas after refueling in all prior stations, return -1 # - unable to reach the destination heapq.heappush(max_heap, -capacity) # add amount of fuel available at current location prevLoc = location # mark the previous location, go to next location return result # return count of refueling
minimum-number-of-refueling-stops
[Python] Beats 99% Faster Solution using MaxHeap || Documented
Buntynara
0
8
minimum number of refueling stops
871
0.398
Hard
14,177
https://leetcode.com/problems/minimum-number-of-refueling-stops/discuss/2453165/Python-Accepted
class Solution: def minRefuelStops(self, target: int, startFuel: int, stations: List[List[int]]) -> int: stops = 0 heapq.heapify(stations) fuel_heap = [] distance = startFuel while True: if distance >= target: return stops while stations and distance >= stations[0][0]: heappush(fuel_heap, -heappop(stations)[1]) if not fuel_heap: return -1 distance -= heappop(fuel_heap) stops+=1
minimum-number-of-refueling-stops
Python Accepted ✅
Khacker
0
28
minimum number of refueling stops
871
0.398
Hard
14,178
https://leetcode.com/problems/minimum-number-of-refueling-stops/discuss/2452799/Python-O(n*log(n))-time-or-O-(N)-space
class Solution: def minRefuelStops(self, target: int, startFuel: int, stations: List[List[int]]) -> int: stops = 0 heapq.heapify(stations) fuel_heap = [] distance = startFuel while True: if distance >= target: return stops while stations and distance >= stations[0][0]: heappush(fuel_heap, -heappop(stations)[1]) if not fuel_heap: return -1 distance -= heappop(fuel_heap) stops+=1
minimum-number-of-refueling-stops
Python O(n*log(n)) time | O (N) space
vtalantsev
0
14
minimum number of refueling stops
871
0.398
Hard
14,179
https://leetcode.com/problems/minimum-number-of-refueling-stops/discuss/2452754/Python3-Solution-with-using-heap
class Solution: def minRefuelStops(self, target: int, startFuel: int, stations: List[List[int]]) -> int: heap = [] stations.append([target, float('inf')]) cur_capacity = startFuel prev_pos, stops = 0, 0 for cur_pos, station_capacity in stations: cur_capacity -= cur_pos - prev_pos while heap and cur_capacity < 0: cur_capacity += -heapq.heappop(heap) stops += 1 if cur_capacity < 0: return -1 heapq.heappush(heap, -station_capacity) prev_pos = cur_pos return stops
minimum-number-of-refueling-stops
[Python3] Solution with using heap
maosipov11
0
7
minimum number of refueling stops
871
0.398
Hard
14,180
https://leetcode.com/problems/minimum-number-of-refueling-stops/discuss/2452753/O(n)-using-BFS-%2B-Two-Queues-%2B-Update-Optimization-(illustration-examples-easy-understanding)
class Solution: def minRefuelStops(self, target: int, startFuel: int, stations: List[List[int]]) -> int: """ 0: (0,10) 10(60) - 90: (0, 0)(1,60) 20(30) - 80: (1,50), [(2,80)] 30(30) - 70: (1,40), [(2,70)] 60(40) - 40: (1,10), [(2,50)] 100 - bfs - 2 queue """ ans = -1 stations.append((target, 0)) q1 = [(0,startFuel)] p0 = 0 print("start: ", q1) for pi, fi in stations: q2 = [] for rq, fq in q1: fq -= (pi-p0) if target - pi<=fq: # remain distance ans = rq if ans==-1 or ans>rq else ans elif fq>=0 and (ans==-1 or rq<ans): if fq>0: q2.append((rq, fq)) if ans==-1 or rq+1<ans: q2.append((rq+1, fq+fi)) print(f"+ {pi} ({fi}) - {target - pi}: {q2} - {ans}") p0 = pi q1 = q2 print("end: ", q1) print("="*100) return ans print = lambda *a,**aa: ()
minimum-number-of-refueling-stops
O(n) using BFS + Two Queues + Update Optimization (illustration examples - easy understanding)
dntai
0
8
minimum number of refueling stops
871
0.398
Hard
14,181
https://leetcode.com/problems/minimum-number-of-refueling-stops/discuss/1275556/Python3-priority-queue
class Solution: def minRefuelStops(self, target: int, startFuel: int, stations: List[List[int]]) -> int: ans = k = 0 total = startFuel pq = [] while total < target: while k < len(stations) and stations[k][0] <= total: heappush(pq, -stations[k][1]) k += 1 if not pq: return -1 total -= heappop(pq) ans += 1 return ans
minimum-number-of-refueling-stops
[Python3] priority queue
ye15
0
60
minimum number of refueling stops
871
0.398
Hard
14,182
https://leetcode.com/problems/leaf-similar-trees/discuss/1564699/Easy-Python-Solution-or-Faster-than-98-(24ms)
class Solution: def __init__(self): self.n = [] def dfs(self, root): if root: # checking if the node is leaf if not root.left and not root.right: # appends the leaf nodes to the list - self.n self.n.append(root.val) self.dfs(root.left) self.dfs(root.right) def leafSimilar(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> bool: self.dfs(root1) a = self.n self.n = [] self.dfs(root2) if a == self.n: return True else: return False
leaf-similar-trees
Easy Python Solution | Faster than 98% (24ms)
the_sky_high
4
174
leaf similar trees
872
0.652
Easy
14,183
https://leetcode.com/problems/leaf-similar-trees/discuss/1356825/DFS-with-iterative-and-recursive-generator-in-python
class Solution: def leafSimilar(self, root1: TreeNode, root2: TreeNode) -> bool: def leaf_gen(rt: TreeNode): if (None, None) == (rt.left, rt.right): yield rt.val else: if rt.left: yield from leaf_gen(rt.left) if rt.right: yield from leaf_gen(rt.right) return all(l1 == l2 for l1, l2 in itertools.zip_longest(leaf_gen(root1), leaf_gen(root2)))
leaf-similar-trees
DFS with iterative and recursive generator in python
mousun224
1
72
leaf similar trees
872
0.652
Easy
14,184
https://leetcode.com/problems/leaf-similar-trees/discuss/1356825/DFS-with-iterative-and-recursive-generator-in-python
class Solution: def leafSimilar(self, root1: TreeNode, root2: TreeNode) -> bool: def leaf_gen(rt: TreeNode): stack = [rt] while stack: node = stack.pop() if (None, None) == (node.left, node.right): yield node.val else: if node.right: stack += node.right, if node.left: stack += node.left, return all(l1 == l2 for l1, l2 in itertools.zip_longest(leaf_gen(root1), leaf_gen(root2)))
leaf-similar-trees
DFS with iterative and recursive generator in python
mousun224
1
72
leaf similar trees
872
0.652
Easy
14,185
https://leetcode.com/problems/leaf-similar-trees/discuss/2338191/Python3-recursive-solution
class Solution: def leafSimilar(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> bool: def fm(rt): if not rt: return [] elif not rt.left and not rt.right: return [rt.val] else: lv = fm(rt.left) rv= fm(rt.right) return lv+rv lst1 = fm(root1) lst2 = fm(root2) return True if lst1 ==lst2 else False
leaf-similar-trees
Python3 recursive solution
sanzid
0
9
leaf similar trees
872
0.652
Easy
14,186
https://leetcode.com/problems/leaf-similar-trees/discuss/1918251/Python-Recursive-Solution-(DFS)-Faster-Than-94-Easy-To-Understand
class Solution: def leafSimilar(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> bool: v, v1 = [], [] def dfs(tree): if not tree: return if tree.left is None and tree.right is None: v.append(tree.val) dfs(tree.left) dfs(tree.right) dfs(root1) v1 = v v = [] dfs(root2) return v == v1
leaf-similar-trees
Python Recursive Solution (DFS), Faster Than 94% Easy To Understand
Hejita
0
59
leaf similar trees
872
0.652
Easy
14,187
https://leetcode.com/problems/leaf-similar-trees/discuss/1853770/PYTHON-RECURSIVE-solution-step-by-step-(28ms)
class Solution: def leafSimilar(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> bool: #Lists for each path #I append to them during the recursion #This will work because lists are mutable #And will keep the changes made to them throughout #The recursions firstPath = []; secondPath = []; #Call the helper function on both roots each with their respective path list self.findLeafSeq( root1, firstPath ); self.findLeafSeq( root2, secondPath ); #See if they are equal return firstPath == secondPath; #At each level def findLeafSeq( self, root , leafPath ): #Look at the children leftChild = root.left; rightChild = root.right; #If they are both None, we are a leaf if leftChild is None and rightChild is None: #So we take the current value and append it to the path current = root.val; leafPath.append( current ); return; #Otherwise we dig down into the recursion #If there is only one child, because the other is none #take the valid path elif leftChild is None: self.findLeafSeq( rightChild, leafPath ); elif rightChild is None: self.findLeafSeq( leftChild, leafPath ); #If there are two children, call the left and then the right child else: self.findLeafSeq( leftChild, leafPath ); self.findLeafSeq( rightChild, leafPath );
leaf-similar-trees
PYTHON RECURSIVE solution step-by-step (28ms)
greg_savage
0
25
leaf similar trees
872
0.652
Easy
14,188
https://leetcode.com/problems/leaf-similar-trees/discuss/1432154/Python3-Iterative-DFS-with-queue
class Solution: def leafSimilar(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> bool: leafs = collections.deque([]) stack = [root1] while stack: node = stack.pop() if not node.right and not node.left: leafs.append(node.val) continue if node.right: stack.append(node.right) if node.left: stack.append(node.left) stack = [root2] while stack: node = stack.pop() if not node.right and not node.left: if len(leafs) == 0 or leafs.popleft() != node.val: return False continue if node.right: stack.append(node.right) if node.left: stack.append(node.left) return len(leafs) == 0
leaf-similar-trees
[Python3] Iterative DFS with queue
maosipov11
0
31
leaf similar trees
872
0.652
Easy
14,189
https://leetcode.com/problems/leaf-similar-trees/discuss/1422716/Traverse-the-trees-append-the-leaves-88-speed
class Solution: def leafSimilar(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> bool: leaves = [[], []] def traverse(node: TreeNode, tree_idx=0) -> None: nonlocal leaves if not node.left and not node.right: leaves[tree_idx].append(node.val) else: if node.left: traverse(node.left, tree_idx) if node.right: traverse(node.right, tree_idx) traverse(root1, 0) traverse(root2, 1) return leaves[0] == leaves[1]
leaf-similar-trees
Traverse the trees, append the leaves, 88% speed
EvgenySH
0
93
leaf similar trees
872
0.652
Easy
14,190
https://leetcode.com/problems/leaf-similar-trees/discuss/1070709/Python3-simple-solution-using-%22dfs%22-beats-95
class Solution: def leafSimilar(self, root1: TreeNode, root2: TreeNode) -> bool: leaves1, leaves2 = [], [] def dfs(root,leaves): if root: if root.left == None and root.right == None: leaves.append(root.val) if root.left: dfs(root.left, leaves) if root.right: dfs(root.right, leaves) if root.left == None and root.right == None: leaves.append(root.val) return leaves return dfs(root1, leaves1) == dfs(root2, leaves2)
leaf-similar-trees
Python3 simple solution using "dfs" beats 95%
EklavyaJoshi
0
24
leaf similar trees
872
0.652
Easy
14,191
https://leetcode.com/problems/leaf-similar-trees/discuss/944913/Stack-iterative-and-99-faster
class Solution: def leafSimilar(self, root1: TreeNode, root2: TreeNode) -> bool: def stackdfs(root1): stack, mylist = [], [] while stack or root1: if root1: stack.append(root1) root1 = root1.left else: root1 = stack.pop() if not root1.left and not root1.right: mylist.append(root1.val) root1 = root1.right return mylist return stackdfs(root1) == stackdfs(root2)
leaf-similar-trees
Stack, iterative and 99% faster
serdarkuyuk
0
89
leaf similar trees
872
0.652
Easy
14,192
https://leetcode.com/problems/leaf-similar-trees/discuss/436575/Python-Simple-easy-to-understand-solution
class Solution: def leafSimilar(self, root1: TreeNode, root2: TreeNode) -> bool: store = [] def fn(root): if not root: return if not (root.left) and not (root.right): store.append(root.val) else: fn(root.left) fn(root.right) if root1: fn(root1) st = store store = [] if root2: fn(root2) return st==store
leaf-similar-trees
Python Simple easy to understand solution
saffi
0
165
leaf similar trees
872
0.652
Easy
14,193
https://leetcode.com/problems/leaf-similar-trees/discuss/312065/Python3-most-straightforward-and-concise-solution-beats-90
class Solution: def leafSimilar(self, root1: TreeNode, root2: TreeNode) -> bool: return self.helper(root1)==self.helper(root2) def helper(self,root): res=[] if not root: return [] if not root.left and not root.right: res.append(root.val) res+=self.helper(root.left) res+=self.helper(root.right) return res
leaf-similar-trees
Python3 most straightforward and concise solution beats 90%
jasperjoe
0
39
leaf similar trees
872
0.652
Easy
14,194
https://leetcode.com/problems/length-of-longest-fibonacci-subsequence/discuss/2732493/python-simple-solution-faster
class Solution: def lenLongestFibSubseq(self, arr: List[int]) -> int: arrset=set(arr) res=0 for i in range(len(arr)): for j in range(i+1,len(arr)): a,b,l=arr[i],arr[j],2 while(a+b in arrset): a,b,l=b,a+b,l+1 res=max(res,l) return res if res>=3 else 0
length-of-longest-fibonacci-subsequence
python simple solution faster
Raghunath_Reddy
0
8
length of longest fibonacci subsequence
873
0.486
Medium
14,195
https://leetcode.com/problems/length-of-longest-fibonacci-subsequence/discuss/1863246/python-easy-to-understand-dp-solution
class Solution(object): def lenLongestFibSubseq(self, arr): n = len(arr) longest = defaultdict(int) index = {} for i in range(n): index[arr[i]] = i res = 0 for i in range(n): for j in range(i+1, n): k = arr[i] + arr[j] if k in index: idx = index[k] longest[(j, idx)] = longest[(i, j)] + 1 res = max(res, longest[(j, idx)]) if res >= 1: return res+2 else: return 0
length-of-longest-fibonacci-subsequence
python easy-to-understand dp solution
byuns9334
0
142
length of longest fibonacci subsequence
873
0.486
Medium
14,196
https://leetcode.com/problems/length-of-longest-fibonacci-subsequence/discuss/1461646/PyPy3-Solution-with-recursion-%2B-memoization-w-comments
class Solution: def lenLongestFibSubseq(self, arr: List[int]) -> int: # NOTE: returning zero if next element in fib seq # is not found is the crux of the optimization. If # ignored time limit in the test cases exceeds. # Init arr.sort() n = len(arr) A = set(arr) t = defaultdict(lambda: 0) # A Function to compute fib length # starting with a sequence i,j,i+j,... def fibLen(i: int, j: int) -> int: nonlocal t # If key is not processed if (i,j) not in t: # Continue if fib seq valid k = i + j if k not in A: return 0 else: t[(i,j)] = fibLen(j, k) + 1 return t[(i,j)] # For all possible combination max_len = -sys.maxsize for i in range(0,n-1): for j in range(i+1,n): max_len = max(max_len, fibLen(arr[i],arr[j])) # Add 2 to the max_len if it is not zero, this will include # the length of the first two elements which are not counted # previously. return max_len + 2 if max_len else 0
length-of-longest-fibonacci-subsequence
[Py/Py3] Solution with recursion + memoization w/ comments
ssshukla26
0
173
length of longest fibonacci subsequence
873
0.486
Medium
14,197
https://leetcode.com/problems/length-of-longest-fibonacci-subsequence/discuss/1024869/Python-N2-logM-solution
class Solution: def lenLongestFibSubseq(self, arr: List[int]) -> int: n = len(arr) m = arr[-1] def recursive(a, index, last2, last): if index>=n or last2>m: return 0 if a<2: return max(1+recursive(a+1,index+1,last2+arr[index],arr[index]), recursive(a, index+1, last2, last)) else: pos = bisect_left(arr, last2, lo = index) if pos<n and arr[pos]==last2: return (1+recursive(a+1,pos+1,last+arr[pos],arr[pos])) else: return 0 a= recursive(0,0,0,0) if a <3: return 0 else: return a
length-of-longest-fibonacci-subsequence
Python N^2 logM solution
adit_negi
0
171
length of longest fibonacci subsequence
873
0.486
Medium
14,198
https://leetcode.com/problems/length-of-longest-fibonacci-subsequence/discuss/942291/Python3-dp-O(N2)
class Solution: def lenLongestFibSubseq(self, A: List[int]) -> int: seen = {} for i in range(len(A)): for j in range(i): seen[A[i], A[j]] = 1 + seen.get((A[j], A[i] - A[j]), 1) ans = max(seen.values()) return ans if ans >= 3 else 0
length-of-longest-fibonacci-subsequence
[Python3] dp O(N^2)
ye15
0
140
length of longest fibonacci subsequence
873
0.486
Medium
14,199