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/maximize-sum-of-array-after-k-negations/discuss/1587950/Python(40ms)-Faster-than-95-oror-Simplest-logic-oror-No-extra-edge-cases
class Solution: def largestSumAfterKNegations(self, nums: List[int], k: int) -> int: nums.sort() i=0 n = len(nums) while(i<n and k>0): if nums[i]<0: #make it positive nums[i] = -nums[i] k-=1 i+=1 elif nums[i]>=0: break if k%2==1: return sum(nums)-2*(min(nums)) else: return sum(nums) #if k is odd, we will have to take the minimum element 2k+1 times #if its even, we can take whole nums, as it has k nonnegative values
maximize-sum-of-array-after-k-negations
Python(40ms) Faster than 95% || Simplest logic || No extra edge cases
ana_2kacer
1
203
maximize sum of array after k negations
1,005
0.51
Easy
16,400
https://leetcode.com/problems/maximize-sum-of-array-after-k-negations/discuss/1424648/Python3-Nice-Trick-Faster-Than-97.09-Memory-Less-Than-81.00
class Solution: def largestSumAfterKNegations(self, nums: List[int], k: int) -> int: less = False for i in nums: if i < 0: less = True break nums.sort(key = lambda x : abs(x)) if not less: if k % 2 == 0: return sum(nums) else: return sum(nums[1:]) - nums[0] i = len(nums) - 1 while(k > 0): if nums[i] < 0: nums[i] *= -1 k -= 1 i -= 1 if i == 0 and k > 0: if nums[0] > 0: if k % 2 == 0: break else: nums[0] *= -1 break else: if k % 2 == 0: break else: nums[0] *= -1 break return sum(nums)
maximize-sum-of-array-after-k-negations
Python3 Nice Trick Faster Than 97.09%, Memory Less Than 81.00%
Hejita
1
122
maximize sum of array after k negations
1,005
0.51
Easy
16,401
https://leetcode.com/problems/maximize-sum-of-array-after-k-negations/discuss/732238/Simple-python-solution-sort-by-absolute-value.
class Solution: def largestSumAfterKNegations(self, A: List[int], K: int) -> int: A.sort(key=abs, reverse=True) k = 0 for i in range(len(A)): if A[i] < 0: A[i] = -A[i] k += 1 if k >= K: return sum(A) if (K - k) % 2 == 1: A[-1] = -A[-1] return sum(A)
maximize-sum-of-array-after-k-negations
Simple python solution sort by absolute value.
usualwitch
1
595
maximize sum of array after k negations
1,005
0.51
Easy
16,402
https://leetcode.com/problems/maximize-sum-of-array-after-k-negations/discuss/2849415/Python-oror-99-Less-Memory-oror-For-Loop
class Solution: def largestSumAfterKNegations(self, nums: List[int], k: int) -> int: nums.sort() temp = 0 nums[0] *= -1 for i in range(1,k): if nums[temp] == 0: break elif nums[temp] < 0: nums[temp] *= -1 else: nums[nums.index(min(nums))] *= -1 if temp == len(nums)-1: temp = len(nums)-1 else: temp += 1 return sum(nums)
maximize-sum-of-array-after-k-negations
Python || 99% Less Memory || For Loop
Vedant_3907
0
1
maximize sum of array after k negations
1,005
0.51
Easy
16,403
https://leetcode.com/problems/maximize-sum-of-array-after-k-negations/discuss/2787771/Simple-python-solution
class Solution: def largestSumAfterKNegations(self, nums: List[int], k: int) -> int: cons=0 nums.sort() i=0 while i<len(nums) and k>0: if nums[i]<0: nums[i]=nums[i]*(-1) i+=1 k-=1 cons+=1 elif nums[i]==0: k=0 elif nums[i]>0 and cons==0: if k%2==1: nums[i]=nums[i]*(-1) k=0 elif nums[i]>0 and cons>0 and k%2==1: if abs(nums[i])<=nums[i-1]: nums[i]=nums[i]*(-1) else: nums[i-1]=nums[i-1]*(-1) k=0 elif nums[i]>0 and cons>0 and k%2==0: k=0 if i==len(nums) and k>0: i-=1 return sum(nums)
maximize-sum-of-array-after-k-negations
Simple python solution
Aadesh_Aadi
0
3
maximize sum of array after k negations
1,005
0.51
Easy
16,404
https://leetcode.com/problems/maximize-sum-of-array-after-k-negations/discuss/2787701/Python-Concise-Solution
class Solution: def largestSumAfterKNegations(self, nums: List[int], k: int) -> int: for _ in range(k): min_value = min(nums) min_index = nums.index(min_value) nums[min_index] *= -1 return sum(nums)
maximize-sum-of-array-after-k-negations
Python Concise Solution
namashin
0
4
maximize sum of array after k negations
1,005
0.51
Easy
16,405
https://leetcode.com/problems/maximize-sum-of-array-after-k-negations/discuss/2766709/easiest-solution-to-understand-in-Python
class Solution: def largestSumAfterKNegations(self, nums: List[int], k: int) -> int: pos = [] neg = [] zero = [] for n in nums: if n == 0: zero.append(n) elif n > 0: pos.append(n) else: neg.append(n) neg.sort() if len(neg) > k: i = 0 while k > 0: neg[i] = - neg[i] i += 1 k -= 1 return sum(pos) + sum(neg) else: i = 0 while i < len(neg): neg[i] = - neg[i] i += 1 k -= 1 if len(zero) != 0: return sum(pos) + sum(neg) else: if k%2 == 0: return sum(pos) + sum(neg) else: res = pos + neg return sum(pos) + sum(neg) - 2*min(res)
maximize-sum-of-array-after-k-negations
easiest solution to understand in Python
neeshumaini55
0
3
maximize sum of array after k negations
1,005
0.51
Easy
16,406
https://leetcode.com/problems/maximize-sum-of-array-after-k-negations/discuss/2765460/Python-1-Using-Sort-2-Using-Heap
class Solution: def largestSumAfterKNegations(self, nums: List[int], k: int) -> int: nums.sort() for i in range(k): nums[0]=-nums[0] nums.sort() return sum(nums)
maximize-sum-of-array-after-k-negations
Python [1] Using Sort [2] Using Heap
mehtay037
0
2
maximize sum of array after k negations
1,005
0.51
Easy
16,407
https://leetcode.com/problems/maximize-sum-of-array-after-k-negations/discuss/2765460/Python-1-Using-Sort-2-Using-Heap
class Solution: def largestSumAfterKNegations(self, nums: List[int], k: int) -> int: heapify(nums) #print(nums) while k>0: heapq.heappush(nums,-(heapq.heappop(nums))) k-=1 return sum(nums)
maximize-sum-of-array-after-k-negations
Python [1] Using Sort [2] Using Heap
mehtay037
0
2
maximize sum of array after k negations
1,005
0.51
Easy
16,408
https://leetcode.com/problems/maximize-sum-of-array-after-k-negations/discuss/2616308/python-easy-solution-
class Solution: def largestSumAfterKNegations(self, nums: List[int], k: int) -> int: for i in range(k): k=min(nums) index=nums.index(k) nums.pop(index) nums.insert(index,-k) return sum(nums)
maximize-sum-of-array-after-k-negations
python easy solution --------
Shreya_sg_283
0
11
maximize sum of array after k negations
1,005
0.51
Easy
16,409
https://leetcode.com/problems/maximize-sum-of-array-after-k-negations/discuss/2514790/Python-heap
class Solution: def largestSumAfterKNegations(self, nums: List[int], k: int) -> int: import heapq heapq.heapify(nums) while k!=0: node=heapq.heappop(nums) heapq.heappush(nums,-1*(node)) k-=1 return sum(nums)
maximize-sum-of-array-after-k-negations
Python heap
deepanshu704281
0
29
maximize sum of array after k negations
1,005
0.51
Easy
16,410
https://leetcode.com/problems/maximize-sum-of-array-after-k-negations/discuss/2314972/Python-Solution-Simple
class Solution: def largestSumAfterKNegations(self, nums: List[int], k: int) -> int: nums.sort() i = 0 while k>0 and i<len(nums) and nums[i]<=0: nums[i] = -nums[i] k-=1 i+=1 nums.sort() while k>0: nums[0] = -nums[0] k-=1 return sum(nums)
maximize-sum-of-array-after-k-negations
Python Solution Simple
Abhi_009
0
54
maximize sum of array after k negations
1,005
0.51
Easy
16,411
https://leetcode.com/problems/maximize-sum-of-array-after-k-negations/discuss/2143637/Python-easy-solution-with-explanation
class Solution: def largestSumAfterKNegations(self, nums: List[int], k: int) -> int: #First we'll sort the values in nums nums.sort() # Then first perform operation on negative values and make it positive if there is any negative value for i in range(len(nums)): if(nums[i]<0 and k!=0): nums[i]= -nums[i] # Taking negative of negative values to make it positive k-=1 # Decrementing the value of k after every operation nums.sort() # After iteration again sorting to make least value come first so that making it negative every time will not affect the overall maximum sum while(k>0): # Again till the time k is not equal to 0, make the 1st value always negative so that the overall sum won't affect too much. nums[0]=-nums[0] # Making the 1st value as negative. k-=1 # Decrementing k till it is not 0 and it will automatically come out of loop return sum(nums) # At last return the sum of overall element present in nums.
maximize-sum-of-array-after-k-negations
Python easy solution with explanation
yashkumarjha
0
49
maximize sum of array after k negations
1,005
0.51
Easy
16,412
https://leetcode.com/problems/maximize-sum-of-array-after-k-negations/discuss/1810878/3-Lines-Python-Solution-oror-70-Faster-oror-Memory-less-than-60
class Solution: def largestSumAfterKNegations(self, nums: List[int], k: int) -> int: heapify(nums) for _ in range(k): heapreplace(nums, -nums[0]) return sum(nums)
maximize-sum-of-array-after-k-negations
3-Lines Python Solution || 70% Faster || Memory less than 60%
Taha-C
0
55
maximize sum of array after k negations
1,005
0.51
Easy
16,413
https://leetcode.com/problems/maximize-sum-of-array-after-k-negations/discuss/1584758/Python-sol-faster-than-88
class Solution: def largestSumAfterKNegations(self, nums: List[int], k: int) -> int: nums.sort() i = 0 while i < len(nums) and nums[i] < 0 and k > 0 : nums[i] = -1 * nums[i] i += 1 k -= 1 if k == 0: return sum(nums) if k % 2 == 1: return sum(nums) - (2 * (min(nums))) return sum(nums)
maximize-sum-of-array-after-k-negations
Python sol faster than 88%
elayan
0
93
maximize sum of array after k negations
1,005
0.51
Easy
16,414
https://leetcode.com/problems/maximize-sum-of-array-after-k-negations/discuss/1563384/Python3-dollarolution-(91-faster-and-81-better-mem)
class Solution: def largestSumAfterKNegations(self, nums: List[int], k: int) -> int: i, x = 0, 0 nums = sorted(nums) while i < len(nums) and nums[i] < 0 and k > 0: nums[i] *= -1 k -= 1 i += 1 if k > 0: if k % 2 != 0: x = 2 * min(nums) return sum(nums) - x
maximize-sum-of-array-after-k-negations
Python3 $olution (91% faster and 81% better mem)
AakRay
0
77
maximize sum of array after k negations
1,005
0.51
Easy
16,415
https://leetcode.com/problems/maximize-sum-of-array-after-k-negations/discuss/1210000/Python3-simple-solution-beats-almost-90-users
class Solution: def largestSumAfterKNegations(self, nums: List[int], k: int) -> int: total = 0 pos = [] neg = [] flag = (k%2 == 0) for i in nums: if i <= 0: neg.append(i) else: pos.append(i) total += abs(i) neg.sort() pos.sort() if neg: if k <= len(neg): return total + 2*(sum(neg[k:])) else: if (k-len(neg))%2 == 0: return total else: return total - 2*(min(pos[0],abs(neg[-1]))) else: if not flag: return total - 2*pos[0]
maximize-sum-of-array-after-k-negations
Python3 simple solution beats almost 90% users
EklavyaJoshi
0
39
maximize sum of array after k negations
1,005
0.51
Easy
16,416
https://leetcode.com/problems/maximize-sum-of-array-after-k-negations/discuss/1192549/2-line-solution-in-python3
class Solution: def largestSumAfterKNegations(self, a: List[int], k: int) -> int: while k: a[a.index(min(a))]=-min(a) k-=1 return sum(a)
maximize-sum-of-array-after-k-negations
2 line solution in python3
janhaviborde23
0
93
maximize sum of array after k negations
1,005
0.51
Easy
16,417
https://leetcode.com/problems/maximize-sum-of-array-after-k-negations/discuss/810094/Python3-simple-and-clean
class Solution: def largestSumAfterKNegations(self, A: List[int], k: int) -> int: A.sort() max_sum = 0 i = 0 while i < len(A) and k > 0: if A[i] >= 0: break k -= 1 max_sum += -A[i] i += 1 if k <= 0 or i >= len(A): return max_sum + sum(A[i:]) if k % 2 == 1: if i > 0 and A[i] > -A[i-1]: max_sum += 2*A[i-1] else: max_sum += -A[i] i += 1 return max_sum + sum(A[i:]) return max_sum + sum(A[i:])
maximize-sum-of-array-after-k-negations
Python3 simple and clean
Abhay-D
0
77
maximize sum of array after k negations
1,005
0.51
Easy
16,418
https://leetcode.com/problems/maximize-sum-of-array-after-k-negations/discuss/626231/Intuitive-approach-by-sorting-A-after-action-so-we-can-only-pay-attention-to-the-first-element
class Solution: def largestSumAfterKNegations(self, A: List[int], K: int) -> int: A = sorted(A) while K > 0: if A[0] < 0: A[0] *= -1 elif A[0] == 0: break else: A[0] *= -1 A = sorted(A) K -= 1 return sum(A)
maximize-sum-of-array-after-k-negations
Intuitive approach by sorting A after action so we can only pay attention to the first element
puremonkey2001
0
35
maximize sum of array after k negations
1,005
0.51
Easy
16,419
https://leetcode.com/problems/maximize-sum-of-array-after-k-negations/discuss/626231/Intuitive-approach-by-sorting-A-after-action-so-we-can-only-pay-attention-to-the-first-element
class Solution: def largestSumAfterKNegations(self, A: List[int], K: int) -> int: A = sorted(A) while K > 0: if A[0] < 0: A.append(A[0] * -1) del A[0] elif A[0] == 0: break else: A = sorted(A) if K % 2 == 1: A[0] *= -1 break K -= 1 return sum(A)
maximize-sum-of-array-after-k-negations
Intuitive approach by sorting A after action so we can only pay attention to the first element
puremonkey2001
0
35
maximize sum of array after k negations
1,005
0.51
Easy
16,420
https://leetcode.com/problems/maximize-sum-of-array-after-k-negations/discuss/403196/Needs-input-to-make-it-faster-86-faster-100-less-memory
class Solution(object): def largestSumAfterKNegations(self, A, k): """ :type A: List[int] :type K: int :rtype: int """ sortedA = sorted(A) if(sortedA[0]>0): if(k%2==0): return sum(A) else: sortedA[0] = -sortedA[0] return sum(sortedA) else: count = 0 for i in sortedA: if(i<0): count += 1 temp = k-count if(temp >= 0): for i in range(0,count): sortedA[i] = -sortedA[i] if(temp%2 != 0): if(sortedA[count-1] > sortedA[count]): sortedA[count] = -sortedA[count] else: sortedA[count-1] = -sortedA[count-1] else: for i in range(0,k): sortedA[i] = -sortedA[i] return sum(sortedA)
maximize-sum-of-array-after-k-negations
Needs input to make it faster; 86% faster, 100% - less memory,
logan_kd
0
92
maximize sum of array after k negations
1,005
0.51
Easy
16,421
https://leetcode.com/problems/maximize-sum-of-array-after-k-negations/discuss/300814/Brutal-force-with-Python3-solution
class Solution: def largestSumAfterKNegations(self, A: List[int], K: int) -> int: while K>0: ind=A.index(min(A)) A[ind]=-A[ind] K-=1 return sum(A)
maximize-sum-of-array-after-k-negations
Brutal force with Python3 solution
JasperZhou
0
45
maximize sum of array after k negations
1,005
0.51
Easy
16,422
https://leetcode.com/problems/maximize-sum-of-array-after-k-negations/discuss/1065626/Python-Fast-Using-Heap
class Solution: def largestSumAfterKNegations(self, A: List[int], K: int) -> int: heapq.heapify(A) for i in range(K): heapq.heappush(A,-1 * heapq.heappop(A)) return sum(A)
maximize-sum-of-array-after-k-negations
Python [Fast] Using Heap
Akarsh_B
-1
46
maximize sum of array after k negations
1,005
0.51
Easy
16,423
https://leetcode.com/problems/clumsy-factorial/discuss/395085/Three-Solutions-in-Python-3-(beats-~99)-(one-line)
class Solution: def clumsy(self, N: int) -> int: return N + ([1,2,2,-1][N % 4] if N > 4 else [0,0,0,3,3][N])
clumsy-factorial
Three Solutions in Python 3 (beats ~99%) (one line)
junaidmansuri
3
525
clumsy factorial
1,006
0.55
Medium
16,424
https://leetcode.com/problems/clumsy-factorial/discuss/395085/Three-Solutions-in-Python-3-(beats-~99)-(one-line)
class Solution: def clumsy(self, N: int) -> int: return eval(str(N)+''.join([['*','//','+','-'][(N-i-1)%4]+str(i) for i in range(N-1,0,-1)]))
clumsy-factorial
Three Solutions in Python 3 (beats ~99%) (one line)
junaidmansuri
3
525
clumsy factorial
1,006
0.55
Medium
16,425
https://leetcode.com/problems/clumsy-factorial/discuss/395085/Three-Solutions-in-Python-3-(beats-~99)-(one-line)
class Solution: def clumsy(self, N: int) -> int: a, n, b = 0, N, N >= 4 if b: a, n = n*(n-1)//(n-2)+(n-3), n - 4 while n >= 4: a, n = a - n*(n-1)//(n-2)+(n-3), n - 4 return a + [0,-1,-2,-6][n]*(2*b-1) - Junaid Mansuri (LeetCode ID)@hotmail.com
clumsy-factorial
Three Solutions in Python 3 (beats ~99%) (one line)
junaidmansuri
3
525
clumsy factorial
1,006
0.55
Medium
16,426
https://leetcode.com/problems/clumsy-factorial/discuss/1252299/easy-solution-in-python
class Solution: def clumsy(self, n: int) -> int: res="" j=-1 for i in range(n,0,-1): res+=str(i) j+=1 if j <n-1: if j%4==0 : res+="*" elif j%4==1: res+="//" elif j%4==2: res+="+" elif j%4==3: res+="-" return (eval(res))
clumsy-factorial
easy solution in python
janhaviborde23
1
135
clumsy factorial
1,006
0.55
Medium
16,427
https://leetcode.com/problems/clumsy-factorial/discuss/2737628/Easy-Python-or-O(1)-solution
class Solution: def __init__ (self): self.base_cases = [1, 2, 6, 7] self.offsets = [2, 2, -1, 1] def clumsy(self, n: int) -> int: if n <= 4: return self.base_cases [n - 1] return n + self.offsets[(n + 3) % 4]
clumsy-factorial
Easy Python | O(1) solution
on_danse_encore_on_rit_encore
0
6
clumsy factorial
1,006
0.55
Medium
16,428
https://leetcode.com/problems/clumsy-factorial/discuss/2147205/Python3-Iterative-Intuition
class Solution: # Iterative, Time = O(N), Space = O(1) def clumsy(self, n: int) -> int: # Idea is to complete the steps from n, backwards # Using intuitive solution, following the steps # as specified total = 0 curr = n ops = 0 # [*, /, +] # Obtain initial positive value ONLY from the first # 4 values. Note that curr = n for the beginning for i in range(n-1, n-4, -1): if i < 1: break match ops%3: case 0: curr *= i case 1: curr //= i case 2: curr += i ops += 1 ops %= 3 total += curr # Return if no subtraction was needed if n < 5: return total ops = 0 # [+ CURR, * CURR, / CURR AND - FROM TOTAL, + TOTAL] curr = 0 # Continue where we left off (n - 4) for i in range(n-4, 0, -1): match ops%4: case 0: curr += i case 1: curr *= i case 2: curr //= i total -= curr curr = 0 case 3: total += i curr = 0 ops += 1 ops %= 4 return total - curr
clumsy-factorial
[Python3] Iterative Intuition
betaRobin
0
44
clumsy factorial
1,006
0.55
Medium
16,429
https://leetcode.com/problems/clumsy-factorial/discuss/462637/44ms-python3-easy-to-understand
class Solution: def clumsy(self, N: int) -> int: if N==1: return 1 if N==2: return 2 if N==3: return 6 res = 0 for m in range(N//4): if m==0: res += (N-m*4)*(N-m*4-1)//(N-m*4-2)+(N-m*4-3) else: res -= (N-m*4)*(N-m*4-1)//(N-m*4-2)-(N-m*4-3) if N%4==0: return res if N%4==1: return res-1 if N%4==2: return res-2 if N%4==3: return res-6
clumsy-factorial
44ms python3, easy to understand
felicia1994
0
178
clumsy factorial
1,006
0.55
Medium
16,430
https://leetcode.com/problems/clumsy-factorial/discuss/1388158/Python-Very-simple-Runtime%3A-32-ms-faster-than-93.37
class Solution: def clumsy(self, n: int) -> int: if n == 1 or n == 2: return n if n >= 3: fact = n * (n - 1) // (n - 2) n -= 3 while n - 4 >= 0: fact = fact + n - (n - 1) * (n - 2) // (n - 3) n -= 4 if n > 0: fact += n n = n - 1 if n > 0: fact -= n n = n- 1 return fact
clumsy-factorial
[Python} [Very simple] Runtime: 32 ms, faster than 93.37%
G_Venkatesh
-1
158
clumsy factorial
1,006
0.55
Medium
16,431
https://leetcode.com/problems/minimum-domino-rotations-for-equal-row/discuss/1865333/Python3-UNPRECENDENT-NUMBER-OF-COUNTERS-o()o-Explained
class Solution: def minDominoRotations(self, tops: List[int], bottoms: List[int]) -> int: total = len(tops) top_fr, bot_fr, val_total = [0]*7, [0]*7, [total]*7 for top, bot in zip(tops, bottoms): if top == bot: val_total[top] -= 1 else: top_fr[top] += 1 bot_fr[bot] += 1 for val in range(1, 7): if (val_total[val] - top_fr[val]) == bot_fr[val]: return min(top_fr[val], bot_fr[val]) return -1
minimum-domino-rotations-for-equal-row
✔️[Python3] UNPRECENDENT NUMBER OF COUNTERS o͡͡͡͡͡͡͡͡͡͡͡͡͡͡╮(。❛ᴗ❛。)╭o͡͡͡͡͡͡͡͡͡͡͡͡͡͡, Explained
artod
23
1,100
minimum domino rotations for equal row
1,007
0.524
Medium
16,432
https://leetcode.com/problems/minimum-domino-rotations-for-equal-row/discuss/1865339/Python-Simple-Python-Solution-Using-Dictionary-or-Hashmap-oror-O(n)
class Solution: def minDominoRotations(self, tops: List[int], bottoms: List[int]) -> int: frequency_tops = {1:0,2:0,3:0,4:0,5:0,6:0} for i in tops: if i not in frequency_tops: frequency_tops[i] = 1 else: frequency_tops[i] = frequency_tops[i] + 1 frequency_bottoms = {1:0,2:0,3:0,4:0,5:0,6:0} for i in bottoms: if i not in frequency_bottoms: frequency_bottoms[i] = 1 else: frequency_bottoms[i] = frequency_bottoms[i] + 1 swap_number = 0 for i in range(1,7): if frequency_tops[i] + frequency_bottoms[i] >= len(tops): swap_number = i if swap_number == 0: return -1 min_num1 = len(tops)-frequency_tops[swap_number] min_num2 = len(bottoms)-frequency_bottoms[swap_number] for i in range(len(tops)): if swap_number not in [tops[i],bottoms[i]]: return -1 return min(min_num1,min_num2)
minimum-domino-rotations-for-equal-row
[ Python ] ✔✔ Simple Python Solution Using Dictionary or Hashmap || O(n) 🔥✌
ASHOK_KUMAR_MEGHVANSHI
3
486
minimum domino rotations for equal row
1,007
0.524
Medium
16,433
https://leetcode.com/problems/minimum-domino-rotations-for-equal-row/discuss/1867514/Use-Sets-for-Easily-Solving-It
class Solution: def minDominoRotations(self, tops: List[int], bottoms: List[int]) -> int: n = len(tops) inter = {tops[0], bottoms[0]} for i in range(n): inter = inter.intersection({tops[i], bottoms[i]}) # This gives us the finaly common values b/w all the indices. if len(inter) == 0: # Case 1 return -1 elif len(inter) == 2: # Case 3 target = inter.pop() m = tops.count(target) return min(m, n-m) else: # Case 2 for_tops = for_bottom = 0 target = inter.pop() target_in_tops = tops.count(target) target_in_bottoms = bottoms.count(target) return n - max(target_in_tops, target_in_bottoms)
minimum-domino-rotations-for-equal-row
Use Sets for Easily Solving It
anCoderr
2
151
minimum domino rotations for equal row
1,007
0.524
Medium
16,434
https://leetcode.com/problems/minimum-domino-rotations-for-equal-row/discuss/2612144/Python3-solution
class Solution: def minDominoRotations(self, tops: List[int], bottoms: List[int]) -> int: nlen = len(tops) top_count = {1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0} bottom_count = {1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0} both_count = {1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0} i = 0 while i < nlen: top_count[tops[i]] += 1 bottom_count[bottoms[i]] += 1 if tops[i] == bottoms[i]: both_count[bottoms[i]] += 1 i += 1 print(top_count) print(bottom_count) print(both_count) res = 30000 for i in range(1, 7): if top_count[i] + bottom_count[i] - both_count[i] == nlen: res = min(res, min(top_count[i], bottom_count[i]) - both_count[i]) if res == 30000: return -1 return res
minimum-domino-rotations-for-equal-row
Python3 solution
alih107
0
13
minimum domino rotations for equal row
1,007
0.524
Medium
16,435
https://leetcode.com/problems/minimum-domino-rotations-for-equal-row/discuss/2010682/Simple-python-O(n)-solution-faster-than-99
class Solution: def minDominoRotations(self, tops: List[int], bottoms: List[int]) -> int: x=tops[0] y=bottoms[0] res=-1 fx=1 fy=1 for i in range(len(tops)): if tops[i]==x or bottoms[i]==x: continue else: fx=0 break for i in range(len(tops)): if tops[i]==y or bottoms[i]==y: continue else: fy=0 break if fx==0 and fy==0: return -1 res=100000 if fx==1: a=tops.count(x) b=bottoms.count(x) res=len(tops)-(max(a,b)) if fy==1: a=tops.count(y) b=bottoms.count(y) res=min(res,len(tops)-(max(a,b))) return res
minimum-domino-rotations-for-equal-row
Simple python O(n) solution, faster than 99%
pbhuvaneshwar
0
71
minimum domino rotations for equal row
1,007
0.524
Medium
16,436
https://leetcode.com/problems/minimum-domino-rotations-for-equal-row/discuss/1867314/Python-simple-single-pass-approaches-using-set-intersection
class Solution: def minDominoRotations(self, tops: List[int], bottoms: List[int]) -> int: present_in_all = {tops[0], bottoms[0]} top_count = defaultdict(int) top_count[tops[0]] += 1 bottom_count = defaultdict(int) bottom_count[bottoms[0]] += 1 for i in range(1, len(tops)): top = tops[i] bottom = bottoms[i] present_in_all &amp;= {top, bottom} if len(present_in_all) == 0: return -1 if top in present_in_all: top_count[top] += 1 if bottom in present_in_all: bottom_count[bottom] += 1 min_swaps = len(tops) for present_in_all_el in present_in_all: min_swaps_el = len(tops) - max(top_count[present_in_all_el], bottom_count[present_in_all_el]) min_swaps = min(min_swaps, min_swaps_el) break return min_swaps
minimum-domino-rotations-for-equal-row
Python simple single pass approaches using set intersection
H2Oaq
0
26
minimum domino rotations for equal row
1,007
0.524
Medium
16,437
https://leetcode.com/problems/minimum-domino-rotations-for-equal-row/discuss/1867314/Python-simple-single-pass-approaches-using-set-intersection
class Solution: def minDominoRotations(self, tops: List[int], bottoms: List[int]) -> int: present_in_all = {tops[0], bottoms[0]} for i in range(1, len(tops)-1): present_in_all &amp;= {tops[i], bottoms[i]} if len(present_in_all) == 0: return -1 # case 1 present_in_all_el = None for el in present_in_all: present_in_all_el = el break # case 3 not_in_tops = 0 not_in_bottoms = 0 for i in range(len(tops)): if tops[i] != present_in_all_el: not_in_tops += 1 if bottoms[i] != present_in_all_el: not_in_bottoms += 1 return min(not_in_tops, not_in_bottoms) # case 2
minimum-domino-rotations-for-equal-row
Python simple single pass approaches using set intersection
H2Oaq
0
26
minimum domino rotations for equal row
1,007
0.524
Medium
16,438
https://leetcode.com/problems/minimum-domino-rotations-for-equal-row/discuss/1867093/Python3-Solution-with-using-greedy-approach
class Solution: def bypass(self, _0, first, second): swap_cnt1 = swap_cnt2 = 0 len_arr = len(first) for i in range(len_arr): if first[i] != _0 and second[i] != _0: return -1 elif first[i] != _0: swap_cnt1 += 1 elif second[i] != _0: swap_cnt2 += 1 return min(swap_cnt1, swap_cnt2) def minDominoRotations(self, tops: List[int], bottoms: List[int]) -> int: top_0 = tops[0] bottom_0 = bottoms[0] cnt1 = self.bypass(top_0, tops, bottoms) cnt2 = self.bypass(bottom_0, tops, bottoms) if cnt1 == -1: return cnt2 if cnt2 == -1: return cnt1 return min(cnt1, cnt2)
minimum-domino-rotations-for-equal-row
[Python3] Solution with using greedy approach
maosipov11
0
8
minimum domino rotations for equal row
1,007
0.524
Medium
16,439
https://leetcode.com/problems/minimum-domino-rotations-for-equal-row/discuss/1865923/Simple-Python3-Solution
class Solution: def minDominoRotations(self, tops: List[int], bottoms: List[int]) -> int: frequency_tops = {1:0,2:0,3:0,4:0,5:0,6:0} for i in tops: if i not in frequency_tops: frequency_tops[i] = 1 else: frequency_tops[i] = frequency_tops[i] + 1 frequency_bottoms = {1:0,2:0,3:0,4:0,5:0,6:0} for i in bottoms: if i not in frequency_bottoms: frequency_bottoms[i] = 1 else: frequency_bottoms[i] = frequency_bottoms[i] + 1 swap_number = 0 for i in range(1,7): if frequency_tops[i] + frequency_bottoms[i] >= len(tops): swap_number = i if swap_number == 0: return -1 min_num1 = len(tops)-frequency_tops[swap_number] min_num2 = len(bottoms)-frequency_bottoms[swap_number] for i in range(len(tops)): if swap_number not in [tops[i],bottoms[i]]: return -1 return min(min_num1,min_num2)
minimum-domino-rotations-for-equal-row
Simple Python3 Solution
user6774u
0
6
minimum domino rotations for equal row
1,007
0.524
Medium
16,440
https://leetcode.com/problems/minimum-domino-rotations-for-equal-row/discuss/1865535/Python3-Solution
class Solution(object): def minDominoRotations(self, A, B): n = len(A) cntA = [0] * 7 cntB = [0] * 7 cntSame = [0] * 7 for i in range(n): a, b = A[i], B[i] cntA[a] += 1 cntB[b] += 1 if a == b: cntSame[a] += 1 ans = n for v in range(1, 7): if cntA[v] + cntB[v] - cntSame[v] == n: minSwap = min(cntA[v], cntB[v]) - cntSame[v] ans = min(ans, minSwap) return -1 if ans == n else ans
minimum-domino-rotations-for-equal-row
Python3 Solution
nomanaasif9
0
22
minimum domino rotations for equal row
1,007
0.524
Medium
16,441
https://leetcode.com/problems/minimum-domino-rotations-for-equal-row/discuss/1865509/Python-solution-using-hashmap
class Solution: def minDominoRotations(self, tops: List[int], bottoms: List[int]) -> int: def get_min(arr1, arr2): hash_map = {} min_val = float('+inf') for i in range(len(arr1)): if arr1[i] in hash_map.keys(): continue cur_val, count, swap_count = arr1[i], 0, 0 for j in range(len(arr1)): if i == j or arr1[j] == cur_val: count += 1 elif arr2[j] == cur_val: count += 1 swap_count += 1 if count == len(arr1): min_val = min(min_val, swap_count) hash_map[arr1[i]] = min_val return min_val top_min = get_min(tops, bottoms) bottom_min = get_min(bottoms, tops) if top_min == float('+inf') and bottom_min == float('+inf'): return -1 if top_min != float('+inf') and bottom_min != float('+inf'): return min(top_min, bottom_min) else: if top_min == float('+inf'): return bottom_min else: return top_min
minimum-domino-rotations-for-equal-row
Python solution, using hashmap
pradeep288
0
20
minimum domino rotations for equal row
1,007
0.524
Medium
16,442
https://leetcode.com/problems/minimum-domino-rotations-for-equal-row/discuss/902017/Python-Clean-and-Simple
class Solution: def minDominoRotations(self, A: List[int], B: List[int]) -> int: l = len(A) possibles = [A[0], B[0]] if A[0] != B[0] else [A[0]] for p in possibles: a, b, i = 0, 0, l-1 while i >= 0: if A[i] != p and B[i] != p: break if A[i] != p: a += 1 if B[i] != p: b += 1 i -= 1 if i < 0: return min(a, b) return -1
minimum-domino-rotations-for-equal-row
[Python] Clean & Simple
yo1995
0
41
minimum domino rotations for equal row
1,007
0.524
Medium
16,443
https://leetcode.com/problems/minimum-domino-rotations-for-equal-row/discuss/901940/Python3-greedy
class Solution: def minDominoRotations(self, A: List[int], B: List[int]) -> int: def fn(k): """Return min swap to get all k in one array.""" xx = yy = 0 for x, y in zip(A, B): if x != k and y != k: return inf if x != k and y == k: xx += 1 if x == k and y != k: yy += 1 return min(xx, yy) ans = min(fn(A[0]), fn(B[0])) return ans if ans < inf else -1
minimum-domino-rotations-for-equal-row
[Python3] greedy
ye15
0
38
minimum domino rotations for equal row
1,007
0.524
Medium
16,444
https://leetcode.com/problems/minimum-domino-rotations-for-equal-row/discuss/901694/Simple-solution-in-python-looking-for-improvement
class Solution: def minDominoRotations(self, A: List[int], B: List[int]) -> int: if not(A and B): return 0 # A set that store the first dominoe # One of them must appears in all dominoes ab0 = (A[0], B[0]) # Count the number of A[0] appears [ top half, bottom half ] a0 = [1,0] # Count the number of B[0] appears [ top half, bottom half ] b0 = [0,1] length = len(A) for i in range(1,length): # If A[0] doesn't exist in both A and B in i-th index # That number cannot form a equal row if ab0[0] != A[i] and ab0[0] != B[i]: a0 = [0] # If B[0] doesn't exist in both A and B in i-th index # That number cannot form a equal row if ab0[1] != A[i] and ab0[1] != B[i]: b0 = [0] # If both A[0] and B[0] are not possible to form equal row, End of world :) if a0 == [0] and b0 == [0]: return -1 # Below just do the count of A[0]/B[0] occurance in row A/B if a0 != [0] and A[i] == ab0[0]: a0[0] += 1 if a0 != [0] and B[i] == ab0[0]: a0[1] += 1 if b0 != [0] and A[i] == ab0[1]: b0[0] += 1 if b0 != [0] and B[i] == ab0[1]: b0[1] += 1 return length-max(max(a0),max(b0))
minimum-domino-rotations-for-equal-row
Simple solution in python, looking for improvement
M0UZ337
0
29
minimum domino rotations for equal row
1,007
0.524
Medium
16,445
https://leetcode.com/problems/minimum-domino-rotations-for-equal-row/discuss/901499/Python-Solution-Explained-(video-%2B-code)-(beats-95)
class Solution: def minDominoRotations(self, A: List[int], B: List[int]) -> int: if len(A) <= 1: return 0 def helper(target, A, B): count = 0 for indx in range(len(A)): a, b = A[indx], B[indx] if target == a: continue else: if b == target: count += 1 else: count = float("inf") break return count res = min(helper(A[0], A, B), helper(A[0], B, A), helper(B[0], A, B), helper(B[0], B, A)) return res if res != float('inf') else -1
minimum-domino-rotations-for-equal-row
Python Solution Explained (video + code) (beats 95%)
spec_he123
0
60
minimum domino rotations for equal row
1,007
0.524
Medium
16,446
https://leetcode.com/problems/minimum-domino-rotations-for-equal-row/discuss/608430/Simple-Python-Solution
class Solution: def minDominoRotations(self, A: List[int], B: List[int]) -> int: d1=Counter(A) d2=Counter(B) print(d1) print(d2) k1=list(d1.keys()) k2=list(d2.keys()) maxv1=0 count1=0 maxv2=0 count2=0 for i in range(len(k1)): if d1[k1[i]]>count1: maxv1=k1[i] count1=d1[k1[i]] for i in range(len(k2)): if d2[k2[i]]>count2: maxv2=k2[i] count2=d2[k2[i]] rotations=0 if count1>count2: for i in range(len(A)): if A[i]!=maxv1: rotations+=1 A[i]=B[i] if len(set(A))==1: return rotations else: for i in range(len(B)): if B[i]!=maxv2: rotations+=1 B[i]=A[i] if len(set(B))==1: return rotations return -1
minimum-domino-rotations-for-equal-row
Simple Python Solution
Ayu-99
0
86
minimum domino rotations for equal row
1,007
0.524
Medium
16,447
https://leetcode.com/problems/minimum-domino-rotations-for-equal-row/discuss/427884/Python3-set-intersection-1215ms-faster-than-97
class Solution: def minDominoRotations(self, A: List[int], B: List[int]) -> int: available={A[0],B[0]} for i in range(1,len(A)): if len(available)==0: return -1 available=available.intersection({A[i],B[i]}) # find the intersection of the different columns, the intersection can be deemed as values to algin for A or B countedA=collections.Counter(A) countedB=collections.Counter(B) if len(available)==2: # if two values can be aligned on A or B return min(len(A)-max(countedA.values()),len(A)-max(countedB.values())) else: # if one value can be aligned on A or B return min(len(A)-countedA[list(available)[0]],len(A)-countedB[list(available)[0]])
minimum-domino-rotations-for-equal-row
Python3 set intersection 1215ms faster than 97%
wangzi100
0
75
minimum domino rotations for equal row
1,007
0.524
Medium
16,448
https://leetcode.com/problems/minimum-domino-rotations-for-equal-row/discuss/400769/Slower-than-73.24-of-solutions-but-easy-to-read-and-very-ugly-less3
class Solution: def minDominoRotations(self, A: List[int], B: List[int]) -> int: d = {} # populate our occurance dictionary for i in range(len(A)): if A[i] not in d: d[A[i]] = 1 else: d[A[i]] += 1 if B[i] not in d: d[B[i]] = 1 else: d[B[i]] += 1 maxnum = max(d, key=d.get) countA = 0 countB = 0 for i in range(len(A)): if A[i] != maxnum and B[i] == maxnum: countA+=1 if B[i] != maxnum and A[i] == maxnum: countB +=1 if B[i] != maxnum and A[i] != maxnum: return -1 return min(countA,countB)
minimum-domino-rotations-for-equal-row
Slower than 73.24% of solutions, but easy to read and very ugly <3
LeetDoge
0
134
minimum domino rotations for equal row
1,007
0.524
Medium
16,449
https://leetcode.com/problems/minimum-domino-rotations-for-equal-row/discuss/252421/python-beat-100-easy-to-understand
class Solution(object): def minDominoRotations(self, A, B): """ :type A: List[int] :type B: List[int] :rtype: int """ for x in range(1, 7): ca = cb = 0 for i in range(len(A)): if A[i] != x and B[i] != x: break else: for i in range(len(A)): if A[i] != x: ca += 1 if B[i] != x: cb += 1 return min(ca, cb) return -1
minimum-domino-rotations-for-equal-row
python beat 100%, easy to understand
alpc66
0
191
minimum domino rotations for equal row
1,007
0.524
Medium
16,450
https://leetcode.com/problems/construct-binary-search-tree-from-preorder-traversal/discuss/649369/Python.-No-recursion.
class Solution: def bstFromPreorder(self, preorder: List[int]) -> TreeNode: node_stack = [] node = root = TreeNode(preorder[0]) for n in preorder[1:]: if n <= node.val: node.left = TreeNode(n) node_stack.append(node) node = node.left else: while node_stack and n > node_stack[-1].val: node = node_stack.pop() node.right = TreeNode(n) node = node.right return root
construct-binary-search-tree-from-preorder-traversal
Python. No recursion.
techrabbit58
4
464
construct binary search tree from preorder traversal
1,008
0.809
Medium
16,451
https://leetcode.com/problems/construct-binary-search-tree-from-preorder-traversal/discuss/648968/Python-O(-n-)-sol.-by-definition-85%2B-with-Hint
class Solution: def bstFromPreorder(self, preorder: List[int]) -> TreeNode: root_index = 0 def helper( preorder, upperbound): nonlocal root_index if root_index == len(preorder) or preorder[root_index] > upperbound: return None root = TreeNode( preorder[root_index] ) # update root index by adding one root_index += 1 root.left = helper( preorder, root.val ) root.right = helper( preorder, upperbound ) return root return helper( preorder, float('inf') )
construct-binary-search-tree-from-preorder-traversal
Python O( n ) sol. by definition 85%+ [ with Hint ]
brianchiang_tw
2
232
construct binary search tree from preorder traversal
1,008
0.809
Medium
16,452
https://leetcode.com/problems/construct-binary-search-tree-from-preorder-traversal/discuss/1519352/Python-Iterative-Solution!-Easy-to-understand-w-Explanation
class Solution: def bstFromPreorder(self, preorder: List[int]) -> Optional[TreeNode]: root = TreeNode(preorder[0]) # start with the root node of the BST for i in range(1, len(preorder)): # for each successive element: curr = root # 1. start at the root node while True: # 2. traverse to the appropriate parent node if preorder[i] < curr.val: if not curr.left: # appropriate parent node reached curr.left = TreeNode(preorder[i]) break # node added, go to the next element curr = curr.left else: if not curr.right: # appropriate parent node reached curr.right = TreeNode(preorder[i]) break # node added, go to the next element curr = curr.right return root
construct-binary-search-tree-from-preorder-traversal
Python Iterative Solution! Easy-to-understand w Explanation
zayne-siew
1
139
construct binary search tree from preorder traversal
1,008
0.809
Medium
16,453
https://leetcode.com/problems/construct-binary-search-tree-from-preorder-traversal/discuss/1518992/Two-Methods-oror-Space-Optimized-oror-Time-Optimized
class Solution: def bstFromPreorder(self, preorder: List[int]) -> Optional[TreeNode]: inorder = sorted(preorder) def make(inorder): if len(inorder)==0: return val = preorder.pop(0) ind = inorder.index(val) root = TreeNode(val) root.left = make(inorder[:ind]) root.right= make(inorder[ind+1:]) return root return make(inorder)
construct-binary-search-tree-from-preorder-traversal
📌📌 Two-Methods || Space Optimized || Time-Optimized 🐍
abhi9Rai
1
200
construct binary search tree from preorder traversal
1,008
0.809
Medium
16,454
https://leetcode.com/problems/construct-binary-search-tree-from-preorder-traversal/discuss/1518992/Two-Methods-oror-Space-Optimized-oror-Time-Optimized
class Solution: def bstFromPreorder(self, preorder: List[int]) -> Optional[TreeNode]: inorder = sorted(preorder) dic = {val:i for i,val in enumerate(inorder)} def bst(l,r): if l>=r: return val = preorder.pop(0) ind = dic[val] root = TreeNode(val) root.left = bst(l,ind) root.right= bst(ind+1,r) return root return bst(0,len(inorder))
construct-binary-search-tree-from-preorder-traversal
📌📌 Two-Methods || Space Optimized || Time-Optimized 🐍
abhi9Rai
1
200
construct binary search tree from preorder traversal
1,008
0.809
Medium
16,455
https://leetcode.com/problems/construct-binary-search-tree-from-preorder-traversal/discuss/1518992/Two-Methods-oror-Space-Optimized-oror-Time-Optimized
class Solution(object): def bstFromPreorder(self, preorder): def insert(root, val): if root is None: return TreeNode(val) if root.val >= val: root.left = insert(root.left, val) if root.val < val: root.right = insert(root.right, val) return root root = None for item in preorder: root = insert(root, item) return root
construct-binary-search-tree-from-preorder-traversal
📌📌 Two-Methods || Space Optimized || Time-Optimized 🐍
abhi9Rai
1
200
construct binary search tree from preorder traversal
1,008
0.809
Medium
16,456
https://leetcode.com/problems/construct-binary-search-tree-from-preorder-traversal/discuss/2768342/Python-3-3-line-recursive-approach
class Solution: def bstFromPreorder(self, preorder: List[int]) -> Optional[TreeNode]: if not preorder: return None # Where is the "cut" between left and right branch pos = sum([p < preorder[0] for p in preorder]) + 1 return TreeNode(preorder[0], self.bstFromPreorder(preorder[1:pos]), self.bstFromPreorder(preorder[pos:]))
construct-binary-search-tree-from-preorder-traversal
Python 3 - 3 line recursive approach
SirHiss
0
3
construct binary search tree from preorder traversal
1,008
0.809
Medium
16,457
https://leetcode.com/problems/construct-binary-search-tree-from-preorder-traversal/discuss/2732394/HELP-ME-WITH-A-QUERY
class Solution: def bstFromPreorder(self, preorder: List[int]) -> Optional[TreeNode]: def build(preorder, i, bound): if i == len(preorder) or preorder[i] > bound: return None node = TreeNode(preorder[i]) i+=1 node.left = build(preorder, i, node.val) node.right = build(preorder, i, bound) return node return build(preorder, 0, math.inf)
construct-binary-search-tree-from-preorder-traversal
HELP ME WITH A QUERY
hacktheirlives
0
5
construct binary search tree from preorder traversal
1,008
0.809
Medium
16,458
https://leetcode.com/problems/construct-binary-search-tree-from-preorder-traversal/discuss/2732394/HELP-ME-WITH-A-QUERY
class Solution: def bstFromPreorder(self, preorder: List[int]) -> Optional[TreeNode]: self.i = 0 def build(preorder, i, bound): if self.i == len(preorder) or preorder[self.i] > bound: return None node = TreeNode(preorder[self.i]) self.i+=1 node.left = build(preorder, self.i, node.val) node.right = build(preorder, self.i, bound) return node return build(preorder, self.i, math.inf)
construct-binary-search-tree-from-preorder-traversal
HELP ME WITH A QUERY
hacktheirlives
0
5
construct binary search tree from preorder traversal
1,008
0.809
Medium
16,459
https://leetcode.com/problems/construct-binary-search-tree-from-preorder-traversal/discuss/2717171/Python3-One-Line-Recursive
class Solution: def bstFromPreorder(self, preorder: List[int]) -> Optional[TreeNode]: return None if len(preorder) == 0 else TreeNode(preorder[0], self.bstFromPreorder([x for x in preorder[1:] if x < preorder[0]]), self.bstFromPreorder([x for x in preorder[1:] if x > preorder[0]]))
construct-binary-search-tree-from-preorder-traversal
Python3 One Line Recursive
godshiva
0
4
construct binary search tree from preorder traversal
1,008
0.809
Medium
16,460
https://leetcode.com/problems/construct-binary-search-tree-from-preorder-traversal/discuss/2695016/Python-3-8-liner-DFS
class Solution: def bstFromPreorder(self, preorder: List[int]) -> Optional[TreeNode]: def dfs(arr): if len(arr) == 0: return None node = TreeNode(arr.pop(0)) node.left = dfs([val for val in arr if val < node.val]) node.right = dfs([val for val in arr if val > node.val]) return node return dfs(preorder)
construct-binary-search-tree-from-preorder-traversal
Python 3 8-liner, DFS
zakmatt
0
9
construct binary search tree from preorder traversal
1,008
0.809
Medium
16,461
https://leetcode.com/problems/construct-binary-search-tree-from-preorder-traversal/discuss/2452086/Simple-oror-Python3-oror-O(Nlog(H))
class Solution: def bstFromPreorder(self, preorder: List[int]) -> Optional[TreeNode]: if not preorder: return None root = TreeNode(preorder[0]) for i in range(1, len(preorder)): tmp = TreeNode(preorder[i]) s = root ; p = None while s: p = s if tmp.val < s.val: s = s.left else: s = s.right if tmp.val < p.val: p.left = tmp else: p.right = tmp return root
construct-binary-search-tree-from-preorder-traversal
Simple || Python3 || O(Nlog(H))
shreerajbhamare
0
35
construct binary search tree from preorder traversal
1,008
0.809
Medium
16,462
https://leetcode.com/problems/construct-binary-search-tree-from-preorder-traversal/discuss/2242321/Python3-Simple-Recursive-solution
class Solution: def bstFromPreorder(self, preorder: List[int]) -> Optional[TreeNode]: inorder = sorted(preorder) def bst(preorder, inorder): if not preorder or not inorder: return root = TreeNode(preorder[0]) mid = inorder.index(preorder[0]) root.left = bst(preorder[1: mid+1], inorder[:mid]) root.right = bst(preorder[mid+1:], inorder[mid+1:]) return root return bst(preorder, inorder)
construct-binary-search-tree-from-preorder-traversal
[Python3] Simple Recursive solution
Gp05
0
23
construct binary search tree from preorder traversal
1,008
0.809
Medium
16,463
https://leetcode.com/problems/construct-binary-search-tree-from-preorder-traversal/discuss/2049079/Python-using-bound.-O(N)
class Solution: def bstFromPreorder(self, preorder: List[int]) -> Optional[TreeNode]: def construct(bound): if self.i == len(preorder) or preorder[self.i] > bound: return None node = TreeNode(preorder[self.i]) self.i += 1 node.left = construct(node.val) node.right = construct(bound) return node self.i = 0 return construct(math.inf)
construct-binary-search-tree-from-preorder-traversal
Python, using bound. O(N)
blue_sky5
0
36
construct binary search tree from preorder traversal
1,008
0.809
Medium
16,464
https://leetcode.com/problems/construct-binary-search-tree-from-preorder-traversal/discuss/1856197/Python3-recursive-solution
class Solution(object): def bstFromPreorder(self, preorder): """ :type preorder: List[int] :rtype: TreeNode """ ''' Input: preorder = [8,5,1,7,10,12] Output: [8,5,10,1,7,null,12] ''' return self.helper(preorder, 0,len(preorder)-1) def helper(self,preorder,left,right): if right<left: return None root=TreeNode(preorder[left]) middle=left+1 while middle<=right and preorder[middle]<root.val: middle+=1 root.left=self.helper(preorder,left+1,middle-1) root.right=self.helper(preorder, middle, right) return root
construct-binary-search-tree-from-preorder-traversal
Python3 recursive solution
muzhang90
0
39
construct binary search tree from preorder traversal
1,008
0.809
Medium
16,465
https://leetcode.com/problems/construct-binary-search-tree-from-preorder-traversal/discuss/1647999/Simplest-0ms-faster-than-100-C%2B%2B-solution-or-O(N)-time-or-Additional-Python-solution
class Solution: def bstFromPreorder(self, vec: List[int]) -> Optional[TreeNode]: if len(vec) == 0: return None idx = 1 for i in range(1, len(vec)): if vec[i] > vec[0]: break idx+=1; root = TreeNode(vec[0]) root.left = self.bstFromPreorder(vec[1:idx]) root.right = self.bstFromPreorder(vec[idx:]) return root
construct-binary-search-tree-from-preorder-traversal
Simplest 0ms faster than 100% C++ solution | O(N) time | Additional Python solution
itzritz
0
91
construct binary search tree from preorder traversal
1,008
0.809
Medium
16,466
https://leetcode.com/problems/construct-binary-search-tree-from-preorder-traversal/discuss/1519062/Python3-solution-using-a-stack
class Solution: def bstFromPreorder(self, preorder: List[int]) -> Optional[TreeNode]: root = TreeNode(preorder[0]) i = 1 st = [root] while i<len(preorder): value = preorder[i] if value<st[-1].val: st[-1].left=TreeNode(value) st.append(st[-1].left) else: last = st[-1] while st and st[-1].val < value: last = st.pop() last.right = TreeNode(value) st.append(last.right) i+=1 return root
construct-binary-search-tree-from-preorder-traversal
Python3 solution using a stack
ashwinbhat
0
29
construct binary search tree from preorder traversal
1,008
0.809
Medium
16,467
https://leetcode.com/problems/construct-binary-search-tree-from-preorder-traversal/discuss/1518694/Python3-solution
class Solution: def bstFromPreorder(self, preorder: List[int]) -> Optional[TreeNode]: if not preorder: return None node = TreeNode(preorder[0]) l, r = [], [] for i in range(1, len(preorder)): l.append(preorder[i]) if preorder[i] < preorder[0] else r.append(preorder[i]) node.left = self.bstFromPreorder(l) node.right = self.bstFromPreorder(r) return node
construct-binary-search-tree-from-preorder-traversal
Python3 solution
dalechoi
0
52
construct binary search tree from preorder traversal
1,008
0.809
Medium
16,468
https://leetcode.com/problems/construct-binary-search-tree-from-preorder-traversal/discuss/1182238/Using-Inorder-Preorder-Traversal-greater-90-Faster
class Solution: def createBST(self,preorder,inorder): if preorder: val = preorder[0] idx = inorder.index(val) root = TreeNode(val=val) root.left = self.createBST(preorder[1:idx+1],inorder[:idx]) root.right = self.createBST(preorder[idx+1:],inorder[idx+1:]) return root def bstFromPreorder(self, preorder: List[int]) -> TreeNode: inorder = sorted(preorder) root = self.createBST(preorder,inorder) return root
construct-binary-search-tree-from-preorder-traversal
Using Inorder-Preorder Traversal => 90% Faster
tgoel219
0
63
construct binary search tree from preorder traversal
1,008
0.809
Medium
16,469
https://leetcode.com/problems/construct-binary-search-tree-from-preorder-traversal/discuss/1073426/Elegant-Python-Recursion-faster-than-97.87
class Solution: def bstFromPreorder(self, preorder: List[int]) -> TreeNode: if preorder: root = TreeNode(preorder.pop(0)) if preorder: index = 0 while index < len(preorder) and preorder[index] <= root.val: index += 1 root.left = self.bstFromPreorder(preorder[:index]) root.right = self.bstFromPreorder(preorder[index:]) return root
construct-binary-search-tree-from-preorder-traversal
Elegant Python Recursion, faster than 97.87%
111989
0
158
construct binary search tree from preorder traversal
1,008
0.809
Medium
16,470
https://leetcode.com/problems/construct-binary-search-tree-from-preorder-traversal/discuss/787038/Python3-DFS-Faster-than-95
class Solution: def bstFromPreorder(self, preorder: List[int]) -> TreeNode: if not preorder: return None def pre(l,r): if l>r: return None root = TreeNode(preorder[l]) temp = l while temp<=r: if preorder[temp] > preorder[l]: break temp+=1 root.left = pre(l+1,temp-1) root.right = pre(temp,r) return root return pre(0, len(preorder)-1) ```
construct-binary-search-tree-from-preorder-traversal
Python3 DFS Faster than 95%
amrmahmoud96
0
104
construct binary search tree from preorder traversal
1,008
0.809
Medium
16,471
https://leetcode.com/problems/construct-binary-search-tree-from-preorder-traversal/discuss/650657/Python3-iterative-approach
class Solution: def bstFromPreorder(self, preorder: List[int]) -> TreeNode: root = None stack = [] for x in preorder: if not root: root = node = TreeNode(x) elif x < node.val: stack.append(node) node.left = node = TreeNode(x) else: while stack and stack[-1].val < x: node = stack.pop() node.right = node = TreeNode(x) return root
construct-binary-search-tree-from-preorder-traversal
[Python3] iterative approach
ye15
0
64
construct binary search tree from preorder traversal
1,008
0.809
Medium
16,472
https://leetcode.com/problems/construct-binary-search-tree-from-preorder-traversal/discuss/592190/Recursive-Solution-Python3
class Solution: def addChildNodes(self, value, node): if value < node.val: if node.left: self.addChildNodes(value, node.left) else: node.left = TreeNode(value) else: if node.right: self.addChildNodes(value, node.right) else: node.right = TreeNode(value) def bstFromPreorder(self, preorder: List[int]) -> TreeNode: root = TreeNode(preorder[0]) for i in range(1,len(preorder)): self.addChildNodes(preorder[i], root) return root
construct-binary-search-tree-from-preorder-traversal
Recursive Solution Python3
kpnigalye
0
75
construct binary search tree from preorder traversal
1,008
0.809
Medium
16,473
https://leetcode.com/problems/construct-binary-search-tree-from-preorder-traversal/discuss/465717/Python3-simple-solution-using-a-while()-loop-faster-than-90.31
class Solution: def bstFromPreorder(self, preorder: List[int]) -> TreeNode: if not preorder: return root = None for value in preorder: node = TreeNode(value) if not root: root = node continue start = root while True: if value < start.val: if not start.left: start.left = node break start = start.left if start.val < value: if not start.right: start.right = node break start = start.right return root
construct-binary-search-tree-from-preorder-traversal
Python3 simple solution using a while() loop, faster than 90.31%
jb07
0
97
construct binary search tree from preorder traversal
1,008
0.809
Medium
16,474
https://leetcode.com/problems/construct-binary-search-tree-from-preorder-traversal/discuss/252264/Python3-Recursive-Solution
class Solution: def bstFromPreorder(self, preorder: List[int]) -> TreeNode: if not preorder: return None root = None for i in range(len(preorder)): node = preorder[i] root = self.handle(root, node) return root def handle(self, root, x): if not root: return TreeNode(x) if x < root.val: root.left = self.handle(root.left, x) else: root.right = self.handle(root.right, x) return root
construct-binary-search-tree-from-preorder-traversal
Python3 - Recursive Solution
qqzzqq
0
101
construct binary search tree from preorder traversal
1,008
0.809
Medium
16,475
https://leetcode.com/problems/complement-of-base-10-integer/discuss/1666811/Python-Simple-Solution-with-Detail-Explanation-%3A-O(log-n)
class Solution: def bitwiseComplement(self, n: int) -> int: if n == 0: return 1 else: result = 0 factor = 1 while(n > 0): result += factor * (1 if n%2 == 0 else 0) factor *= 2 n //= 2 return result
complement-of-base-10-integer
Python Simple Solution with Detail Explanation : O(log n)
yashitanamdeo
2
314
complement of base 10 integer
1,009
0.619
Easy
16,476
https://leetcode.com/problems/complement-of-base-10-integer/discuss/1665812/Python3-Solution-January-Day-4-challenge
class Solution: def bitwiseComplement(self, N: int) -> int: sum_ = 1 while N > sum_: sum_ = sum_ * 2 + 1 return sum_ - N
complement-of-base-10-integer
Python3 Solution January Day 4 challenge
nomanaasif9
2
152
complement of base 10 integer
1,009
0.619
Easy
16,477
https://leetcode.com/problems/complement-of-base-10-integer/discuss/1896224/Python-easy-solution-using-built-in-function
class Solution: def bitwiseComplement(self, n: int) -> int: bin_n = bin(n)[2:] comp = "0b" for i in bin_n: if i == "0": comp += "1" else: comp += "0" return int(comp, 2)
complement-of-base-10-integer
Python easy solution using built-in function
alishak1999
1
55
complement of base 10 integer
1,009
0.619
Easy
16,478
https://leetcode.com/problems/complement-of-base-10-integer/discuss/1667132/Python-Straightforward-one-line-solution-naive-approach
class Solution: def bitwiseComplement(self, n: int) -> int: return int(bin(n)[2:].replace('1', 'z').replace('0', '1').replace('z', '0'), 2)
complement-of-base-10-integer
[Python] Straightforward one-line solution, naive approach
louter
1
51
complement of base 10 integer
1,009
0.619
Easy
16,479
https://leetcode.com/problems/complement-of-base-10-integer/discuss/1666960/Clear-4-lines-solution
class Solution: def bitwiseComplement(self, n: int) -> int: binary=bin(n).replace("0b","") ones="1"*len(binary) binary,ones=int(binary,2),int(ones,2) return binary^ones
complement-of-base-10-integer
Clear 4 lines solution
amannarayansingh10
1
85
complement of base 10 integer
1,009
0.619
Easy
16,480
https://leetcode.com/problems/complement-of-base-10-integer/discuss/1392114/python3%3A-99-faster
class Solution: def bitwiseComplement(self, n: int) -> int: bin_num=list(bin(n)) for i in range(2,len(bin_num)): if bin_num[i]=='1': bin_num[i]='0' else: bin_num[i]='1' return int(''.join(bin_num),2)
complement-of-base-10-integer
python3: 99% faster
p_a
1
120
complement of base 10 integer
1,009
0.619
Easy
16,481
https://leetcode.com/problems/complement-of-base-10-integer/discuss/1306289/Easy-Python-Solution(99.66)
class Solution: def bitwiseComplement(self, n: int) -> int: x=bin(n)[2:] c=0 for i in range(len(x)): if(x[i]=='0'): c+=2**(len(x)-i-1) return c
complement-of-base-10-integer
Easy Python Solution(99.66%)
Sneh17029
1
276
complement of base 10 integer
1,009
0.619
Easy
16,482
https://leetcode.com/problems/complement-of-base-10-integer/discuss/405275/Python-70-faster-solution
class Solution: def bitwiseComplement(self, N: int) -> int: b = bin(N)[2:] b = b.replace('0', '2') b = b.replace('1', '0') b = b.replace('2','1') return int(b,2)
complement-of-base-10-integer
Python 70% faster solution
saffi
1
212
complement of base 10 integer
1,009
0.619
Easy
16,483
https://leetcode.com/problems/complement-of-base-10-integer/discuss/262669/Easy-Complement-of-Base-10-Integer
class Solution: def bitwiseComplement(self, N: int) -> int: lis=[] s='' for i in bin(N)[2:]: if int(i)==0: lis.append(str(int(i)+1)) elif int(i)==1: lis.append(str(int(i)-1)) else: pass for i in lis: s+=i return int(s,2)
complement-of-base-10-integer
Easy Complement of Base 10 Integer
lalithbharadwaj
1
315
complement of base 10 integer
1,009
0.619
Easy
16,484
https://leetcode.com/problems/complement-of-base-10-integer/discuss/256715/Python-Solution
class Solution: def bitwiseComplement(self, N: int) -> int: temp = {'1':'0', '0':'1'} cache = list("{0:b}".format(N)) return int(''.join([temp[x] for x in cache]), 2)
complement-of-base-10-integer
Python Solution
parthjit
1
108
complement of base 10 integer
1,009
0.619
Easy
16,485
https://leetcode.com/problems/complement-of-base-10-integer/discuss/2654354/Complement-of-Base-10-Integer-Python-solution
class Solution: def bitwiseComplement(self, n: int) -> int: mask = 0 num = n if n == 0: return 1 while num != 0: # Shit mask to left and or with 1 till num is not equal to 0 mask = (mask << 1)|1 # Shift num to right till u get all 0 num = num >> 1 ans = (~n) &amp; mask return ans
complement-of-base-10-integer
Complement of Base 10 Integer// Python solution
24Neha
0
5
complement of base 10 integer
1,009
0.619
Easy
16,486
https://leetcode.com/problems/complement-of-base-10-integer/discuss/2045789/Python-simple-oneliner
class Solution: def bitwiseComplement(self, n: int) -> int: return int(bin(n)[2:].replace('1','2').replace('0','1').replace('2','0'),2)
complement-of-base-10-integer
Python simple oneliner
StikS32
0
54
complement of base 10 integer
1,009
0.619
Easy
16,487
https://leetcode.com/problems/complement-of-base-10-integer/discuss/1902526/Python-Bitwise-%2B-One-Liner!
class Solution: def bitwiseComplement(self, num): num_copy, i = num, 0 while num_copy: i += 1 num_copy >>= 1 return num ^ 2**i-1
complement-of-base-10-integer
Python - Bitwise + One Liner!
domthedeveloper
0
64
complement of base 10 integer
1,009
0.619
Easy
16,488
https://leetcode.com/problems/complement-of-base-10-integer/discuss/1902526/Python-Bitwise-%2B-One-Liner!
class Solution: def bitwiseComplement(self, n): return int(bin(n)[2:].translate(str.maketrans("01","10")), 2)
complement-of-base-10-integer
Python - Bitwise + One Liner!
domthedeveloper
0
64
complement of base 10 integer
1,009
0.619
Easy
16,489
https://leetcode.com/problems/complement-of-base-10-integer/discuss/1858194/1-Line-Python-Solution-oror-50-Faster-oror-Memory-less-than-98
class Solution: def bitwiseComplement(self, n: int) -> int: return (1<<n.bit_length()) + ~n if n else 1
complement-of-base-10-integer
1-Line Python Solution || 50% Faster || Memory less than 98%
Taha-C
0
44
complement of base 10 integer
1,009
0.619
Easy
16,490
https://leetcode.com/problems/complement-of-base-10-integer/discuss/1858194/1-Line-Python-Solution-oror-50-Faster-oror-Memory-less-than-98
class Solution: def bitwiseComplement(self, n: int) -> int: return ~n^(-1<<n.bit_length()) if n else 1
complement-of-base-10-integer
1-Line Python Solution || 50% Faster || Memory less than 98%
Taha-C
0
44
complement of base 10 integer
1,009
0.619
Easy
16,491
https://leetcode.com/problems/complement-of-base-10-integer/discuss/1858194/1-Line-Python-Solution-oror-50-Faster-oror-Memory-less-than-98
class Solution: def bitwiseComplement(self, n: int) -> int: return int(bin(n)[2:].replace('1','x').replace('0','1').replace('x','0'),2)
complement-of-base-10-integer
1-Line Python Solution || 50% Faster || Memory less than 98%
Taha-C
0
44
complement of base 10 integer
1,009
0.619
Easy
16,492
https://leetcode.com/problems/complement-of-base-10-integer/discuss/1720270/Simple-solution-using-(-Python3-and-JavaScript-)
class Solution: def bitwiseComplement(self, n: int) -> int: binary = bin(n).replace("0b", "") num = "" for item in binary: if item == "0": num += "1" else: num += "0" num = int(num, 2) return num
complement-of-base-10-integer
Simple solution using - ( Python3 & JavaScript )
shakilbabu
0
44
complement of base 10 integer
1,009
0.619
Easy
16,493
https://leetcode.com/problems/complement-of-base-10-integer/discuss/1670159/Simple-python-code%3A-using-bin()-and-int()-functions
class Solution: def bitwiseComplement(self, n: int) -> int: binary_num = bin(n).replace("0b","") s = '' if(n==0): return 1 for x in range(len(binary_num)): if(int(binary_num[x]) % 10 == 0): s += '1' else: s += '0' return int(s,2)
complement-of-base-10-integer
Simple python code: using bin() and int() functions
KratikaRathore
0
24
complement of base 10 integer
1,009
0.619
Easy
16,494
https://leetcode.com/problems/complement-of-base-10-integer/discuss/1667255/Python3-Solution%3A-Simulate-the-Process-of-Converting-Decimal-to-Binary
class Solution: def bitwiseComplement(self, n: int) -> int: if n == 0: return 1 res = 0 base = 1 while n > 0: res += base * (1 - n % 2) n //= 2 base <<= 1 return res
complement-of-base-10-integer
Python3 Solution: Simulate the Process of Converting Decimal to Binary
RyanLeftYuan
0
14
complement of base 10 integer
1,009
0.619
Easy
16,495
https://leetcode.com/problems/complement-of-base-10-integer/discuss/1666861/Python3-onliner-XOR-with-mask
class Solution: def bitwiseComplement(self, n: int) -> int: # calculate mask and perform XOR return n^int('1'*(len(bin(n))-2),2)
complement-of-base-10-integer
[Python3] onliner XOR with mask
Rainyforest
0
17
complement of base 10 integer
1,009
0.619
Easy
16,496
https://leetcode.com/problems/complement-of-base-10-integer/discuss/1666861/Python3-onliner-XOR-with-mask
class Solution: def bitwiseComplement(self, n): return ((2 << int(math.log(max(n, 1), 2))) - 1) - n
complement-of-base-10-integer
[Python3] onliner XOR with mask
Rainyforest
0
17
complement of base 10 integer
1,009
0.619
Easy
16,497
https://leetcode.com/problems/complement-of-base-10-integer/discuss/1666743/Python3-Solution-with-using-mask
class Solution: def bitwiseComplement(self, n: int) -> int: if n == 0: return 1 cur_num, cur_bit = n, 1 while cur_num: n ^= cur_bit cur_bit <<= 1 cur_num >>= 1 return n
complement-of-base-10-integer
[Python3] Solution with using mask
maosipov11
0
18
complement of base 10 integer
1,009
0.619
Easy
16,498
https://leetcode.com/problems/complement-of-base-10-integer/discuss/1666545/Python3-solution
class Solution: def bitwiseComplement(self, n: int) -> int: # convert int to a binary textual representation without the 0b-prefix get_binary = lambda n: format(n, 'b') input_b = get_binary(n) #e.g.,'101' # get output in binary representation output_b = "" for i in input_b: if i == "1": output_b += "0" else: output_b += "1" # convert output from binary to int get_int = lambda n: int(n, 2) #binary base 2 result = get_int(output_b) return result
complement-of-base-10-integer
Python3 solution
Janetcxy
0
18
complement of base 10 integer
1,009
0.619
Easy
16,499