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/min-cost-climbing-stairs/discuss/2737248/O(n)-time-and-O(1)-space-in-python3-explained
class Solution: def minCostClimbingStairs(self, cost: List[int]) -> int: twoback = cost[0] oneback = cost[1] curr = 0 for i in range(2, len(cost)): curr = cost[i] + min(twoback, oneback) twoback = oneback oneback = curr return min(twoback, oneback)
min-cost-climbing-stairs
O(n) time and O(1) space in python3 explained
ThatTallProgrammer
0
3
min cost climbing stairs
746
0.625
Easy
12,300
https://leetcode.com/problems/min-cost-climbing-stairs/discuss/2736065/Minimum-cost-to-reach-Stair
class Solution: def minCostClimbingStairs(self, cost: List[int]) -> int: stepcount = len(cost) stepcost = [0]*(stepcount+1) if stepcount<3: return min(cost) stepcost[1] = cost[0] stepcost[2] = cost[1] for i in range(2,stepcount): stepcost[i+1] = cost[i]+min(stepcost[i],stepcost[i-1]) return(min(stepcost[-1],stepcost[-2]))
min-cost-climbing-stairs
Minimum cost to reach Stair
tkrishnakumar30
0
2
min cost climbing stairs
746
0.625
Easy
12,301
https://leetcode.com/problems/min-cost-climbing-stairs/discuss/2728934/Python-Solution-or-1D-Bottom-Up-Dynamic-Programming-Based
class Solution: def minCostClimbingStairs(self, cost: List[int]) -> int: # len(cost) + 1 length auxillary array dp = [0] * (len(cost) + 1) # cost of dp[n] = 0 : top # cost of dp[n-1], dp[n-2] are costs[n-1], costs[n-2] respectively dp[-2] = cost[-1] dp[-3] = cost[-2] # build the dp array for i in range(len(dp) - 3, -1 , -1): dp[i] = cost[i] + min(dp[i+1],dp[i+2]) # check if we need to take one step or two at initial point return min(dp[0],dp[1])
min-cost-climbing-stairs
Python Solution | 1D - Bottom Up Dynamic Programming Based
Gautam_ProMax
0
7
min cost climbing stairs
746
0.625
Easy
12,302
https://leetcode.com/problems/min-cost-climbing-stairs/discuss/2715120/Min-Cost-Climbing-Stairs-in-python-very-easy-solution
class Solution: def minCostClimbingStairs(self, cost: List[int]) -> int: cost.append(0) for i in range(len(cost)-3,-1,-1) : cost[i] += min(cost[i+1],cost[i+2]) return min(cost[0],cost[1])
min-cost-climbing-stairs
Min Cost Climbing Stairs in python very easy solution
jashii96
0
2
min cost climbing stairs
746
0.625
Easy
12,303
https://leetcode.com/problems/min-cost-climbing-stairs/discuss/2663502/Python-intuitive-decision-in-3-lines
class Solution: def minCostClimbingStairs(self, cost: List[int]) -> int: for i in range(2, len(cost)): cost[i] += min(cost[i-1], cost[i-2]) return min(cost[-1], cost[-2])
min-cost-climbing-stairs
Python, intuitive decision in 3 lines
drixe
0
4
min cost climbing stairs
746
0.625
Easy
12,304
https://leetcode.com/problems/min-cost-climbing-stairs/discuss/2659214/here-is-my-solution-O(n)-greatergreater%3A)
class Solution: def minCostClimbingStairs(self, c: List[int]) -> int: c.append(0) #cost for top floor if(len(c)==2): return min(c[0],c[1]) else: prev2=c[0] prev1=c[1] for i in range(2,len(c)): crnt1=prev1+c[i] crnt2=prev2+c[i] prev2=prev1 prev1=min(crnt1,crnt2) print(prev1) return prev1
min-cost-climbing-stairs
here is my solution O(n)->>:)
re__fresh
0
3
min cost climbing stairs
746
0.625
Easy
12,305
https://leetcode.com/problems/min-cost-climbing-stairs/discuss/2650530/(beats-90)
class Solution: def minCostClimbingStairs(self, cost: List[int]) -> int: table=list(map(lambda x:0,range(len(cost)+1))) table[-1]=1 i=len(cost) while i>=0: if table!=0: for t in (1,2): f=i-t if f>=0 : v=cost[f]+table[i] if (table[f]==0 or table[f]>v): table[f]=v i-=1 return min(table[:2])-1
min-cost-climbing-stairs
(beats 90%)
chitranshagrawal1804
0
1
min cost climbing stairs
746
0.625
Easy
12,306
https://leetcode.com/problems/min-cost-climbing-stairs/discuss/2645914/Python-recursion.
class Solution: def minCostClimbingStairs(self, cost: List[int]) -> int: def climb(idx: int) -> int: if len(cost) - idx < 3: # reach top of stairs return cost[idx] elif idx in memo: # no need to calculate again return memo[idx] else: min_cost = cost[idx] + min(climb(idx+1), climb(idx+2)) # step 1 or 2 memo[idx] = min_cost return min_cost memo = {} # record the min cost for every stairs idx = 0 return min(climb(idx), climb(idx+1)) # start at index 0 or 1
min-cost-climbing-stairs
Python, recursion.
woora3
0
12
min cost climbing stairs
746
0.625
Easy
12,307
https://leetcode.com/problems/min-cost-climbing-stairs/discuss/2645698/Python-Solution
class Solution: def minCostClimbingStairs(self, cost: List[int]) -> int: cost.append(0) for i in range(len(cost) - 3, -1, -1): cost[i] = min((cost[i] + cost[i+1]), cost[i] + cost[i + 2]) return min(cost[0], cost[1])
min-cost-climbing-stairs
Python Solution
mueezsheersho95
0
4
min cost climbing stairs
746
0.625
Easy
12,308
https://leetcode.com/problems/min-cost-climbing-stairs/discuss/2644086/Python-easy-solution
class Solution: def minCostClimbingStairs(self, cost: List[int]) -> int: totalCost = [0]*len(cost) totalCost[-1], totalCost[-2] = cost[-1], cost[-2] for i in range(len(cost)-3, -1, -1): totalCost[i] = cost[i] + min(totalCost[i+1], totalCost[i+2]) return min(totalCost[0], totalCost[1])
min-cost-climbing-stairs
Python easy solution
Jack_Chang
0
48
min cost climbing stairs
746
0.625
Easy
12,309
https://leetcode.com/problems/min-cost-climbing-stairs/discuss/2595738/Simple-python-code-with-explanation
class Solution: def minCostClimbingStairs(self, cost: List[int]) -> int: cost.append(0) for i in range(len(cost)-3,-1,-1): cost[i] = min((cost[i] + cost[i+1]) , (cost[i] + cost[i+2])) return min(cost[0],cost[1])
min-cost-climbing-stairs
Simple python code with explanation
thomanani
0
40
min cost climbing stairs
746
0.625
Easy
12,310
https://leetcode.com/problems/min-cost-climbing-stairs/discuss/2586032/Self-Understandable-Python%3A
class Solution: def minCostClimbingStairs(self, cost: List[int]) -> int: slow=cost[0] fast=cost[1] for i in range(2,len(cost)): slow,fast=fast,cost[i]+min(slow,fast) return min(slow,fast)
min-cost-climbing-stairs
Self Understandable Python:
goxy_coder
0
16
min cost climbing stairs
746
0.625
Easy
12,311
https://leetcode.com/problems/min-cost-climbing-stairs/discuss/2547215/EASY-PYTHON3-SOLUTION-O(N)
class Solution: def minCostClimbingStairs(self, cost: List[int]) -> int: dp = [0]*len(cost) dp [-1], dp [-2] = cost[-1], cost[-2] for i in range(len(cost)-3, -1, -1): dp[i] = min(dp[i+1], dp[i+2]) + cost[i] return min(dp[0],dp[1])
min-cost-climbing-stairs
βœ…βœ”πŸ”₯ EASY PYTHON3 SOLUTION πŸ”₯O(N)βœ…βœ”
rajukommula
0
65
min cost climbing stairs
746
0.625
Easy
12,312
https://leetcode.com/problems/min-cost-climbing-stairs/discuss/2541187/python-dp-solution-using-recursion
class Solution: def minCostClimbingStairs(self, cost: List[int]) -> int: dp={} def check(idx): if idx>len(cost)-1: return 0 if idx in dp: return dp[idx] dp[idx]=cost[idx]+min(check(idx+1),check(idx+2)) return dp[idx] return min(check(0),check(1))
min-cost-climbing-stairs
python dp solution using recursion
benon
0
47
min cost climbing stairs
746
0.625
Easy
12,313
https://leetcode.com/problems/min-cost-climbing-stairs/discuss/2442330/PYTHON-3-oror-Clean-and-Short-Solution-oror-DP
class Solution: def minCostClimbingStairs(self, cost: List[int]) -> int: cost.append(0) for i in range(len(cost)-3, -1, -1): cost[i] += min(cost[i+1], cost[i+2]) return min(cost[0], cost[1])
min-cost-climbing-stairs
[PYTHON 3] || Clean and Short Solution || DP
WhiteBeardPirate
0
37
min cost climbing stairs
746
0.625
Easy
12,314
https://leetcode.com/problems/min-cost-climbing-stairs/discuss/2415637/Python3-Simple-Min-Cost-w-Explanation
class Solution: def minCostClimbingStairs(self, cost: List[int]) -> int: # Handle empty cost case if not cost: return 0 # min_cost is the minimum cost to get to some step i min_cost = [0] * len(cost) min_cost[0] = cost[0] # Loop through. At each i, the cost is: # - The cost of that step plus the minimum cost of the two steps before it for i in range(1, len(cost)): min_cost[i] = cost[i] + min(min_cost[i-1], min_cost[i-2]) # Return the smaller of the two last steps (since two steps could be taken from the second last step out) return min(min_cost[-1], min_cost[-2])
min-cost-climbing-stairs
[Python3] Simple Min Cost w Explanation
connorthecrowe
0
85
min cost climbing stairs
746
0.625
Easy
12,315
https://leetcode.com/problems/largest-number-at-least-twice-of-others/discuss/2069691/no-loops
class Solution: def dominantIndex(self, nums: List[int]) -> int: if len(nums) is 1: return 0 dom = max(nums) i = nums.index(dom) nums.remove(dom) if max(nums) * 2 <= dom: return i return -1
largest-number-at-least-twice-of-others
no loops
andrewnerdimo
3
90
largest number at least twice of others
747
0.465
Easy
12,316
https://leetcode.com/problems/largest-number-at-least-twice-of-others/discuss/2645620/Python-Simple-or-Clean-or-One-Pass-or-beat-98-O(N)-and-O(1)
class Solution: def dominantIndex(self, nums: List[int]) -> int: largest = max(nums) for idx, val in enumerate(nums): if val==largest: new_idx = idx continue if val*2>largest: return -1 return new_idx
largest-number-at-least-twice-of-others
βœ… [Python] Simple | Clean | One Pass | beat 98% O(N) & O(1)
girraj_14581
1
28
largest number at least twice of others
747
0.465
Easy
12,317
https://leetcode.com/problems/largest-number-at-least-twice-of-others/discuss/2403749/No-Loops-Solution
class Solution: def dominantIndex(self, nums: List[int]) -> int: ind = nums.index(max(nums)) nums.sort() if 2*nums[-2] <= nums[-1]: return ind return -1
largest-number-at-least-twice-of-others
No Loops Solution
Abhi_-_-
1
53
largest number at least twice of others
747
0.465
Easy
12,318
https://leetcode.com/problems/largest-number-at-least-twice-of-others/discuss/1944193/Python-Fast-Solution-or-Sorting-Solution
class Solution: def dominantIndex(self, nums): if len(nums) == 1: return 0 s = sorted(nums, reverse=True) largest, secondLargest = s[0], s[1] return nums.index(largest) if largest >= 2*secondLargest else -1
largest-number-at-least-twice-of-others
Python - Fast Solution | Sorting Solution
domthedeveloper
1
85
largest number at least twice of others
747
0.465
Easy
12,319
https://leetcode.com/problems/largest-number-at-least-twice-of-others/discuss/1944193/Python-Fast-Solution-or-Sorting-Solution
class Solution: def dominantIndex(self, nums): max1_val, max1_idx, max2_val = -1, -1, -1 for i,n in enumerate(nums): if n > max1_val: max2_val = max1_val max1_val, max1_idx = n, i elif n > max2_val: max2_val = n return max1_idx if max1_val >= max2_val*2 else -1
largest-number-at-least-twice-of-others
Python - Fast Solution | Sorting Solution
domthedeveloper
1
85
largest number at least twice of others
747
0.465
Easy
12,320
https://leetcode.com/problems/largest-number-at-least-twice-of-others/discuss/1317645/Python3-dollarolution(Faster-than-99)
class Solution: def dominantIndex(self, nums: List[int]) -> int: if len(nums) == 1: return 0 n = nums[0:] n.sort() if n[-1] >= 2 * n[-2]: return nums.index(n[-1]) return -1
largest-number-at-least-twice-of-others
Python3 $olution(Faster than 99%)
AakRay
1
176
largest number at least twice of others
747
0.465
Easy
12,321
https://leetcode.com/problems/largest-number-at-least-twice-of-others/discuss/401820/Python-Simple-and-Concise-solution
class Solution: def dominantIndex(self, nums: List[int]) -> int: if len(nums)==1: return 0 n = sorted(nums) if n[-1]>=n[-2]*2: return nums.index(n[-1]) else: return -1
largest-number-at-least-twice-of-others
Python Simple and Concise solution
saffi
1
155
largest number at least twice of others
747
0.465
Easy
12,322
https://leetcode.com/problems/largest-number-at-least-twice-of-others/discuss/2816996/Easy-Python-Solution-and-two-linear-solution
class Solution: def dominantIndex(self, nums: List[int]) -> int: largest_ele = float("-inf") second_largest_ele = float("-inf") for num in nums: if num > largest_ele: second_largest_ele = largest_ele largest_ele = num if num < largest_ele and second_largest_ele < num: second_largest_ele = num if largest_ele >= 2*second_largest_ele: return nums.index(largest_ele) return -1
largest-number-at-least-twice-of-others
Easy Python Solution and two linear solution
danishs
0
1
largest number at least twice of others
747
0.465
Easy
12,323
https://leetcode.com/problems/largest-number-at-least-twice-of-others/discuss/2770835/Logical-and-easy-solution.-Python.-Time%3A0(N)-Space-0(1)
class Solution: def dominantIndex(self, nums: List[int]) -> int: #Find the original index largest = nums[0] currind = 0 for ind, val in enumerate (nums): if val > largest: largest = val currind = ind nums.remove(largest) # check the largest number is 2x bigger for n in range(len(nums)): print("nums[n]", nums[n]) if largest < nums[n]*2: return -1 else: continue return currind
largest-number-at-least-twice-of-others
Logical and easy solution. Python. Time:0(N), Space 0(1)
dapilk101
0
3
largest number at least twice of others
747
0.465
Easy
12,324
https://leetcode.com/problems/largest-number-at-least-twice-of-others/discuss/2733378/Python-Solution-Simple-Sorting-algorithm
class Solution: def dominantIndex(self, nums: List[int]) -> int: arr = sorted(nums) #.sort() highest = arr[-1] second = arr[-2] if second == 0: return nums.index(highest) if highest // second >= 2: return nums.index(highest) return -1
largest-number-at-least-twice-of-others
Python Solution - Simple Sorting algorithm
dayaniravi123
0
1
largest number at least twice of others
747
0.465
Easy
12,325
https://leetcode.com/problems/largest-number-at-least-twice-of-others/discuss/2728742/One-pass-constant-space-python-solution
class Solution: def dominantIndex(self, nums: List[int]) -> int: max1, max2 = -1, -1 m1id = -1 for i in range(len(nums)): n = nums[i] if n > max1: max2 = max1 m1id = i max1 = n elif n > max2: max2 = n return m1id if max1 >= max2 * 2 else -1
largest-number-at-least-twice-of-others
One pass constant space python solution
lmnvs
0
1
largest number at least twice of others
747
0.465
Easy
12,326
https://leetcode.com/problems/largest-number-at-least-twice-of-others/discuss/2726772/Python-Solution-Using-Max-Heap
class Solution: def dominantIndex(self, nums: List[int]) -> int: h = [] for index in range(len(nums)): heappush(h, (-1*nums[index], index)) #Reverse min heap to max heap by reversing sign. largest_num_pair = heappop(h) #Get largest pair. largest_num = -1*largest_num_pair[0] #Return negative number to original. largest_index = largest_num_pair[1] #Get index from tuple. second_largest_num = -1*heappop(h)[0] #Return negative number to original. if largest_num >= second_largest_num*2: return largest_index else: return -1
largest-number-at-least-twice-of-others
Python Solution Using Max Heap
mephiticfire
0
3
largest number at least twice of others
747
0.465
Easy
12,327
https://leetcode.com/problems/largest-number-at-least-twice-of-others/discuss/2642341/Python-Simple-and-Easy-Solution
class Solution(object): def dominantIndex(self, n): l = n l = sorted(l) r = l.pop() if r >= (l[-1])*2: return n.index(r) return -1
largest-number-at-least-twice-of-others
Python Simple and Easy Solution
SouravSingh49
0
13
largest number at least twice of others
747
0.465
Easy
12,328
https://leetcode.com/problems/largest-number-at-least-twice-of-others/discuss/2305581/Python-5-liner-oror-Beats-88-in-runtime
class Solution: def dominantIndex(self, nums: List[int]) -> int: index=nums.index(max(nums)) nums.sort(reverse=True) if nums[0]>=nums[1]*2: return index else: return -1
largest-number-at-least-twice-of-others
Python 5 liner || Beats 88% in runtime
keertika27
0
41
largest number at least twice of others
747
0.465
Easy
12,329
https://leetcode.com/problems/largest-number-at-least-twice-of-others/discuss/2263479/Python-2-Liner
class Solution: def dominantIndex(self, nums: List[int]) -> int: s = sorted([(nums[i], i) for i in range(len(nums))], reverse=True) return s[0][1] if s[0][0] / 2 >= s[1][0] else -1
largest-number-at-least-twice-of-others
Python 2-Liner
amaargiru
0
22
largest number at least twice of others
747
0.465
Easy
12,330
https://leetcode.com/problems/largest-number-at-least-twice-of-others/discuss/2130704/Python-simple-solution
class Solution: def dominantIndex(self, nums: List[int]) -> int: if len(nums) == 1: return 0 return nums.index(max(nums)) if sorted(nums)[-1] >= sorted(nums)[-2]*2 else -1
largest-number-at-least-twice-of-others
Python simple solution
StikS32
0
46
largest number at least twice of others
747
0.465
Easy
12,331
https://leetcode.com/problems/largest-number-at-least-twice-of-others/discuss/2015323/Python3-using-for-loop
class Solution: def dominantIndex(self, nums: List[int]) -> int: maxN = max(nums) indexMaxN = nums.index(maxN) isTwice = None nums.sort() if len(nums) == 1: return 0 for n in range(len(nums)): if nums[n] != maxN: twice = nums[n] * 2 if twice > maxN: isTwice = False elif twice == maxN: isTwice = True return indexMaxN if isTwice or isTwice == None else -1
largest-number-at-least-twice-of-others
[Python3] using for loop
Shiyinq
0
26
largest number at least twice of others
747
0.465
Easy
12,332
https://leetcode.com/problems/largest-number-at-least-twice-of-others/discuss/1926619/largest-number-at-least-twice-of-others
class Solution: def dominantIndex(self, nums: List[int]) -> int: m=max(nums) a=nums.index(m) arr=[] g=0 for i in nums: if i!=m: arr.append(i) if len(arr)!=0: g=max(arr) if m>=2*g: return a else: return -1
largest-number-at-least-twice-of-others
largest number at least twice of others
anil5829354
0
27
largest number at least twice of others
747
0.465
Easy
12,333
https://leetcode.com/problems/largest-number-at-least-twice-of-others/discuss/1877010/Python-l-Simple-O(2n)
class Solution: def dominantIndex(self, nums: List[int]) -> int: n = len(nums) max_1 = -inf max_2 = -inf for i in range(n): if max_1 < nums[i]: max_1 = nums[i] idx = i for num in nums: if num != max_1: max_2 = max(num,max_2) if max_1 >= 2*max_2 : return idx return -1
largest-number-at-least-twice-of-others
Python l Simple O(2n)
morpheusdurden
0
43
largest number at least twice of others
747
0.465
Easy
12,334
https://leetcode.com/problems/largest-number-at-least-twice-of-others/discuss/1857544/Simple-and-Easy-to-Understand-python-solution
class Solution: def dominantIndex(self, nums: List[int]) -> int: largest_number = max(nums) for number in nums: if number != largest_number and (number + number) > largest_number: return -1 return nums.index(largest_number)
largest-number-at-least-twice-of-others
Simple and Easy to Understand python solution
hardik097
0
31
largest number at least twice of others
747
0.465
Easy
12,335
https://leetcode.com/problems/largest-number-at-least-twice-of-others/discuss/1853076/Python-(Simple-approach-and-Beginner-friendly)
class Solution: def dominantIndex(self, nums: List[int]) -> int: if len(nums) <= 1: return 0 else: nums1 = nums[:] nums1.sort() if (nums1[-2]*2) <= nums1[-1]: return nums.index(nums1[-1]) return -1
largest-number-at-least-twice-of-others
Python (Simple approach and Beginner-friendly)
vishvavariya
0
47
largest number at least twice of others
747
0.465
Easy
12,336
https://leetcode.com/problems/largest-number-at-least-twice-of-others/discuss/1834341/3-Lines-Python-Solution-oror-50-Faster-oror-Memory-less-than-75
class Solution: def dominantIndex(self, nums: List[int]) -> int: if len(nums)==1: return 0 S=sorted(nums) return [nums.index(S[-1]) if S[-1]>=S[-2]*2 else -1][0]
largest-number-at-least-twice-of-others
3-Lines Python Solution || 50% Faster || Memory less than 75%
Taha-C
0
34
largest number at least twice of others
747
0.465
Easy
12,337
https://leetcode.com/problems/largest-number-at-least-twice-of-others/discuss/1834341/3-Lines-Python-Solution-oror-50-Faster-oror-Memory-less-than-75
class Solution: def dominantIndex(self, nums: List[int]) -> int: return nums.index(max(nums)) if all(i*2<=max(nums) for i in nums if i!=max(nums)) else -1
largest-number-at-least-twice-of-others
3-Lines Python Solution || 50% Faster || Memory less than 75%
Taha-C
0
34
largest number at least twice of others
747
0.465
Easy
12,338
https://leetcode.com/problems/largest-number-at-least-twice-of-others/discuss/1815071/My-solution-in-Python-and-Kotlin
class Solution: def dominantIndex(self, nums: List[int]) -> int: """ determine if BIGGEST value is at least twice larger than any other integer """ biggest_val = max(nums) final_index = None for i in range(len(nums)): num = nums[i] if num != biggest_val and biggest_val < num * 2: return -1 elif num == biggest_val: final_index = i return final_index
largest-number-at-least-twice-of-others
My solution in Python and Kotlin
SleeplessChallenger
0
39
largest number at least twice of others
747
0.465
Easy
12,339
https://leetcode.com/problems/largest-number-at-least-twice-of-others/discuss/1809298/Python-O(nlogn)-easy-to-understand
class Solution: def dominantIndex(self, nums: List[int]) -> int: n = sorted(nums) if len(nums) == 1: return 0 else: if (2*n[-2]) <= n[-1]: return nums.index(n[-1]) else: return -1
largest-number-at-least-twice-of-others
Python O(nlogn) easy to understand
zamya7
0
48
largest number at least twice of others
747
0.465
Easy
12,340
https://leetcode.com/problems/largest-number-at-least-twice-of-others/discuss/1627527/Python-one-pass-solution-with-O(1)-space
class Solution: def dominantIndex(self, nums: List[int]) -> int: n = len(nums) # base case: if n == 1: return 0 # init a min heap min_heap = [] # Time analysis for the itertion: n * O(1) = O(n) for i in range(n): # takes O(log2) = O(1) heappush(min_heap, (nums[i], i)) # maintain the size of min_heap to be 2, pop the smallest if len(min_heap) > 2: heappop(min_heap) second_larget, idx1 = heappop(min_heap) largest, idx2 = heappop(min_heap) return idx2 if largest >= 2 * second_larget else -1
largest-number-at-least-twice-of-others
Python one-pass solution with O(1) space
aldy97
0
102
largest number at least twice of others
747
0.465
Easy
12,341
https://leetcode.com/problems/largest-number-at-least-twice-of-others/discuss/1370113/Python-3-O(n)-1-pass
class Solution: def dominantIndex(self, nums: List[int]) -> int: idx, m1, m2 = -1, -1, -1 for i, n in enumerate(nums): if n > m1: idx, m1, m2 = i, n, m1 elif n > m2: m2 = n return idx if (m1 >= 2*m2) else -1
largest-number-at-least-twice-of-others
Python 3, O(n) 1 pass
MihailP
0
168
largest number at least twice of others
747
0.465
Easy
12,342
https://leetcode.com/problems/largest-number-at-least-twice-of-others/discuss/1355169/Python-Solution
class Solution: def dominantIndex(self, nums: List[int]) -> int: n = len(nums) if n < 2: return 0 # idx1 is the index of the largest element in array and idx2 is the index of the second-largest element in array if nums[0] < nums[1]: idx1, idx2 = 1, 0 else: idx1, idx2 = 0, 1 for i in range(2, n): if nums[i] > nums[idx1]: idx2, idx1 = idx1, i elif nums[i] > nums[idx2]: idx2 = i if nums[idx1] >= 2 * nums[idx2]: return idx1 return -1
largest-number-at-least-twice-of-others
Python Solution
mariandanaila01
0
141
largest number at least twice of others
747
0.465
Easy
12,343
https://leetcode.com/problems/largest-number-at-least-twice-of-others/discuss/1246134/Python3-simple-solution-by-two-approaches
class Solution: def dominantIndex(self, nums: List[int]) -> int: if len(nums) == 1: return 0 temp = nums.copy() nums.sort() return temp.index(nums[-1]) if nums[-2]*2 <= nums[-1] else -1
largest-number-at-least-twice-of-others
Python3 simple solution by two approaches
EklavyaJoshi
0
68
largest number at least twice of others
747
0.465
Easy
12,344
https://leetcode.com/problems/largest-number-at-least-twice-of-others/discuss/1246134/Python3-simple-solution-by-two-approaches
class Solution: def dominantIndex(self, nums: List[int]) -> int: if len(nums) == 1: return 0 n1 = max(nums) i = nums.index(n1) n2 = max(nums[:i]+nums[i+1:]) return i if n2*2 <= n1 else -1
largest-number-at-least-twice-of-others
Python3 simple solution by two approaches
EklavyaJoshi
0
68
largest number at least twice of others
747
0.465
Easy
12,345
https://leetcode.com/problems/largest-number-at-least-twice-of-others/discuss/1155913/single-scan-python3-linear-time-constant-sapce.
class Solution: def dominantIndex(self, nums: List[int]) -> int: # single scan? set the first and second largest as you go through # and check that the second * 2 is not > first first, second = 0, 0 max_index = 0 for i, x in enumerate(nums): if x > first: max_index = i first, second = x, first elif x > second: second = x return max_index if first >= second * 2 else -1
largest-number-at-least-twice-of-others
single scan python3 linear time, constant sapce.
normalpersontryingtopayrent
0
53
largest number at least twice of others
747
0.465
Easy
12,346
https://leetcode.com/problems/largest-number-at-least-twice-of-others/discuss/1036570/PythonPython3-or-One-liner-and-Detailed-or-Largest-Number-At-Least-Twice-of-Others
class Solution: def dominantIndex(self, nums) -> int: return nums.index(max(nums)) if all(2 * x <= max(nums) if x != max(nums) else True for x in nums) else -1
largest-number-at-least-twice-of-others
[Python/Python3] | One-liner & Detailed | Largest Number At Least Twice of Others
newborncoder
0
161
largest number at least twice of others
747
0.465
Easy
12,347
https://leetcode.com/problems/largest-number-at-least-twice-of-others/discuss/1036570/PythonPython3-or-One-liner-and-Detailed-or-Largest-Number-At-Least-Twice-of-Others
class Solution: def dominantIndex(self, nums) -> int: max_nums = max(nums) if all(2*x <= max_nums if x != max_nums else True for x in nums): return nums.index(max_nums) else: return -1
largest-number-at-least-twice-of-others
[Python/Python3] | One-liner & Detailed | Largest Number At Least Twice of Others
newborncoder
0
161
largest number at least twice of others
747
0.465
Easy
12,348
https://leetcode.com/problems/largest-number-at-least-twice-of-others/discuss/538816/Python-Two-Pass
class Solution: def dominantIndex(self, nums: List[int]) -> int: max_val = nums[0] index = 0 for i in range(1,len(nums)): if nums[i] > max_val: max_val = nums[i] index = i for i,num in enumerate(nums): if num * 2 <= max_val: continue elif i == index: continue else: return -1 return index
largest-number-at-least-twice-of-others
Python Two Pass
pratushah
0
114
largest number at least twice of others
747
0.465
Easy
12,349
https://leetcode.com/problems/largest-number-at-least-twice-of-others/discuss/343071/Python3-self-explanatory-and-short-solution
class Solution: def dominantIndex(self, nums: List[int]) -> int: if len(nums)==1:return 0 n=sorted(nums) if n[-1]>=2*n[-2]: return nums.index(n[-1]) return -1
largest-number-at-least-twice-of-others
Python3 self explanatory and short solution
ketan35
0
92
largest number at least twice of others
747
0.465
Easy
12,350
https://leetcode.com/problems/largest-number-at-least-twice-of-others/discuss/336481/Solution-in-Python-3
class Solution: def dominantIndex(self, nums: List[int]) -> int: M = max(nums) return nums.index(M) if len([0 for i in nums if 2*i <= M]) == len(nums)-1 else -1 - Python 3 - Junaid Mansuri
largest-number-at-least-twice-of-others
Solution in Python 3
junaidmansuri
0
316
largest number at least twice of others
747
0.465
Easy
12,351
https://leetcode.com/problems/shortest-completing-word/discuss/1277850/Python3-Simple-solution-without-Dictionary
class Solution: def shortestCompletingWord(self, P: str, words: List[str]) -> str: alphs="" res="" for p in P: if p.isalpha(): alphs+=p.lower() for word in words: if all(alphs.count(alphs[i]) <= word.count(alphs[i]) for i in range(len(alphs))): if res=="" or len(res)>len(word): res=word return res
shortest-completing-word
Python3 Simple solution without Dictionary
Rei4126
4
335
shortest completing word
748
0.592
Easy
12,352
https://leetcode.com/problems/shortest-completing-word/discuss/2419448/Python-magic%3A-3-steps
class Solution: def shortestCompletingWord(self, licensePlate: str, words: List[str]) -> str: req = Counter(filter(str.isalpha, licensePlate.lower())) words.sort(key=len) for count, word in zip(map(Counter, words), words): if count >= req: return word
shortest-completing-word
βœ…Python magic: 3 stepsπŸ”₯
blest
0
28
shortest completing word
748
0.592
Easy
12,353
https://leetcode.com/problems/shortest-completing-word/discuss/1791199/5-Lines-Python-Solution-oror-75-Faster-oror-Memory-Less-than-85
class Solution: def shortestCompletingWord(self, licensePlate: str, words: List[str]) -> str: l, mx, ans = ''.join([x.lower() for x in licensePlate if x.isalpha()]), 0, '' for word in words: sumChars = sum([min(word.count(char),l.count(char)) for char in set(l)]) if sumChars > mx or (sumChars == mx and len(word) < len(ans)): mx, ans = sumChars, word return ans
shortest-completing-word
5-Lines Python Solution || 75% Faster || Memory Less than 85%
Taha-C
0
155
shortest completing word
748
0.592
Easy
12,354
https://leetcode.com/problems/shortest-completing-word/discuss/1690838/Python-simple-solution
class Solution: def shortestCompletingWord(self, licensePlate: str, words: List[str]) -> str: license = defaultdict(int) for s in licensePlate: if s.isalpha(): license[s.lower()] += 1 cand = "" candlen = float('inf') def check(word): count = defaultdict(int) for w in word: count[w] += 1 for w in license: if count[w] < license[w]: return False return True for word in words: if check(word): if len(word) < candlen: cand = word candlen = len(word) return cand
shortest-completing-word
Python simple solution
byuns9334
0
143
shortest completing word
748
0.592
Easy
12,355
https://leetcode.com/problems/shortest-completing-word/discuss/1555151/Python3-using-array-Faster-than-93.88
class Solution: def shortestCompletingWord(self, licensePlate: str, words: List[str]) -> str: # Runtime: 64 ms, faster than 93.88% # Memory Usage: 14.5 MB, less than 81.41% words = sorted(words, key=len) # Handle multiple shortest 'completing' words lic = ''.join(sorted([x for x in licensePlate.lower() if 96 < ord(x) <= 122])) for word in words: buff = ''.join(word) exists = True for char in lic: if char not in buff: exists = False break else: if buff.count(char) < lic.count(char): exists = False break if exists: return word
shortest-completing-word
Python3 - using array Faster than 93.88%
inosuke4
0
93
shortest completing word
748
0.592
Easy
12,356
https://leetcode.com/problems/shortest-completing-word/discuss/625043/python3-solution-wo-Counter-(tricks-explained)
class Solution: def shortestCompletingWord(self, licensePlate: str, words: List[str]) -> str: # remove non-letters, cast to lowercases licensePlate = [i for i in licensePlate if i.isalpha()] licensePlate = list(map(str.lower, licensePlate)) licensePlate = sorted(licensePlate) l_len = len(licensePlate) shortest_len = 16 shortest_match = '' for w in words: w_sorted = sorted(w) ptr = 0 w_len = len(w) match = True for i in range(l_len): # continue moving ptr to the right until licensePlate[i] is met while ptr < w_len and w_sorted[ptr] != licensePlate[i]: ptr += 1 # reach the end of w if ptr == w_len: match = False break # hit ptr += 1 # valid if match and w_len < shortest_len: shortest_len = w_len shortest_match = w return shortest_match
shortest-completing-word
python3 solution w/o Counter (tricks explained)
shaoyu0966
0
127
shortest completing word
748
0.592
Easy
12,357
https://leetcode.com/problems/shortest-completing-word/discuss/475537/Python3-97.03-(60-ms)100.00-(12.8-MB)-sorting
class Solution: def shortestCompletingWord(self, licensePlate: str, words: List[str]) -> str: letter_occurences = [0 for a in range(26)] for char in licensePlate: if ('A' <= char <= 'Z'): letter_occurences[ord(char.lower()) - 97] += 1 elif ('a' <= char <= 'z'): letter_occurences[ord(char) - 97] += 1 else: pass letter_occurences = [[chr(a + 97), letter_occurences[a]] for a in range(26) if letter_occurences[a] > 0] min_length = 1001 index = -1 for index_, word in enumerate(words): if (len(word) < min_length): word = sorted(word) index_word = 0 take_word = True for letter, occurences in letter_occurences: while (index_word < len(word) and word[index_word] < letter): index_word += 1 if (index_word == len(word) or word[index_word] > letter): take_word = False break else: while (index_word < len(word) and word[index_word] == letter): occurences -= 1 index_word += 1 if (occurences > 0): take_word = False break if (not take_word): break if (take_word): min_length = len(word) index = index_ return words[index]
shortest-completing-word
Python3 97.03% (60 ms)/100.00% (12.8 MB) -- sorting
numiek_p
0
183
shortest completing word
748
0.592
Easy
12,358
https://leetcode.com/problems/shortest-completing-word/discuss/460454/60-ms98.5212.9-MB100.00-Answer-for-python3
class Solution: def shortestCompletingWord(self, licensePlate: str, words: List[str]) -> str: strs = [] for char in licensePlate.lower(): if char.isalpha(): strs.append(char) words.sort(key=len) def words_in(strs,words): for char in strs: if strs.count(char) > words.count(char): return False return True for word in words: if words_in(strs, word): return word
shortest-completing-word
60 ms,98.52%/12.9 MB,100.00% Answer for python3
SilverCHN
0
89
shortest completing word
748
0.592
Easy
12,359
https://leetcode.com/problems/shortest-completing-word/discuss/450267/Python3-simple-solution-using-hash-table-runtime%3A-72-ms-faster-than-88.85
class Solution: def shortestCompletingWord(self, licensePlate: str, words: List[str]) -> str: lp = "" for char in licensePlate.lower(): if char.isalpha(): lp += char ld = self.countChars(lp) res = None for word in words: if len(word) < len(lp): continue wd = self.countChars(word) is_valid = True for char in ld: if char not in wd or wd[char] < ld[char]: is_valid = False break if is_valid: if not res: res = word continue if len(word) < len(res): res = word return res def countChars(self, st:str) -> dict: ht = {} for s in st.lower(): if s not in ht: ht[s] = 1 else: ht[s] += 1 return ht
shortest-completing-word
Python3 simple solution using hash table, runtime: 72 ms, faster than 88.85%
jb07
0
103
shortest completing word
748
0.592
Easy
12,360
https://leetcode.com/problems/shortest-completing-word/discuss/325107/Python-solution-using-dictionary
class Solution: def shortestCompletingWord(self, l: str, w: List[str]) -> str: res={} lp=l.lower() d={} for i in lp: if i.isalpha(): d[i]=lp.count(i) for i in w: j=i.lower() c=0 for k in d.keys(): if j.count(k)<d[k]: c=1 break if c==0: m=res.get(len(j),[]) res[len(j)]=m+[j] return res[(min(list(res.keys())))][0]
shortest-completing-word
Python solution using dictionary
ketan35
0
152
shortest completing word
748
0.592
Easy
12,361
https://leetcode.com/problems/contain-virus/discuss/2224726/Pyhon-Easy-Solution-oror-DFS-oror-Time-O(m*n*max(m-n))-oror-Faster
class Solution: def containVirus(self, mat: List[List[int]]) -> int: m,n = len(mat),len(mat[0]) def dfs(i,j,visited,nextInfected): # return no. of walls require to quarantined dfs area if 0<=i<m and 0<=j<n and (i,j) not in visited: if mat[i][j]==2: # Already quarantined cell return 0 if mat[i][j]==0: nextInfected.add((i,j)) # add cell which will be infected next day return 1 # require one wall to quarantined cell from one side else: visited.add((i,j)) return dfs(i-1,j,visited,nextInfected) + dfs(i+1,j,visited,nextInfected) + dfs(i,j-1,visited,nextInfected) + dfs(i,j+1,visited,nextInfected) # traverse all four direction else: return 0 ans = 0 while True: # this loop running "how many days we should installing the walls" times # For every day check which area infect more cells visited = set() # Using in dfs All_nextinfect = set() stop , walls = set(),0 # here stop store the indices of maximum no. of cells in which we stop spreading of virus this day for i in range(m): for j in range(n): if mat[i][j]==1 and (i,j) not in visited: nextInfected = set() a = dfs(i,j,visited,nextInfected) if len(stop)<len(nextInfected): All_nextinfect = All_nextinfect | stop # leave previous saved area from virus stop = nextInfected # pick new area which we want to save walls = a # require walls p,q = i,j # starting position(indices) of this area else: All_nextinfect = All_nextinfect | nextInfected if not stop : # if our job is done i.e. No cell will be infect Later break ans += walls # add new walls installed this day # change each cell value to 2 which will be covered by quarantined area def fun(p,q): if 0<=p<m and 0<=q<n and mat[p][q]==1: mat[p][q]=2 fun(p+1,q) fun(p-1,q) fun(p,q-1) fun(p,q+1) fun(p,q) # start dfs from start point of quarantined area for a,b in All_nextinfect: # set new infected cell value = 1 for iterating next day mat[a][b] = 1 return ans # Final answer
contain-virus
Pyhon Easy Solution || DFS || Time O(m*n*max(m , n)) || Faster
Laxman_Singh_Saini
4
378
contain virus
749
0.509
Hard
12,362
https://leetcode.com/problems/contain-virus/discuss/2537505/Python3-brute-force
class Solution: def containVirus(self, isInfected: List[List[int]]) -> int: m, n = len(isInfected), len(isInfected[0]) ans = 0 while True: regions = [] fronts = [] walls = [] seen = set() for i in range(m): for j in range(n): if isInfected[i][j] == 1 and (i, j) not in seen: seen.add((i, j)) stack = [(i, j)] regions.append([(i, j)]) fronts.append(set()) walls.append(0) while stack: r, c = stack.pop() for rr, cc in (r-1, c), (r, c-1), (r, c+1), (r+1, c): if 0 <= rr < m and 0 <= cc < n: if isInfected[rr][cc] == 1 and (rr, cc) not in seen: seen.add((rr, cc)) stack.append((rr, cc)) regions[-1].append((rr, cc)) elif isInfected[rr][cc] == 0: fronts[-1].add((rr, cc)) walls[-1] += 1 if not regions: break idx = fronts.index(max(fronts, key = len)) ans += walls[idx] for i, region in enumerate(regions): if i == idx: for r, c in region: isInfected[r][c] = -1 # mark as quaranteened else: for r, c in fronts[i]: isInfected[r][c] = 1 # mark as infected return ans
contain-virus
[Python3] brute-force
ye15
1
110
contain virus
749
0.509
Hard
12,363
https://leetcode.com/problems/contain-virus/discuss/2643762/DFS-%2B-Heap
class Solution: def containVirus(self, isInfected: List[List[int]]) -> int: # return number of walls needed def dfs(r, c): # return if (r, c) in visited or r < 0 or c < 0 or r >= m or c >= n: return 0 # contained cells if isInfected[r][c] == -1: return 0 # uninfected cells if isInfected[r][c] == 0: risky.add((r, c)) return 1 # infected cells visited.add((r ,c)) walls = 0 if isInfected[r][c] == 1: walls += dfs(r+1, c) walls += dfs(r-1, c) walls += dfs(r, c+1) walls += dfs(r, c-1) return walls m, n = len(isInfected), len(isInfected[0]) total_wall = 0 while True: # store (len(risky), risky, wall, starting points) gettingInfected = [] visited = set() for i in range(m): for j in range(n): if isInfected[i][j] == 1 and isInfected[i][j] not in visited: risky = set() w = dfs(i, j) gettingInfected.append((-len(risky), risky, w, i, j)) # heapy the gettingInfectious array to get the max len of risky heapq.heapify(gettingInfected) if not gettingInfected or gettingInfected[0][2] == 0: return total_wall # mark the infected cells as contained starting from (i, j) lr, risky, w, i, j = heapq.heappop(gettingInfected) # maybe a dfs for marking the cells? queue = collections.deque([(i, j)]) while queue: r, c = queue.pop() if r < 0 or c < 0 or r >= m or c >= n or isInfected[r][c] != 1: continue isInfected[r][c] = -1 queue.append((r+1, c)) queue.append((r-1, c)) queue.append((r, c+1)) queue.append((r, c-1)) # increment the total walls total_wall += w for area in gettingInfected: riskyCells = area[1] for cell in riskyCells: r, c = cell isInfected[r][c] = 1
contain-virus
DFS + Heap
BBBlair
0
32
contain virus
749
0.509
Hard
12,364
https://leetcode.com/problems/open-the-lock/discuss/1251501/Python-or-Bi-directional-A-star-BFS-or-99.7-or-52ms-or-14.3MB
class Solution: def openLock(self, deadends: List[str], end: str) -> int: if end in deadends or "0000" in deadends: return -1 if end == "0000": return 0 start, end, deadends = 0, int(end), {int(deadend) for deadend in deadends} def distance(cur: int, target: int) -> int: diff = 0 for _ in range(4): a, b = cur % 10, target % 10 d = abs(a - b) diff += min(d, 10 - d) cur, target = cur // 10, target // 10 return diff def turn_knob(cur: int, idx: int) -> Tuple[int, int]: index = 10 ** idx digit = cur // index % 10 up = cur - 9 * index if digit == 9 else cur + index down = cur - index if digit else cur + 9 * index return up, down def process( this_q: List[int], this_v: Dict[int, int], other_v: Dict[int, int], target: int ) -> int: _, cur = heappop(this_q) step = this_v[cur] for i in range(4): up, down = turn_knob(cur, i) if up in other_v: return step + other_v[up] + 1 if down in other_v: return step + other_v[down] + 1 if up not in deadends and up not in this_v: this_v[up] = step + 1 this_q.append((distance(up, target), up)) if down not in deadends and down not in this_v: this_v[down] = step + 1 this_q.append((distance(down, target), down)) heapify(this_q) return None s_q, s_v = [(distance(start, end), start)], {start: 0} e_q, e_v = [(distance(end, start), end)], {end: 0} while s_q and e_q: s = process(s_q, s_v, e_v, end) if s: return s e = process(e_q, e_v, s_v, start) if e: return e return -1
open-the-lock
Python | Bi-directional A star, BFS | 99.7% | 52ms | 14.3MB
PuneethaPai
3
110
open the lock
752
0.555
Medium
12,365
https://leetcode.com/problems/open-the-lock/discuss/2106499/Python-or-WITHOUT-STRINGS-or-MEMORY-LESS-THAN-100
class Solution: def openLock(self, deadends: list[str], target: str) -> int: target, turns = int(target), [0] * 10000 for el in deadends: turns[int(el)] = -1 dq = deque([0] * (turns[0] + 1)) while dq: cur = dq.popleft() if cur == target: return turns[cur] for x in (10, 100, 1000, 10000): for k in (1, 9): nxt = cur // x * x + (cur + k * x // 10) % x if not turns[nxt]: dq.append(nxt) turns[nxt] = turns[cur] + 1 return -1
open-the-lock
Python | WITHOUT STRINGS | MEMORY LESS THAN 100%
miguel_v
2
70
open the lock
752
0.555
Medium
12,366
https://leetcode.com/problems/open-the-lock/discuss/916895/Python3-BFS-and-Dijkstra
class Solution: def openLock(self, deadends: List[str], target: str) -> int: ans = 0 queue = ["0000"] deadends = set(deadends) while queue: newq = [] for n in queue: if n not in deadends: deadends.add(n) if n == target: return ans for i in range(4): for chg in (-1, 1): nn = n[:i] + str((int(n[i]) + chg) % 10) + n[i+1:] newq.append(nn) queue = newq ans += 1 return -1
open-the-lock
[Python3] BFS & Dijkstra
ye15
2
134
open the lock
752
0.555
Medium
12,367
https://leetcode.com/problems/open-the-lock/discuss/916895/Python3-BFS-and-Dijkstra
class Solution: def openLock(self, deadends: List[str], target: str) -> int: deadends = set(deadends) if "0000" not in deadends: ans = 0 queue = ["0000"] deadends.add("0000") while queue: newq = [] for n in queue: if n == target: return ans for i in range(4): for chg in (-1, 1): nn = n[:i] + str((int(n[i]) + chg) % 10) + n[i+1:] if nn not in deadends: newq.append(nn) deadends.add(nn) queue = newq ans += 1 return -1
open-the-lock
[Python3] BFS & Dijkstra
ye15
2
134
open the lock
752
0.555
Medium
12,368
https://leetcode.com/problems/open-the-lock/discuss/916895/Python3-BFS-and-Dijkstra
class Solution: def openLock(self, deadends: List[str], target: str) -> int: deadends = set(deadends) if "0000" not in deadends: deadends.add("0000") pq = [(0, "0000")] while pq: k, n = heappop(pq) if n == target: return k for i in range(4): for chg in (-1, 1): nn = n[:i] + str((int(n[i]) + chg) % 10) + n[i+1:] if nn not in deadends: deadends.add(nn) heappush(pq, (k+1, nn)) return -1
open-the-lock
[Python3] BFS & Dijkstra
ye15
2
134
open the lock
752
0.555
Medium
12,369
https://leetcode.com/problems/open-the-lock/discuss/1250796/Open-The-Lock-or-BFS-or-Shortest-Path-or-Python
class Solution: def openLock(self, deadends: List[str], target: str) -> int: if '0000' in deadends: return -1 if '0000' == target: return 0 queue = collections.deque() queue.append(('0000', 0)) visited = set('0000') while queue: node, dist = queue.popleft() if node in deadends: continue if node == target: return dist for i in range(len(node)): num = int(node[i]) # For wrap round we consider both forward and reverse directions. for dx in [-1, 1]: nodeUpdated = node[:i] + str((num + dx) % 10) + node[i+1:] if nodeUpdated not in visited: queue.append((nodeUpdated, dist + 1)) visited.add(nodeUpdated) return -1
open-the-lock
Open The Lock | BFS | Shortest Path | Python
shubh_027
1
104
open the lock
752
0.555
Medium
12,370
https://leetcode.com/problems/open-the-lock/discuss/2834501/Python%3A-BFS
class Solution: def openLock(self, deadends: List[str], target: str) -> int: deadends = set(deadends) def update_lock(state, slot, direction): curr = int(state[slot]) if curr + direction < 0: new = '9' else: new = str((curr + direction) % 9) new_state = state[:slot] + new + state[slot+1:] return(new_state) def bfs(target): queue = [(0, '0000')] seen = set([0]) min_steps = float('inf') while queue: steps, curr_state = queue.pop(0) if curr_state == target: min_steps = min(min_steps, steps) continue else: for i in range(4): for dx in {-1, 1}: new_state = update_lock(curr_state, i, dx) if new_state not in seen and new_state not in deadends: seen.add(new_state) queue.append((steps + 1, new_state)) else: continue return(min_steps if min_steps < float('inf') else -1) if '0000' in deadends: return(-1) else: return(bfs(target))
open-the-lock
Python: BFS
aaroto
0
2
open the lock
752
0.555
Medium
12,371
https://leetcode.com/problems/open-the-lock/discuss/2705992/Python-straightforward-approach-90-fast-and-90-space
class Solution: def openLock(self, deadends: List[str], target: str) -> int: deadends = set(deadends) # makes 2x faster if "0000" in deadends: return -1 if "0000" == target: return 0 memo = {"0000": 0} # state: steps needed to reach state bfs = ["0000"] for s in bfs: # s is current state for i, c in enumerate(s): nxt1 = s[:i] + str((int(c) + 1) % 10) + s[i+1:] nxt2 = s[:i] + str((int(c) - 1) % 10) + s[i+1:] for nxt in {nxt1, nxt2}: if nxt == target: return memo[s] + 1 if nxt not in memo and nxt not in deadends: bfs.append(nxt) memo[nxt] = memo[s] + 1 return -1
open-the-lock
Python straightforward approach [90 % fast and 90 % space]
amuwal
0
6
open the lock
752
0.555
Medium
12,372
https://leetcode.com/problems/open-the-lock/discuss/2352209/python3-O(N)-Time-O(1)-Space-Solution
class Solution: def openLock(self, deadends: List[str], target: str) -> int: #Let n = len(deadends) #Time Complexity: O(n + 80000*4*6) -> O(n) #Space-Complexity: O(10000 + 10000) -> O(1) #base case: if our start point is a deadend, we can't ever reach target since #target is gauranteed to be not in deadends(constriant of the problem) if("0000" in deadends): return -1 queue = collections.deque() #we can keep track of lock combination as well as number of moves it took to raech the #lock combinatoin #each element in queue = [lock_comb, num_of_moves] queue.append(["0000", 0]) #we need to keep track of all lock combinations that already have been tried before #so we don't redo any computation! #hashset visited = set() visited.add("0000") #also, we do not ever want to visit a deadend! #thus, we can just put that in visited set to start off with! for deadend in deadends: visited.add(deadend) #this helper will return array of child lock combinations! def helper(comb): #need to run for loop four times for each of the circular wheel digit! ans = [] for i in range(4): digit = str(((int(comb[i]))+1) % 10) ans.append(comb[:i] + digit + comb[i+1:]) digit = str(((int(comb[i]))-1+10)% 10) ans.append(comb[:i] + digit + comb[i+1:]) return ans #in worst case, we have to process every single combination possible = 10^4 = 10000 while queue: lock, num_of_moves = queue.popleft() #if the lock is the target lock combination, we can imeediately return answer! if(lock == target): return num_of_moves #otherwise, we need to generate the 8 children combinations from current lock #combination! #this for loop runs 8 times! for child_lock in helper(lock): #check that this child_lock has not been tried yet and is not part of deadend! if(child_lock not in visited): queue.append([child_lock, num_of_moves + 1]) visited.add(child_lock) #if we get to this point, we tried every lock combination possible and can't get target! return -1
open-the-lock
python3 O(N) Time O(1) Space Solution
JOON1234
0
54
open the lock
752
0.555
Medium
12,373
https://leetcode.com/problems/open-the-lock/discuss/2300363/Clear-Python-solution-with-BFS
class Solution: def openLock(self, deadends: List[str], target: str) -> int: q = [] visited = set() step = 0 deads = set() q.append("0000") visited.add("0000") for deadend in deadends: deads.add(deadend) while (len(q) > 0): size = len(q) for i in range(size): curr = q.pop(0) # skip if encountering a deadend if (curr in deads): continue if (curr == target): return step for j in range(4): up = self.plusOne(curr, j) if (up not in visited): visited.add(up) q.append(up) down = self.minusOne(curr, j) if (down not in visited): visited.add(down) q.append(down) step += 1 return -1 def plusOne(self, s, j): listStr = list(s) if (listStr[j] == '9'): listStr[j] = '0' else: listStr[j] = str(int(listStr[j]) + 1) return ''.join(listStr) def minusOne(self, s, j): listStr = list(s) if (listStr[j] == '0'): listStr[j] = '9' else: listStr[j] = str(int(listStr[j]) - 1) return ''.join(listStr)
open-the-lock
Clear Python solution with BFS
leqinancy
0
21
open the lock
752
0.555
Medium
12,374
https://leetcode.com/problems/open-the-lock/discuss/2258220/PythonBFSEasy-to-Understand
class Solution: def openLock(self, deadends: List[str], target: str) -> int: start = "0000" # Set to track Deadends deadset = set(deadends) # if the starting position is a deadend, return -1 if start in deadset: return -1 # Add the starting position to the queue with count value as 0 q = [(0,start)] while(q): count, curr = q.pop(0) # if target found, return the count if curr == target: return count #Update +1 and -1 to all positions the lock and add it to he queue along with count+1 for i in range(4): if curr[i] == "0": curr1 = curr[:i] + "1" + curr[i+1:] curr2 = curr[:i] + "9" + curr[i+1:] elif curr[i] == "9": curr1 = curr[:i] + "8" + curr[i+1:] curr2 = curr[:i] + "0" + curr[i+1:] else: curr1 = curr[:i] + str(int(curr[i]) + 1) + curr[i+1:] curr2 = curr[:i] + str(int(curr[i]) - 1) + curr[i+1:] if curr1 not in deadset: q.append([count+1,curr1]) deadset.add(curr1) if curr2 not in deadset: q.append([count+1,curr2]) deadset.add(curr2) return -1
open-the-lock
[Python][BFS][Easy to Understand]
maverick02
0
44
open the lock
752
0.555
Medium
12,375
https://leetcode.com/problems/open-the-lock/discuss/2237155/Python3-oror-BFS
class Solution: def openLock(self, deadends: List[str], target: str) -> int: deadend_set = set(deadends) if "0000" in deadend_set: return -1 queue = deque([(0,"0000")]) visited = set("0000") while queue: steps,char = queue.popleft() if char == target: return steps for idx,c in enumerate(char): new_str1, new_str2 = "","" if c == "0": new_str1 = char[:idx] + "1" + char[idx+1:] new_str2 = char[:idx] + "9" + char[idx+1:] elif c == "9": new_str1 = char[:idx] + "0" + char[idx+1:] new_str2 = char[:idx] + "8" + char[idx+1:] else: new_str1 = char[:idx] + str(int(c)+1) + char[idx+1:] new_str2 = char[:idx] + str(int(c)-1) + char[idx+1:] if new_str1 not in visited and new_str1 not in deadend_set: visited.add(new_str1) queue.append((steps+1,new_str1)) if new_str2 not in visited and new_str2 not in deadend_set: visited.add(new_str2) queue.append((steps+1,new_str2)) return -1
open-the-lock
Python3 || BFS
s_m_d_29
0
26
open the lock
752
0.555
Medium
12,376
https://leetcode.com/problems/open-the-lock/discuss/2216291/Python-Hadlock's-Algorithm-(fast-but-not-simple)
class Solution: def openLock(self, deadends: List[str], target: str) -> int: deadends = set(deadends) # if '0000' is in deadends there's nothing we can do if '0000' in deadends: return -1 target_list = list(map(int, target)) # helper function to get the distance between an array and the target def get_distance(source): distance = 0 for i in range(4): distance += min(abs(target_list[i]-source[i]), source[i]+(10-target_list[i])) return distance distance = get_distance([0,0,0,0]) # Use a stack, primary, to perform DFS iteratively primary = [[[0,0,0,0], '0000', distance]] # Have a secondary stack to keep track of movements that move away from the target secondary = [] # detour is used to keep track of how many steps away from directly moving towards the target we took detour = 0 visited = set() while primary or secondary: # If there's no elements in the primary stack, use the secondary and increment detours if not primary: primary, secondary = secondary, [] detour += 1 code, code_str, prev_dist = primary.pop() if code_str == target: # for each step away, we have to make two steps to get back return distance + detour * 2 visited.add(code_str) # Iterate through all possible changes to the current code for i, num in enumerate(code): for k in range(-1, 2, 2): next_code = list(code[:]) next_code[i] += k if next_code[i] < 0: next_code[i] = 9 elif next_code[i] >= 10: next_code[i] = 0 next_code_str = ''.join(map(str, next_code)) # ensure this iteration doesn't produce a previous result, or an invalid result if next_code_str in visited or next_code_str in deadends: continue next_dist = get_distance(next_code) visited.add(next_code_str) # if this next iteration doesn't take us closer, put it in the secondary stack to check if we don't find our target in primary if prev_dist < next_dist: secondary.append([next_code, next_code_str, next_dist]) else: primary.append([next_code, next_code_str, next_dist]) # we ran out of options, and there's no way to get to the target, return -1 return -1
open-the-lock
[Python] Hadlock's Algorithm (fast, but not simple)
logtd
0
28
open the lock
752
0.555
Medium
12,377
https://leetcode.com/problems/open-the-lock/discuss/2034985/Python-easy-to-read-and-understand-or-BFS-hashmap
class Solution: def __init__(self): self.d = { '0': ['9', '1'], '1': ['0', '2'], '2': ['1', '3'], '3': ['2', '4'], '4': ['3', '5'], '5': ['4', '6'], '6': ['5', '7'], '7': ['6', '8'], '8': ['7', '9'], '9': ['8', '0'], } def openLock(self, deadends: List[str], target: str) -> int: visit = set() visit.add('0000') q = ['0000'] steps = 0 while q: num = len(q) for i in range(num): match = q.pop(0) if match == target: return steps if match in deadends: continue for i in range(4): key = match[i] for j in range(2): temp = match[:i] + self.d[key][j] + match[i+1:] #print(match, temp) if temp not in visit: visit.add(temp) q.append(temp) if q: steps+=1 return -1
open-the-lock
Python easy to read and understand | BFS-hashmap
sanial2001
0
50
open the lock
752
0.555
Medium
12,378
https://leetcode.com/problems/open-the-lock/discuss/1816727/Python-ll-Iterative-BFS
class Solution: def openLock(self, deadends: List[str], target: str) -> int: deadends = set(deadends) if '0000' in deadends: return -1 def neib(code): neighbors = [] for i in range(4): new1 = code[:i] + str((int(code[i])+1)%10) + code[i+1:] new2 = code[:i] + str((int(code[i])-1)%10) + code[i+1:] if new1 not in deadends: neighbors.append(new1) if new2 not in deadends: neighbors.append(new2) return neighbors Q = deque([(0,"0000")]) visited = set() while Q: rank,vertex = Q.popleft() if vertex == target: return rank if vertex in visited: continue visited.add(vertex) for nei in neib(vertex): Q.append((rank+1,nei)) return -1
open-the-lock
Python ll Iterative BFS
morpheusdurden
0
49
open the lock
752
0.555
Medium
12,379
https://leetcode.com/problems/open-the-lock/discuss/1698183/752-Open-the-Lock-via-BFS
class Solution: def openLock(self, deadends, target): visited = set(deadends) q = deque(["0000"]); depth = 0 while q: ### search vertically for the depth of the graph qlen = len(q) for _ in range(qlen): ### search horizontally for the current layer in the graph node = q.popleft() if node == target: return depth if node not in visited: ### if the node is visited or not in deadends, it is impossible to go further from this node visited.add(node) for i in range(4): q.append(self.turnup(node, i)) q.append(self.turndown(node, i)) depth += 1 return -1 def turnup(self, char, i): char = list(char) char[i] = "0" if char[i] == "9" else str(int(char[i]) + 1) return "".join(char) def turndown(self, char, i): char = list(char) char[i] = "9" if char[i] == "0" else str(int(char[i]) - 1) return "".join(char)
open-the-lock
752 Open the Lock via BFS
zwang198
0
33
open the lock
752
0.555
Medium
12,380
https://leetcode.com/problems/open-the-lock/discuss/1251148/Python-O(No.-of-Combinations)-time-and-O(L)-space-solution-using-BFS
class Solution: def openLock(self, deadends: List[str], target: str) -> int: mp, queue, vis, ans = Counter(deadends), deque(), Counter(), 0 if mp['0000'] > 0: return -1 queue.append(['0','0','0','0']) vis['0000'], len_q = 1, 1 while len_q: ans += 1 while len_q: var = queue.popleft() digit = ''.join(var) if digit == target: return ans - 1 for i in range(4): ch = var[i] forw, rev = int(ch) + 1 if int(ch) + 1 < 10 else 9 - int(ch), int(ch) - 1 if int(ch) - 1 >= 0 else 9 + int(ch) for direction in [forw, rev]: var[i] = str(direction) digit = ''.join(var) if mp[digit] == 0 and vis[digit] == 0: queue.append([d for d in digit]) vis[digit] = 1 var[i] = ch len_q -= 1 len_q = len(queue) return -1
open-the-lock
Python O(No. of Combinations) time & O(L) space solution using BFS
m0biu5
0
70
open the lock
752
0.555
Medium
12,381
https://leetcode.com/problems/cracking-the-safe/discuss/2825347/DFS-Solution-in-Python
class Solution: def crackSafe(self, n: int, k: int) -> str: def dfs(path, visitedCombinations, targetNumVisited, combos): # Base Case. We've visited all possible combinations if len(visitedCombinations) == targetNumVisited: combos.append(''.join([str(x) for x in path])) return True # This if/else is necessary to prevent Python from picking up the first element if n = 1 if n > 1: lastDigits = ''.join([str(x) for x in path[-(n-1):]]) else: lastDigits = '' for i in range(k): path.append(i) newPwd = f'{lastDigits}{i}' # We have not reached the minimum pwd length. Continue recursion if len(newPwd) != n: if dfs(path, visitedCombinations, targetNumVisited, combos): return True if len(newPwd) == n and newPwd not in visitedCombinations: visitedCombinations[newPwd] = 1 if dfs(path, visitedCombinations, targetNumVisited, combos): return True del visitedCombinations[newPwd] path.pop() return False # Empty visited Combinations hash set visitedCombinations = {} combos = [] dfs([], visitedCombinations, k**n, combos) return combos[0]
cracking-the-safe
DFS Solution in Python
user0138r
0
1
cracking the safe
753
0.555
Hard
12,382
https://leetcode.com/problems/cracking-the-safe/discuss/2775817/Python-DFS
class Solution: def crackSafe(self, n: int, k: int) -> str: total = k**n-1 start = '0' * n visited = set() visited.add('0' * n) self.ans = '0' * n def dfs(total,start): if total == 0: return True for i in range(k): last = start[1:n] #print(last+str(i)) end = last+str(i) if end not in visited: visited.add(end) total = total-1 self.ans = self.ans+str(i) if dfs(total, end): return True else: visited.remove(end) total = total+1 self.ans = self.ans[:-1] #print("l") return False dfs(total,start) return self.ans
cracking-the-safe
Python DFS
xiwenliu
0
8
cracking the safe
753
0.555
Hard
12,383
https://leetcode.com/problems/reach-a-number/discuss/991390/Python-Dummy-math-solution-easy-to-understand
class Solution: def reachNumber(self, target: int) -> int: target = abs(target) step = 0 far = 0 while far < target or far%2 != target%2: step += 1 far +=step return step
reach-a-number
[Python] Dummy math solution, easy to understand
KevinZzz666
1
47
reach a number
754
0.426
Medium
12,384
https://leetcode.com/problems/reach-a-number/discuss/991282/explained-binary-search-with-a-little-bit-math-(including-a-thinking-process)
class Solution: def reachNumber(self, target: int) -> int: def gaussSum(n): return n*(n+1)//2 def binaryFind(lower, upper): t = abs(target) sums, n = -1, -1 while lower <= upper: mid = (lower+upper)//2 if gaussSum(mid) >= t: sums, n = gaussSum(mid), mid upper = mid-1 else: lower = mid+1 return sums, n lower, upper = 0, 10**5 # find min n s.t. 1+2+...+n>=abs(target) sums, n = binaryFind(lower, upper) while sums%2 != abs(target)%2: sums += n+1 n += 1 return n
reach-a-number
explained binary search with a little bit math (including a thinking process)
ytb_algorithm
1
120
reach a number
754
0.426
Medium
12,385
https://leetcode.com/problems/reach-a-number/discuss/343194/Solution-in-Python-3-(beats-100)-(No-loop-needed!)
class Solution: def reachNumber(self, target: int) -> int: t = abs(target) n = int(((1+8*t)**.5-1)/2) LT = n*(n+1)//2 if LT == t: return n if (LT + n + 1 - t) % 2 == 0: return n + 1 return n + 3 - n % 2 - Python 3 - Junaid Mansuri
reach-a-number
Solution in Python 3 (beats 100%) (No loop needed!)
junaidmansuri
0
374
reach a number
754
0.426
Medium
12,386
https://leetcode.com/problems/pyramid-transition-matrix/discuss/921324/Python3-progressively-building-new-rows
class Solution: def pyramidTransition(self, bottom: str, allowed: List[str]) -> bool: mp = {} for x, y, z in allowed: mp.setdefault((x, y), set()).add(z) def fn(row): """Return list of rows built from given row.""" ans = [""] for x, y in zip(row, row[1:]): if (x, y) not in mp: return [] ans = [xx + zz for xx in ans for zz in mp[x, y]] return ans # dfs stack = [bottom] while stack: row = stack.pop() if len(row) == 1: return True stack.extend(fn(row)) return False
pyramid-transition-matrix
[Python3] progressively building new rows
ye15
2
215
pyramid transition matrix
756
0.531
Medium
12,387
https://leetcode.com/problems/pyramid-transition-matrix/discuss/921324/Python3-progressively-building-new-rows
class Solution: def pyramidTransition(self, bottom: str, allowed: List[str]) -> bool: mp = {} for x, y, z in allowed: mp.setdefault((x, y), set()).add(z) def fn(row): """Return True if row could be built.""" if len(row) == 1: return True for xx in product(*(mp.get((x, y), []) for x, y in zip(row, row[1:]))): if fn(xx): return True return False return fn(bottom)
pyramid-transition-matrix
[Python3] progressively building new rows
ye15
2
215
pyramid transition matrix
756
0.531
Medium
12,388
https://leetcode.com/problems/pyramid-transition-matrix/discuss/1684955/Python-oror-Recursion-oror-Memoization
class Solution: def pyramidTransition(self, bottom: str, allowed: List[str]) -> bool: allowed=set(allowed) letters=['A','B','C','D','E','F'] @lru_cache(None) def solve(bottom): if len(bottom)==1: return True tops=[""] n=len(bottom) ans=False for i in range(n-1): temp=[] while tops: top=tops.pop(0) for letter in letters: if bottom[i]+bottom[i+1]+letter in allowed: temp.append(top+letter) tops=temp for top in tops: ans=ans or solve(top) return ans return solve(bottom)
pyramid-transition-matrix
Python || Recursion || Memoization
ketan_raut
1
143
pyramid transition matrix
756
0.531
Medium
12,389
https://leetcode.com/problems/pyramid-transition-matrix/discuss/2794622/Python-straightforward-DFS-with-heuristic-pruning
class Solution: def pyramidTransition(self, bottom: str, allowed: List[str]) -> bool: mem = dict() mem2 = set() for a in allowed: if a[:2] not in mem: mem[a[:2]] = list() mem2.add(a[0]) mem[a[:2]].append(a[-1]) n = len(bottom) def helper(cur_sol, i, j): if i == n: return True l, r = cur_sol[i - 1][j], cur_sol[i - 1][j + 1] if l + r in mem: for candidate in mem[l + r]: if j == 0 or (j > 0 and cur_sol[i][j - 1] + candidate in mem): if j == n - i - 1 or (j < n - i - 1 and candidate in mem2): cur_sol[i].append(candidate) if j < n - i - 1: next_i, next_j = i, j + 1 else: next_i, next_j = i + 1, 0 if helper(cur_sol, next_i, next_j): return True cur_sol[i].pop() return False cur_sol = [list(bottom)] + [list() for _ in range(n - 1)] return helper(cur_sol, 1, 0)
pyramid-transition-matrix
Python, straightforward DFS with heuristic pruning
yiming999
0
8
pyramid transition matrix
756
0.531
Medium
12,390
https://leetcode.com/problems/set-intersection-size-at-least-two/discuss/2700915/Python-Explained-or-O(nlogn)
class Solution: def intersectionSizeTwo(self, intervals: List[List[int]]) -> int: intervals.sort(key = lambda x:x[1]) size = 0 prev_start = -1 prev_end = -1 for curr_start, curr_end in intervals: if prev_start == -1 or prev_end < curr_start: #if intervals do not overlap size += 2 prev_start = curr_end-1 prev_end = curr_end elif prev_start < curr_start: #if intervals overlap if prev_end != curr_end: prev_start = prev_end prev_end = curr_end else: prev_start = curr_end-1 prev_end = curr_end size += 1 return size
set-intersection-size-at-least-two
Python [Explained] | O(nlogn)
diwakar_4
1
545
set intersection size at least two
757
0.439
Hard
12,391
https://leetcode.com/problems/set-intersection-size-at-least-two/discuss/1569334/Python3-greedy
class Solution: def intersectionSizeTwo(self, intervals: List[List[int]]) -> int: ans = [] for x, y in sorted(intervals, key=lambda x: (x[1], -x[0])): if not ans or ans[-2] < x: if ans and x <= ans[-1]: ans.append(y) else: ans.extend([y-1, y]) return len(ans)
set-intersection-size-at-least-two
[Python3] greedy
ye15
1
311
set intersection size at least two
757
0.439
Hard
12,392
https://leetcode.com/problems/set-intersection-size-at-least-two/discuss/2281243/Sorting-or-Time%3A-O(nlogn)-or-Space%3A-O(n)
class Solution: def intersectionSizeTwo(self, A: List[List[int]]) -> int: A.sort(key=lambda x:(x[1],-x[0])) ans = [] ans.append(A[0][1]-1) ans.append(A[0][1]) n = len(A) # print(A) for i in range(1,n): if A[i][0]>ans[-1]: ans.append(A[i][1]-1) ans.append(A[i][1]) elif A[i][0]>ans[-2]: ans.append(A[i][1]) # print(ans) return len(ans)
set-intersection-size-at-least-two
Sorting | Time: O(nlogn) | Space: O(n)
Shivamk09
0
263
set intersection size at least two
757
0.439
Hard
12,393
https://leetcode.com/problems/special-binary-string/discuss/1498369/Easy-Approach-oror-Well-Explained-oror-Substring
class Solution: def makeLargestSpecial(self, s: str) -> str: l = 0 balance = 0 sublist = [] for r in range(len(s)): balance += 1 if s[r]=='1' else -1 if balance==0: sublist.append("1" + self.makeLargestSpecial(s[l+1:r])+ "0") l = r+1 sublist.sort(reverse=True) return ''.join(sublist)
special-binary-string
πŸ“ŒπŸ“Œ Easy-Approach || Well-Explained || Substring 🐍
abhi9Rai
5
371
special binary string
761
0.604
Hard
12,394
https://leetcode.com/problems/special-binary-string/discuss/1251452/Python3-partition-via-recursion
class Solution: def makeLargestSpecial(self, s: str) -> str: def fn(lo, hi): if lo == hi: return "" vals = [] ii, prefix = lo, 0 for i in range(lo, hi): prefix += 1 if s[i] == "1" else -1 if prefix == 0: vals.append("1" + fn(ii+1, i) + "0") ii = i+1 return "".join(sorted(vals, reverse=True)) return fn(0, len(s))
special-binary-string
[Python3] partition via recursion
ye15
1
325
special binary string
761
0.604
Hard
12,395
https://leetcode.com/problems/prime-number-of-set-bits-in-binary-representation/discuss/1685874/Simple-python-code
class Solution: def isPrime(self,x): flag=0 if x==1: return False for i in range(2,x): if x%i==0: flag=1 break if flag==1: return False return True def countPrimeSetBits(self, left: int, right: int) -> int: arr_dict={} lst=list(range(left,right+1)) for i in lst: if i not in arr_dict: arr_dict[i]=bin(i).replace("0b","") arr=list(arr_dict.values()) count=0 for i in arr: if self.isPrime(i.count('1')): # print(i) count+=1 return count
prime-number-of-set-bits-in-binary-representation
Simple python code
amannarayansingh10
1
105
prime number of set bits in binary representation
762
0.678
Easy
12,396
https://leetcode.com/problems/prime-number-of-set-bits-in-binary-representation/discuss/381146/Solution-in-Python-3-(beats-~98)-(one-line)
class Solution: def countPrimeSetBits(self, L: int, R: int) -> int: return sum(1 for i in range(L,R+1) if bin(i).count('1') in {2,3,5,7,11,13,17,19}) - Junaid Mansuri (LeetCode ID)@hotmail.com
prime-number-of-set-bits-in-binary-representation
Solution in Python 3 (beats ~98%) (one line)
junaidmansuri
1
309
prime number of set bits in binary representation
762
0.678
Easy
12,397
https://leetcode.com/problems/prime-number-of-set-bits-in-binary-representation/discuss/2836218/97.16-or-Python-or-LeetCode-or-762.-Prime-Number-of-Set-Bits-in-Binary-Representation-(Easy)
class Solution: def countPrimeSetBits(self, left: int, right: int) -> int: set_ = {2, 3, 5, 7, 11, 13, 17, 19} h = 0 for i in range(left, right + 1): w = bin(i) count = w.count("1") if count in set_: h += 1 return h
prime-number-of-set-bits-in-binary-representation
97.16 % | Python | LeetCode | 762. Prime Number of Set Bits in Binary Representation (Easy)
UzbekDasturchisiman
0
1
prime number of set bits in binary representation
762
0.678
Easy
12,398
https://leetcode.com/problems/prime-number-of-set-bits-in-binary-representation/discuss/2817836/Python-Easy
class Solution: def countPrimeSetBits(self, left: int, right: int) -> int: from collections import Counter ans = 0 primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 49, 53] for i in range(left, right + 1): tmp = bin(i)[2:] count = Counter(tmp) if count["1"] in primes: ans += 1 return ans
prime-number-of-set-bits-in-binary-representation
Python Easy
lucasschnee
0
2
prime number of set bits in binary representation
762
0.678
Easy
12,399