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/special-array-with-x-elements-greater-than-or-equal-x/discuss/2605119/Python3-Counting-sort-O(n)-time-and-space
class Solution: def specialArray(self, nums: List[int]) -> int: a = [0] * 1001 for n in nums: a[n] += 1 i = 0 n = len(nums) for val, fre in enumerate(a): if not i < len(nums): break # print(f"val -> fre:{val} -> {fre}") # print(f"how many has passed: {i}") # print(f"Number on the right of {val}, inclusive: {n - i}") # print() if val == n - i: return val if fre: i += fre return -1
special-array-with-x-elements-greater-than-or-equal-x
[Python3] Counting sort, O(n) time & space
DG_stamper
0
19
special array with x elements greater than or equal x
1,608
0.601
Easy
23,500
https://leetcode.com/problems/special-array-with-x-elements-greater-than-or-equal-x/discuss/2583341/Python-Linear-Complexity-PrefixSum-without-Sort
class Solution: def specialArray(self, nums: List[int]) -> int: # make an array to count numbers counts = [0]*10001 # count the numbers for num in nums: counts[num] += 1 # make a prefix sum (suffix sum since reverse) for index in range(len(counts)-2, -1, -1): # compute the current counter counts[index] = counts[index+1] + counts[index] # check whether we found the number if counts[index] == index: return index return -1
special-array-with-x-elements-greater-than-or-equal-x
[Python] - Linear Complexity PrefixSum without Sort
Lucew
0
25
special array with x elements greater than or equal x
1,608
0.601
Easy
23,501
https://leetcode.com/problems/special-array-with-x-elements-greater-than-or-equal-x/discuss/2531272/Python3-or-Solved-Using-Binary-Search-or-Look-for-Index-Pos-Where-All-Elements-From-There-Onwards-greater-X
class Solution: #Let n = len(nums)! #Time-Complexity: O(n + (n * log(n))) -> O(nlogn) #Space-Complexity: O(1) def specialArray(self, nums: List[int]) -> int: #Approach: Perform binary search over the array nums to find #if even a single value X candidate exists s.t. there are exactly X numbers #in nums with val(s) greater than or equal to X! #helper binary search! def binary_search(e, a): L, R = 0, (len(a) - 1) while L <= R: mid = (L + R) // 2 middle = a[mid] if(middle > e): R = mid - 1 continue elif(middle < e): L = mid + 1 continue else: #we still search left since there may be duplicates even if element e #exists as the current middle element! R = mid - 1 continue return L #we need to sort nums array beforehand! nums.sort() #smalest X could be is 1 and largest it could be is len(nums)! for i in range(1, len(nums) + 1): index = binary_search(i, nums) number_greater = (len(nums) - index) if(number_greater == i): return i return -1
special-array-with-x-elements-greater-than-or-equal-x
Python3 | Solved Using Binary Search | Look for Index Pos Where All Elements From There Onwards >= X
JOON1234
0
28
special array with x elements greater than or equal x
1,608
0.601
Easy
23,502
https://leetcode.com/problems/special-array-with-x-elements-greater-than-or-equal-x/discuss/2440905/C%2B%2B-and-Python-O(N*log(N))-Solution
class Solution: def specialArray(self, nums: List[int]) -> int: nums.sort() n = len(nums) if n<=nums[0]: return n #binary search start,end = 0,n while(start<=end): mid = (start+end)//2 #index of middle element count = 0 for i in range(0,n): if nums[i]>=mid: count = n-i #count+=1 could use this but will take more iterations then. break if count==mid: return count elif count<mid: end = mid-1 else: start=mid+1 return -1
special-array-with-x-elements-greater-than-or-equal-x
C++ & Python O(N*log(N)) Solution
arpit3043
0
73
special array with x elements greater than or equal x
1,608
0.601
Easy
23,503
https://leetcode.com/problems/special-array-with-x-elements-greater-than-or-equal-x/discuss/2375715/Python-Short-and-Faster-Solution-Sorting
class Solution: def specialArray(self, nums: List[int]) -> int: nums.sort() n = len(nums) if n <= nums[0]: return len(nums) for i in range(1, n): if nums[i-1] < n-i <= nums[i]: return n-i return -1
special-array-with-x-elements-greater-than-or-equal-x
[Python] Short and Faster Solution - Sorting
Buntynara
0
18
special array with x elements greater than or equal x
1,608
0.601
Easy
23,504
https://leetcode.com/problems/special-array-with-x-elements-greater-than-or-equal-x/discuss/2332050/python-tricky-solution-without-binary-search
class Solution: def specialArray(self, nums: List[int]) -> int: # sort the numbers in ascending order nums.sort() # find the length totallen = len(nums) # total number of elemnts greater than a number can be calculated using indexes startindex = 0 # traverse over possible numbers for i in range(0, totallen + 1): # total number of greater than at i is totallen - startindex # the number of elements greater than goes on descresing # if i is greater than this it means next part of array can never give # solution .. Example: if i= 4 and we are left with 2 elements # no way u can have i = 5 giving 5 elements greater than 5 if totallen - startindex < i: break # condition to check index overflow if startindex < totallen: # count ones less than i while(nums[startindex] < i ): startindex +=1 if startindex >= totallen: break # check the matching condition in question if i == totallen - startindex: return i return -1
special-array-with-x-elements-greater-than-or-equal-x
python - tricky solution without binary search
krishnamsgn
0
13
special array with x elements greater than or equal x
1,608
0.601
Easy
23,505
https://leetcode.com/problems/special-array-with-x-elements-greater-than-or-equal-x/discuss/2123360/Simple-Python-Solution-Explained
class Solution(object): def specialArray(self, nums): nums.sort() def countHigher(x): for i in range(len(nums)): if nums[i]>=x: return len(nums[i:]) return 0 for x in range(nums[-1]+1): if countHigher(x) == x: return x return -1
special-array-with-x-elements-greater-than-or-equal-x
Simple Python Solution Explained
NathanPaceydev
0
54
special array with x elements greater than or equal x
1,608
0.601
Easy
23,506
https://leetcode.com/problems/special-array-with-x-elements-greater-than-or-equal-x/discuss/2106132/Python-simple-solution
class Solution: def specialArray(self, nums: List[int]) -> int: for i in range(1, max(nums)+1): tmp = 0 for j in nums: if j >= i: tmp += 1 if tmp == i: return i return -1
special-array-with-x-elements-greater-than-or-equal-x
Python simple solution
StikS32
0
57
special array with x elements greater than or equal x
1,608
0.601
Easy
23,507
https://leetcode.com/problems/special-array-with-x-elements-greater-than-or-equal-x/discuss/2011937/Binary-search-not-needed
class Solution: def specialArray(self, nums: List[int]) -> int: n = len(nums) nums.sort() for i in range(1, n + 1): target = i if nums[n - i] >= target: if (n - i > 0 and nums[n - 1 - i] < target) or n - i == 0: return target return -1
special-array-with-x-elements-greater-than-or-equal-x
Binary search not needed
lyhar54
0
43
special array with x elements greater than or equal x
1,608
0.601
Easy
23,508
https://leetcode.com/problems/special-array-with-x-elements-greater-than-or-equal-x/discuss/1898658/Python-Binary-Search-approach
class Solution: def specialArray(self, nums: List[int]) -> int: nums.sort() count=[] ans=-1 for i in range(1,len(nums)+1): l=0 h=len(nums)-1 while(l<=h): mid=l+(h-l)//2 if nums[mid]>= i: h=mid-1 else: l=mid+1 count.append([i,len(nums)-1-h]) #print(count) for j in count: if j[0] == j[1]: ans=j[0] return ans
special-array-with-x-elements-greater-than-or-equal-x
Python Binary Search approach
tripathi_shreesh
0
59
special array with x elements greater than or equal x
1,608
0.601
Easy
23,509
https://leetcode.com/problems/special-array-with-x-elements-greater-than-or-equal-x/discuss/1827967/2-Python-Solutions-oror-75-Faster-oror-Memory-less-than-80
class Solution: def specialArray(self, nums: List[int]) -> int: x=0 while x<=max(nums): cnt=0 for num in nums: if num>=x: cnt+=1 if cnt==x: return x x+=1 return -1
special-array-with-x-elements-greater-than-or-equal-x
2 Python Solutions || 75% Faster || Memory less than 80%
Taha-C
0
80
special array with x elements greater than or equal x
1,608
0.601
Easy
23,510
https://leetcode.com/problems/special-array-with-x-elements-greater-than-or-equal-x/discuss/1827967/2-Python-Solutions-oror-75-Faster-oror-Memory-less-than-80
class Solution: def specialArray(self, nums: List[int]) -> int: counter=Counter(nums) ; res=0 for i in range(1001): if i==len(nums)-res: return i res+=counter[i] return -1
special-array-with-x-elements-greater-than-or-equal-x
2 Python Solutions || 75% Faster || Memory less than 80%
Taha-C
0
80
special array with x elements greater than or equal x
1,608
0.601
Easy
23,511
https://leetcode.com/problems/special-array-with-x-elements-greater-than-or-equal-x/discuss/1759373/Python-dollarolution
class Solution: def specialArray(self, nums: List[int]) -> int: for i in range(len(nums)+1): count = 0 for j in range(len(nums)): if nums[j] > i-1: count += 1 if count == i: return i return -1
special-array-with-x-elements-greater-than-or-equal-x
Python $olution
AakRay
0
97
special array with x elements greater than or equal x
1,608
0.601
Easy
23,512
https://leetcode.com/problems/special-array-with-x-elements-greater-than-or-equal-x/discuss/1643220/Python-or-Binary-Search-or-Fast-and-Easy
class Solution(object): def specialArray(self, nums): """ :type nums: List[int] :rtype: int """ nums.sort() for i in range(len(nums)+1): left, right = 0, len(nums)-1 while left <= right: mid = (left+right)//2 if nums[mid] < i: left = mid + 1 else: right = mid - 1 if len(nums)-left==i: return len(nums)-left return -1
special-array-with-x-elements-greater-than-or-equal-x
Python | Binary Search | Fast and Easy
Xueting_Cassie
0
154
special array with x elements greater than or equal x
1,608
0.601
Easy
23,513
https://leetcode.com/problems/special-array-with-x-elements-greater-than-or-equal-x/discuss/1603788/Python3-simple-solution-with-sort
class Solution: def specialArray(self, nums: List[int]) -> int: nums.sort(reverse=True) if nums[0] < 0: return 0 if len(nums) <= nums[-1]: return len(nums) for i in range(len(nums)): if nums[i] < i: if nums[i-1] > i-1: return i return -1
special-array-with-x-elements-greater-than-or-equal-x
[Python3] simple solution with sort
Rainyforest
0
62
special array with x elements greater than or equal x
1,608
0.601
Easy
23,514
https://leetcode.com/problems/special-array-with-x-elements-greater-than-or-equal-x/discuss/1603788/Python3-simple-solution-with-sort
class Solution: def specialArray(self, nums: List[int]) -> int: nums.sort(reverse=True) l, r = 0, len(nums) while l < r: m = l + (r - l) // 2 if m < nums[m]: l = m + 1 else: r = m return -1 if l < len(nums) and l == nums[l] else l
special-array-with-x-elements-greater-than-or-equal-x
[Python3] simple solution with sort
Rainyforest
0
62
special array with x elements greater than or equal x
1,608
0.601
Easy
23,515
https://leetcode.com/problems/special-array-with-x-elements-greater-than-or-equal-x/discuss/1072648/Python-3-faster-than-97.54-of-Python3
class Solution: def specialArray(self, nums: list) -> int: number = 0 for i in sorted(nums,reverse=True): number+=1 if i < number or i<=0: number-=1 break return number if number == sum(map(lambda x:x>=number, nums)) else -1
special-array-with-x-elements-greater-than-or-equal-x
[Python 3] faster than 97.54% of Python3
WiseLin
0
233
special array with x elements greater than or equal x
1,608
0.601
Easy
23,516
https://leetcode.com/problems/special-array-with-x-elements-greater-than-or-equal-x/discuss/877837/Python3-via-binary-search
class Solution: def specialArray(self, nums: List[int]) -> int: nums.sort() if len(nums) <= nums[0]: return len(nums) # edge case for i in range(1, len(nums)): if nums[i-1] < len(nums)-i <= nums[i]: return len(nums)-i return -1
special-array-with-x-elements-greater-than-or-equal-x
[Python3] via binary search
ye15
0
84
special array with x elements greater than or equal x
1,608
0.601
Easy
23,517
https://leetcode.com/problems/special-array-with-x-elements-greater-than-or-equal-x/discuss/877837/Python3-via-binary-search
class Solution: def specialArray(self, nums: List[int]) -> int: nums.sort() fn = lambda x: x - (len(nums) - bisect_left(nums, x)) lo, hi = 0, nums[-1] while lo <= hi: mid = lo + hi >> 1 if fn(mid) < 0: lo = mid + 1 elif fn(mid) == 0: return mid else: hi = mid - 1 return -1
special-array-with-x-elements-greater-than-or-equal-x
[Python3] via binary search
ye15
0
84
special array with x elements greater than or equal x
1,608
0.601
Easy
23,518
https://leetcode.com/problems/even-odd-tree/discuss/877858/Python3-bfs-by-level
class Solution: def isEvenOddTree(self, root: TreeNode) -> bool: even = 1 # even level queue = deque([root]) while queue: newq = [] prev = -inf if even else inf for _ in range(len(queue)): node = queue.popleft() if even and (node.val&amp;1 == 0 or prev >= node.val) or not even and (node.val&amp;1 or prev <= node.val): return False prev = node.val if node.left: queue.append(node.left) if node.right: queue.append(node.right) even ^= 1 return True
even-odd-tree
[Python3] bfs by level
ye15
1
103
even odd tree
1,609
0.538
Medium
23,519
https://leetcode.com/problems/even-odd-tree/discuss/2758633/Level-Order-Solution-in-Python-and-Golang
class Solution: def isEvenOddTree(self, root: Optional[TreeNode]) -> bool: if root is None: return False level_order = self.level_order(root) # check level 0 if level_order[0][0] % 2 == 0: return False # check level 1 ~ end for i, level in enumerate(level_order[1:], 2): if i % 2 == 0: # even and decreasing order previous_element = level[0] if previous_element % 2 != 0: return False for element in level[1:]: if element % 2 != 0 or previous_element < element: return False previous_element = element else: # odd and increasing order previous_element = level[0] if previous_element % 2 == 0: return False for element in level[1:]: if element % 2 == 0 or element < previous_element: return False previous_element = level return True def level_order(self, root: Optional[TreeNode]) -> List[List[int]]: queue = [root] level_order = [] while queue: size = len(queue) level = [] for _ in range(size): node = queue.pop(0) if node.left: queue.append(node.left) if node.right: queue.append(node.right) level.append(node.val) level_order.append(level) return level_order
even-odd-tree
Level Order Solution in Python and Golang
namashin
0
3
even odd tree
1,609
0.538
Medium
23,520
https://leetcode.com/problems/even-odd-tree/discuss/2506861/Python-96-faster
class Solution: def isEvenOddTree(self, root: Optional[TreeNode]) -> bool: queue = deque() queue.append(root) even_idx = True while len(queue): for i in range(len(queue)): node = queue.popleft() if node == '$': continue if even_idx and node.val%2 == 0: return False elif not even_idx and node.val%2!= 0: return False if even_idx: # strictly decreasing order if queue and queue[0]!='$' and node.val >= queue[0].val: return False elif not even_idx: if queue and queue[0]!='$' and node.val <= queue[0].val: print('called') return False if node.left: queue.append(node.left) if node.right: queue.append(node.right) if queue: queue.append('$') even_idx = not even_idx return True
even-odd-tree
Python 96% faster
Abhi_009
0
23
even odd tree
1,609
0.538
Medium
23,521
https://leetcode.com/problems/even-odd-tree/discuss/2051207/Python-solution-O(n)-space-and-time-Straight
class Solution: def isEvenOddTree(self, root: Optional[TreeNode]) -> bool: q = deque() q.append(root) levelCounter = 0 while q: odd = False even = False if levelCounter % 2 != 0: odd = True prevVal = float("inf") else: even = True prevVal = float("-inf") for i in range(len(q)): node = q.popleft() if node: if even and (node.val % 2 == 0 or node.val <= prevVal): return False elif odd and (node.val % 2 != 0 or node.val >= prevVal): return False prevVal = node.val q.append(node.left) q.append(node.right) levelCounter += 1 return True
even-odd-tree
Python solution O(n) space and time - Straight
mynavy
0
29
even odd tree
1,609
0.538
Medium
23,522
https://leetcode.com/problems/even-odd-tree/discuss/1467918/python-bfs
class Solution: def isEvenOddTree(self, root: Optional[TreeNode]) -> bool: from collections import deque queue = deque([(root, 0)]) depth = defaultdict(list) depth[0] = [root.val] if root.val %2 == 0: return False while queue: node, d = queue.popleft() if len(depth[d]) == 0: if d %2 == 0 and node.val %2 == 0: return False elif d %2 ==1 and node.val %2 ==1: return False else: depth[d].append(node.val) else: if d>0 and d %2 == 0: if node.val <= depth[d][-1] or node.val %2 ==0: return False if d>0 and d % 2 ==1: if node.val >= depth[d][-1] or node.val %2 ==1: return False depth[d].append(node.val) if node: if node.left: queue.append((node.left, d+1)) if node.right: queue.append((node.right, d+1)) return True
even-odd-tree
python bfs
byuns9334
0
65
even odd tree
1,609
0.538
Medium
23,523
https://leetcode.com/problems/even-odd-tree/discuss/1436676/Python-or-BFS
class Solution: def isEvenOddTree(self, root: Optional[TreeNode]) -> bool: q=[[root,1]] arr=[] while q: node,lvl=q.pop(0) if lvl>len(arr): tlvl=lvl-1 if (tlvl%2==0 and node.val%2!=0) or (tlvl%2!=0 and node.val%2==0): arr.append([node.val]) else: return False else: if (tlvl%2==0 and node.val%2!=0 and node.val>arr[tlvl][-1]) or (tlvl%2!=0 and node.val%2==0 and node.val<arr[tlvl][-1]): arr[tlvl].append(node.val) else: return False if node.left: q.append([node.left,lvl+1]) if node.right: q.append([node.right,lvl+1]) return True
even-odd-tree
Python | BFS
heckt27
0
35
even odd tree
1,609
0.538
Medium
23,524
https://leetcode.com/problems/even-odd-tree/discuss/1299505/WEEB-DOES-PYTHON-BFS
class Solution: def isEvenOddTree(self, root: TreeNode) -> bool: queue, result, level = deque([root]), [], 1 if root.val % 2 != 1 : return False while queue: cur_arr = [] for _ in range(len(queue)): curNode = queue.popleft() cur_arr.append(curNode.val) if level % 2 == 0: if curNode.left: if curNode.left.val % 2 == 1: queue.append(curNode.left) else: return False if curNode.right: if curNode.right.val % 2 == 1: queue.append(curNode.right) else: return False else: if curNode.left: if curNode.left.val % 2 == 0: queue.append(curNode.left) else: return False if curNode.right: if curNode.right.val % 2 == 0: queue.append(curNode.right) else: return False level += 1 if len(set(cur_arr)) == len(cur_arr): # check for duplicates if level % 2 == 0 and sorted(cur_arr) != cur_arr: return False if level % 2 == 1 and sorted(cur_arr, reverse=True) != cur_arr: return False else: return False # if there are duplicates, there cannot be an increasing or decreasing order return True
even-odd-tree
WEEB DOES PYTHON BFS
Skywalker5423
0
65
even odd tree
1,609
0.538
Medium
23,525
https://leetcode.com/problems/even-odd-tree/discuss/885968/Python3-BFS
class Solution: def isEvenOddTree(self, root: TreeNode) -> bool: if not root: return True queue=[root] lvl=0 while queue: order=[] for _ in range(len(queue)): node=queue.pop(0) if lvl%2==0: if node.val&amp;1: if not order: order.append(node.val) else: if order[-1]<node.val: order.append(node.val) else: return False if node.left:queue.append(node.left) if node.right: queue.append(node.right) else: return False else: if node.val%2==0: if not order: order.append(node.val) else: if order[-1]>node.val: order.append(node.val) else: return False if node.left:queue.append(node.left) if node.right: queue.append(node.right) else: return False lvl+=1 return True
even-odd-tree
Python3 BFS
harshitCode13
0
51
even odd tree
1,609
0.538
Medium
23,526
https://leetcode.com/problems/maximum-number-of-visible-points/discuss/1502236/Python-Clean-Sliding-Window
class Solution: def visiblePoints(self, points: List[List[int]], angle: int, l: List[int]) -> int: array = [] nloc = 0 for p in points: if p == l: nloc += 1 else: array.append(math.degrees(atan2(p[1]-l[1], p[0]-l[0]))) array.sort() angles = array + [a+360 for a in array] left, maxm = 0, 0 for right, a in enumerate(angles): if a-angles[left] > angle: left += 1 maxm = max(right-left+1, maxm) return maxm + nloc
maximum-number-of-visible-points
[Python] Clean Sliding Window
soma28
1
669
maximum number of visible points
1,610
0.374
Hard
23,527
https://leetcode.com/problems/minimum-one-bit-operations-to-make-integers-zero/discuss/2273798/Easy-to-understand-6-line-solution-with-explanation-or-O(N)-time-O(1)-space
class Solution: def minimumOneBitOperations(self, n: int) -> int: """ to flip the bits to turn the number to zero Interpretation of Rules: - recursive: to turn a leading one of i bits to zero, the only way is to turn the i-1 bits to a leading one pattern and to turn the i-1 bits leading zero to zero, the only way is to turn the i-2 bits to a leading one pattern and so on, which is a recursive process (10000.. -> 11000.. -> 01000..), (01000.. -> 01100.. -> 00100), ..., (..010 -> ..011 -> ..001 -> ..000) - reversable: Let's make some observations to check if there's any pattern: - 2: 10 -> 11 -> 01 -> 00 - 4: 100 -> 101 -> 111 -> 110 -> 010 -> 011 -> 001 -> 000 - 8: 1000 -> 1001 -> 1011 -> 1010 -> 1110 -> 1111 -> 1101 -> 1100 -> 0100 -> (reversing 100 to 000) -> 0000 ... based on the observation, turning every i bits leading one to zero, is turning the i-1 bits from 00.. to 10.. and then back to 00.., which is a reverable process, and with the recursive process we can conclude that turning any length of 00..M-> 10.. is a reversable process - all unique states: since it is recursive and reversable, and we are flipping every bit between 1 and 0 programtically 10.. <-> 00.. we can conclude that every intermediate state in a process is unique (2**i unique states, so we need 2**i - 1 steps) for i bits 10.. <-> 00.. - numer of operations f(i) = 2**i - 1 this also aligns with the observation above that f(i) = 2*f(i-1) - 1 (-1 for no operation needed to achieve the initial 000) Process: to turn any binary to 0, we can turning the 1s to 0s one by one from lower bit to higher bit and because turning a higher bit 1 to 0, would passing the unique state including the lower bit 1s we can reverse those operations needed for the higher bit 100.. to the unique state including the lower bit 1s e.g. turning 1010100 to 0 - 1010(100) -> 1010(000), we will need 2**3 - 1 operations - 10(10000) -> 10(00000), we will need (2**5 - 1) - (2**3 - 1) operations we will be passing the state 10(10100), which is ready available from the last state so we can save/reverse/deduct the operations needed for 1010(000) <-> 1010(100) - ... so for any binary, f(binary) would tell us how many operations we need for binary <-> 000.. and for any more 1s, 100{binary} we can regard it as a process of 100.. <-> 100{binary} <-> 000{000..} which is 100.. <-> 000.. (2**i - 1) saving the operations 100{000..} <-> 100{binary} (f(binary)) = (2**i - 1) - f(last_binary) """ binary = format(n, "b") N, res = len(binary), 0 for i in range(1, N+1): if binary[-i] == "1": res = 2**i-1 - res return res
minimum-one-bit-operations-to-make-integers-zero
Easy to understand 6-line solution with explanation | O(N) time O(1) space
zhenyulin
2
370
minimum one bit operations to make integers zero
1,611
0.634
Hard
23,528
https://leetcode.com/problems/minimum-one-bit-operations-to-make-integers-zero/discuss/1197093/Simple-python3-solution-using-for-loop-with-99-memory-usage-and-90-runtime.
class Solution: def minimumOneBitOperations(self, n: int) -> int: x = '{0:b}'.format(n) y = list(x) r = 0 s = True for k in range(len(y)): if x[k]=='1' and s: r+=(2**(len(y)-k))-1 s=False elif x[k]=='1': r-=(2**(len(y)-k))-1 s=True return r
minimum-one-bit-operations-to-make-integers-zero
Simple python3 solution using for loop with 99% memory usage and 90% runtime.
Sanyamx1x
1
413
minimum one bit operations to make integers zero
1,611
0.634
Hard
23,529
https://leetcode.com/problems/minimum-one-bit-operations-to-make-integers-zero/discuss/882803/Python3-recursive-solution
class Solution: def minimumOneBitOperations(self, n: int) -> int: if not n: return 0 # edge case if not (n &amp; (n-1)): return 2*n-1 b = 1 << n.bit_length()-1 return self.minimumOneBitOperations((b>>1)^b^n) + b
minimum-one-bit-operations-to-make-integers-zero
[Python3] recursive solution
ye15
0
222
minimum one bit operations to make integers zero
1,611
0.634
Hard
23,530
https://leetcode.com/problems/maximum-nesting-depth-of-the-parentheses/discuss/1171599/Python3-Simple-And-Readable-Solution
class Solution: def maxDepth(self, s: str) -> int: depths = [0] count = 0 for i in s: if(i == '('): count += 1 elif(i == ')'): count -= 1 depths.append(count) return max(depths)
maximum-nesting-depth-of-the-parentheses
[Python3] Simple And Readable Solution
VoidCupboard
7
258
maximum nesting depth of the parentheses
1,614
0.827
Easy
23,531
https://leetcode.com/problems/maximum-nesting-depth-of-the-parentheses/discuss/1422545/O(1)-space-solution-in-Python
class Solution: def maxDepth(self, s: str) -> int: r = cnt = 0 for c in s: if c == ")": if cnt: cnt -= 1 r = max(r, cnt + 1) elif c == "(": cnt += 1 return r
maximum-nesting-depth-of-the-parentheses
O(1)-space solution in Python
mousun224
2
171
maximum nesting depth of the parentheses
1,614
0.827
Easy
23,532
https://leetcode.com/problems/maximum-nesting-depth-of-the-parentheses/discuss/888944/Python3-linear-scan
class Solution: def maxDepth(self, s: str) -> int: ans = op = 0 for c in s: if c == "(": op += 1 elif c == ")": op -= 1 ans = max(ans, op) return ans
maximum-nesting-depth-of-the-parentheses
[Python3] linear scan
ye15
2
93
maximum nesting depth of the parentheses
1,614
0.827
Easy
23,533
https://leetcode.com/problems/maximum-nesting-depth-of-the-parentheses/discuss/2825257/Python-oror-99.42-Faster-oror-Without-Stack-oror-O(N)-Solution
class Solution: def maxDepth(self, s: str) -> int: m,c,n=0,0,len(s) for i in range(n): if s[i]=='(': c+=1 m=max(c,m) elif s[i]==')': c-=1 return m
maximum-nesting-depth-of-the-parentheses
Python || 99.42% Faster || Without Stack || O(N) Solution
DareDevil_007
1
73
maximum nesting depth of the parentheses
1,614
0.827
Easy
23,534
https://leetcode.com/problems/maximum-nesting-depth-of-the-parentheses/discuss/1243432/Python3-space-efficent-short-code-with-explanation
class Solution: def maxDepth(self, s: str) -> int: num = maxnum = 0 for char in s: num += (char == "(") - (char == ")") maxnum = num if num > maxnum else maxnum return maxnum
maximum-nesting-depth-of-the-parentheses
Python3 space efficent, short code, with explanation
albezx0
1
59
maximum nesting depth of the parentheses
1,614
0.827
Easy
23,535
https://leetcode.com/problems/maximum-nesting-depth-of-the-parentheses/discuss/1094932/python-stack-based-solution
class Solution: def maxDepth(self, s: str) -> int: stack = [] maxlen =0 for w in s: if (w == "("): stack.append("(") if(maxlen < len(stack)): maxlen = maxlen+1 elif(w == ")"): stack.pop(-1) return maxlen
maximum-nesting-depth-of-the-parentheses
python, stack based solution
user7351c
1
66
maximum nesting depth of the parentheses
1,614
0.827
Easy
23,536
https://leetcode.com/problems/maximum-nesting-depth-of-the-parentheses/discuss/2814858/(-)-Easy-Simple-Commented-Linear-Solution
class Solution(object): def maxDepth(self, s): maxBrackets=0 #Deepest bracket bracketStack=[] #Stack to keep track of bracket pair for idx in range(len(s)): if s[idx]=='(': #if opening bracket we add to stack bracketStack.append(s[idx]) elif s[idx]==')':#if closing then we check if lenght of stack is greater than prev one maxBrackets=max(maxBrackets, len(bracketStack)) bracketStack.pop() #also pop the stack to move onwards. return maxBrackets
maximum-nesting-depth-of-the-parentheses
( ͡° ͜ʖ ͡°) Easy Simple Commented Linear Solution
fa19-bcs-016
0
2
maximum nesting depth of the parentheses
1,614
0.827
Easy
23,537
https://leetcode.com/problems/maximum-nesting-depth-of-the-parentheses/discuss/2810187/Easy-solution-using-stack-in-python
class Solution: def maxDepth(self, s: str) -> int: st = [] res = 0 for c in s: if c == "(": st.append(c) elif c == ")": res = max(res, len(st)) st.pop() return res
maximum-nesting-depth-of-the-parentheses
Easy solution using stack in python
ankurbhambri
0
7
maximum nesting depth of the parentheses
1,614
0.827
Easy
23,538
https://leetcode.com/problems/maximum-nesting-depth-of-the-parentheses/discuss/2757971/python-solution-using-stack
class Solution: def maxDepth(self, s: str) -> int: max_iv_seen = 0 stack = [] for ch in s: if ch == "(": stack.append(ch) greater_val = max(max_iv_seen, len(stack)) max_iv_seen = greater_val if ch == ")": stack.pop() return max_iv_seen
maximum-nesting-depth-of-the-parentheses
python solution using stack
samanehghafouri
0
5
maximum nesting depth of the parentheses
1,614
0.827
Easy
23,539
https://leetcode.com/problems/maximum-nesting-depth-of-the-parentheses/discuss/2715116/Python3-Solution
class Solution: def maxDepth(self, s: str) -> int: maximum = n = 0 for i in s: if i == "(": n += 1 maximum = max(maximum,n) if i == ")": n -= 1 return maximum
maximum-nesting-depth-of-the-parentheses
Python3 Solution
sipi09
0
2
maximum nesting depth of the parentheses
1,614
0.827
Easy
23,540
https://leetcode.com/problems/maximum-nesting-depth-of-the-parentheses/discuss/2697328/Stack-Solution-and-Simple-Solution(-o(n)-)
class Solution: def maxDepth(self, s: str) -> int: # By using Stack stack, res = [],0 for i in s: if (i == "("): stack.append(i) res = max(res, len(stack)) elif ( i==')'): stack.pop() return res # normal solution # count, max_num = 0,0 # for i in s: # if (i == "("): # count = count + 1 # ans = max(max_num, count) # elif (i == ")"): # count = count - 1 # return ans
maximum-nesting-depth-of-the-parentheses
Stack Solution and Simple Solution( o(n) )
Baboolal
0
3
maximum nesting depth of the parentheses
1,614
0.827
Easy
23,541
https://leetcode.com/problems/maximum-nesting-depth-of-the-parentheses/discuss/2657222/Python-stack-solution-with-explanation
class Solution: def maxDepth(self, s: str) -> int: stack = [] depth = 0 for c in s: if c == "(": stack.append(c) continue if c == ")" and stack[-1] == "(": depth = max(depth,len(stack)) stack.pop() return depth
maximum-nesting-depth-of-the-parentheses
Python stack solution with explanation
iamrahultanwar
0
5
maximum nesting depth of the parentheses
1,614
0.827
Easy
23,542
https://leetcode.com/problems/maximum-nesting-depth-of-the-parentheses/discuss/2558102/EASY-PYTHON3-SOLUTION-stack-O(n)
class Solution: def maxDepth(self, s: str) -> int: stack=[] count=0 for i in range(len(s)): if s[i]=="(": stack.append(s[i]) elif s[i]==")": stack.pop() else: continue count=max(count,len(stack)) return count
maximum-nesting-depth-of-the-parentheses
✅✔🔥 EASY PYTHON3 SOLUTION 🔥✅✔stack O(n)
rajukommula
0
26
maximum nesting depth of the parentheses
1,614
0.827
Easy
23,543
https://leetcode.com/problems/maximum-nesting-depth-of-the-parentheses/discuss/2500443/Solution-(Using-Stack)
class Solution: def maxDepth(self, s: str) -> int: check1 = 0 check2 = 0 stack = [] for i in range(len(s)): if s[i] == "(": stack.append("(") check1 = stack.count("(") if check1 > check2: check2 = check1 elif s[i] == ")": stack.pop() return check2
maximum-nesting-depth-of-the-parentheses
Solution (Using Stack)
fiqbal997
0
39
maximum nesting depth of the parentheses
1,614
0.827
Easy
23,544
https://leetcode.com/problems/maximum-nesting-depth-of-the-parentheses/discuss/2324239/Python-oror-Easy-Solution
class Solution: def maxDepth(self, s: str) -> int: bcount = 0 maxcount = 0 for i in range(len(s)): if s[i] == "(": bcount += 1 elif s[i] == ")": bcount -= 1 maxcount = max(bcount,maxcount) return maxcount
maximum-nesting-depth-of-the-parentheses
Python || Easy Solution
dyforge
0
18
maximum nesting depth of the parentheses
1,614
0.827
Easy
23,545
https://leetcode.com/problems/maximum-nesting-depth-of-the-parentheses/discuss/2310785/Python-Count-parentheses-or-O(n)or-Easy
class Solution: def maxDepth(self, s: str) -> int: c_in = 0 c_out = 0 max_diff = 0 for i in s: if i=='(': c_in+=1 elif i==')': c_out+=1 max_diff = max(max_diff, c_in-c_out) return max_diff
maximum-nesting-depth-of-the-parentheses
[Python] Count parentheses | O(n)| Easy
sunakshi132
0
10
maximum nesting depth of the parentheses
1,614
0.827
Easy
23,546
https://leetcode.com/problems/maximum-nesting-depth-of-the-parentheses/discuss/2290689/Python3-oror-No-Stack
class Solution: def maxDepth(self, s: str) -> int: maxDepth, curDepth = 0,0 for char in s: if char == "(": curDepth += 1 maxDepth = max(maxDepth, curDepth) elif char == ")": curDepth -= 1 return maxDepth
maximum-nesting-depth-of-the-parentheses
Python3 || No Stack
silva12345
0
14
maximum nesting depth of the parentheses
1,614
0.827
Easy
23,547
https://leetcode.com/problems/maximum-nesting-depth-of-the-parentheses/discuss/2115110/Easy-understanding-python-solution
class Solution: def maxDepth(self, s: str) -> int: c = 0 res = [] for i in s: if i == "(": c += 1 res.append(c) elif i == ")": c -= 1 res.append(c) return max(res) if res != [] else 0
maximum-nesting-depth-of-the-parentheses
Easy understanding python solution
nikhitamore
0
46
maximum nesting depth of the parentheses
1,614
0.827
Easy
23,548
https://leetcode.com/problems/maximum-nesting-depth-of-the-parentheses/discuss/1977417/Simple-Python-Solution-oror-50-Faster-oror-Memory-less-than-90
class Solution: def maxDepth(self, s: str) -> int: ans=0 ; p=0 for c in s: if c=='(': p+=1 elif c==')': p-=1 ans=max(ans,p) return ans
maximum-nesting-depth-of-the-parentheses
Simple Python Solution || 50% Faster || Memory less than 90%
Taha-C
0
54
maximum nesting depth of the parentheses
1,614
0.827
Easy
23,549
https://leetcode.com/problems/maximum-nesting-depth-of-the-parentheses/discuss/1903740/Python-easy-to-read-and-understand-or-stack
class Solution: def maxDepth(self, s: str) -> int: cnt, ans = 0, 0 for i in range(len(s)): if s[i] == '(': cnt += 1 elif s[i] == ')': cnt -= 1 ans = max(ans, cnt) return ans
maximum-nesting-depth-of-the-parentheses
Python easy to read and understand | stack
sanial2001
0
67
maximum nesting depth of the parentheses
1,614
0.827
Easy
23,550
https://leetcode.com/problems/maximum-nesting-depth-of-the-parentheses/discuss/1881394/Python-solution-without-using-stacks
class Solution: def maxDepth(self, s: str) -> int: depth = 0 max_depth = 0 for i in s: if i == '(': depth += 1 if depth > max_depth: max_depth = depth elif i == ')': depth -= 1 return max_depth
maximum-nesting-depth-of-the-parentheses
Python solution without using stacks
alishak1999
0
42
maximum nesting depth of the parentheses
1,614
0.827
Easy
23,551
https://leetcode.com/problems/maximum-nesting-depth-of-the-parentheses/discuss/1867584/Python%3A-using-List-as-Stack-or-Memory-97-or-Runtime-69
class Solution: def maxDepth(self, s: str) -> int: stack = [] depth = 0 max_depth = 0 for char in s: if char == "(": stack.append(char) depth += 1 max_depth = max(max_depth,depth) if char == ")": stack.pop() depth -= 1 if len(stack) == 0: return max_depth
maximum-nesting-depth-of-the-parentheses
Python: using List as Stack | Memory 97% | Runtime 69%
juneju_darad
0
46
maximum nesting depth of the parentheses
1,614
0.827
Easy
23,552
https://leetcode.com/problems/maximum-nesting-depth-of-the-parentheses/discuss/1825869/Python-solution
class Solution: def maxDepth(self, s: str) -> int: maxSoFar = 0 nested = 0 for i in s: if i=="(": nested+=1 if maxSoFar<nested: maxSoFar = nested elif i==")": nested-=1 return maxSoFar
maximum-nesting-depth-of-the-parentheses
Python solution
lucabonagd
0
32
maximum nesting depth of the parentheses
1,614
0.827
Easy
23,553
https://leetcode.com/problems/maximum-nesting-depth-of-the-parentheses/discuss/1753448/Simple-Python-Solution%3A-Beats-92-or-O(n)-time-complexity
class Solution: def maxDepth(self, s: str) -> int: depth = 0 max_depth = 0 for ch in s: if ch == '(': depth += 1 elif ch == ')': depth -= 1 else: continue max_depth = max(depth, max_depth) return max_depth
maximum-nesting-depth-of-the-parentheses
Simple Python Solution: Beats 92% | O(n) time complexity
dos_77
0
90
maximum nesting depth of the parentheses
1,614
0.827
Easy
23,554
https://leetcode.com/problems/maximum-nesting-depth-of-the-parentheses/discuss/1741342/Simple-solution-using-python3
class Solution: def maxDepth(self, s: str) -> int: ans = 0 stack = [] for item in s : if item == "(" : stack.append(item) elif item == ")" : ans = max(ans, len(stack)) stack.pop() return ans
maximum-nesting-depth-of-the-parentheses
Simple solution using python3
shakilbabu
0
27
maximum nesting depth of the parentheses
1,614
0.827
Easy
23,555
https://leetcode.com/problems/maximum-nesting-depth-of-the-parentheses/discuss/1705004/Python-solution-oror-O(n)-time-O(1)-space-complexity
class Solution: def maxDepth(self, s: str) -> int: ans = 0 stack_len = 0 for c in s: if c == "(": stack_len += 1 elif c == ")": ans = max(ans,stack_len) stack_len -= 1 return ans
maximum-nesting-depth-of-the-parentheses
Python solution || O(n) time, O(1) space complexity
s_m_d_29
0
75
maximum nesting depth of the parentheses
1,614
0.827
Easy
23,556
https://leetcode.com/problems/maximum-nesting-depth-of-the-parentheses/discuss/1630094/Easy-Python.-O(n)-time-or-O(1)-space.
class Solution: def maxDepth(self, s: str) -> int: if len(s) == 0 or len(s) == 1: return 0 depth = 0 maxDepth = 0 for char in s: if char == "(": depth+=1 maxDepth = max(depth,maxDepth) elif char == ")": depth -= 1 return maxDepth
maximum-nesting-depth-of-the-parentheses
Easy Python. O(n) time | O(1) space.
manassehkola
0
80
maximum nesting depth of the parentheses
1,614
0.827
Easy
23,557
https://leetcode.com/problems/maximum-nesting-depth-of-the-parentheses/discuss/1625402/Python3-Solution-with-using-stack
class Solution: def maxDepth(self, s: str) -> int: stack = [] res = cur_depth = 0 for c in s: if c == '(': cur_depth += 1 elif c == ')': res = max(res, cur_depth) cur_depth -= 1 return res
maximum-nesting-depth-of-the-parentheses
[Python3] Solution with using stack
maosipov11
0
44
maximum nesting depth of the parentheses
1,614
0.827
Easy
23,558
https://leetcode.com/problems/maximum-nesting-depth-of-the-parentheses/discuss/1591994/Python-3-easy-fast-solution
class Solution: def maxDepth(self, s: str) -> int: cur_open = 0 res = 0 for c in s: if c == '(': cur_open += 1 res = max(res, cur_open) elif c == ')': cur_open -= 1 return res
maximum-nesting-depth-of-the-parentheses
Python 3 easy, fast solution
dereky4
0
166
maximum nesting depth of the parentheses
1,614
0.827
Easy
23,559
https://leetcode.com/problems/maximum-nesting-depth-of-the-parentheses/discuss/1540664/Python3-solution
class Solution: def maxDepth(self, s: str) -> int: st = [] # stack of depth ans = 0 for c in s: if c=='(': depth = st[-1] + 1 if st else 1 ans = max(ans, depth) st.append(depth) elif c==')': st.pop() return ans
maximum-nesting-depth-of-the-parentheses
Python3 solution
dalechoi
0
36
maximum nesting depth of the parentheses
1,614
0.827
Easy
23,560
https://leetcode.com/problems/maximum-nesting-depth-of-the-parentheses/discuss/1528694/Python-simple-single-pass-solution
class Solution: def maxDepth(self, s: str) -> int: max_depth = 0 curr_depth = 0 for i in s: if i == '(': curr_depth += 1 max_depth = max(max_depth, curr_depth) elif i == ')': curr_depth -= 1 return max_depth
maximum-nesting-depth-of-the-parentheses
Python simple single pass solution
prnvshrn
0
30
maximum nesting depth of the parentheses
1,614
0.827
Easy
23,561
https://leetcode.com/problems/maximum-nesting-depth-of-the-parentheses/discuss/1437845/Python-6-Lines-Easy-to-Understand
class Solution(object): def maxDepth(self, s): """ :type s: str :rtype: int """ l, maxlen = 0, 0 for char in s: l += char == '(' l -= char == ')' maxlen = max(maxlen, l) return maxlen
maximum-nesting-depth-of-the-parentheses
Python 6 Lines Easy to Understand
SuperSteven369
0
135
maximum nesting depth of the parentheses
1,614
0.827
Easy
23,562
https://leetcode.com/problems/maximum-nesting-depth-of-the-parentheses/discuss/1335130/Simple-Stack-Solution
class Solution: def maxDepth(self, s: str) -> int: stack = [] max_length = 0 for char in s: if char == "(": stack.append(char) if len(stack) > max_length: max_length = len(stack) if char == ")": stack.pop() return max_length
maximum-nesting-depth-of-the-parentheses
Simple Stack Solution
DuncanScu
0
62
maximum nesting depth of the parentheses
1,614
0.827
Easy
23,563
https://leetcode.com/problems/maximum-nesting-depth-of-the-parentheses/discuss/1096533/Easy-%2B-Clean-Python-beats-95
class Solution: def maxDepth(self, s: str) -> int: lefts = 0 max_depth = 0 for i in s: if i == '(': lefts += 1 max_depth = max(max_depth, lefts) elif i == ')': lefts -= 1 return max_depth
maximum-nesting-depth-of-the-parentheses
Easy + Clean Python beats 95%
Pythagoras_the_3rd
0
59
maximum nesting depth of the parentheses
1,614
0.827
Easy
23,564
https://leetcode.com/problems/maximum-nesting-depth-of-the-parentheses/discuss/1050694/Python3-faster-than-84.42
class Solution: def maxDepth(self, s: str) -> int: left_count = max_value = 0 for item in s: if item == "(": left_count += 1 max_value = max(left_count, max_value) if item == ")": left_count -= 1 return max_value
maximum-nesting-depth-of-the-parentheses
[Python3] faster than 84.42%
WiseLin
0
122
maximum nesting depth of the parentheses
1,614
0.827
Easy
23,565
https://leetcode.com/problems/maximum-nesting-depth-of-the-parentheses/discuss/1403673/Python3-using-stack-(FASTER-THAN-1000000000)
class Solution: def maxDepth(self, s: str) -> int: mostDepth = 0 stack = [] for i in range(0, len(s)): if s[i] == '(': stack.append('(') if len(stack) > mostDepth: mostDepth = len(stack) elif s[i] == ')': stack.pop() return mostDepth
maximum-nesting-depth-of-the-parentheses
Python3 using stack (FASTER THAN 1,000,000,000%)
mahadrehan
-1
123
maximum nesting depth of the parentheses
1,614
0.827
Easy
23,566
https://leetcode.com/problems/maximum-nesting-depth-of-the-parentheses/discuss/897497/Python-Easy-and-Efficient-Solution
class Solution: def maxDepth(self, s: str) -> int: maxDepth:int = 0 bracketNum:int = 0 for c in s: if c == '(': bracketNum += 1 if bracketNum > maxDepth: maxDepth = bracketNum elif c == ')': bracketNum -= 1 return maxDepth
maximum-nesting-depth-of-the-parentheses
[Python] Easy and Efficient Solution
rizwanmustafa0000
-1
54
maximum nesting depth of the parentheses
1,614
0.827
Easy
23,567
https://leetcode.com/problems/maximal-network-rank/discuss/888965/Python3-graph-as-adjacency-list
class Solution: def maximalNetworkRank(self, n: int, roads: List[List[int]]) -> int: graph = {} for u, v in roads: graph.setdefault(u, set()).add(v) graph.setdefault(v, set()).add(u) ans = 0 for i in range(n): for j in range(i+1, n): val = len(graph.get(i, set())) + len(graph.get(j, set())) - (j in graph.get(i, set())) ans = max(ans, val) return ans
maximal-network-rank
[Python3] graph as adjacency list
ye15
8
1,100
maximal network rank
1,615
0.581
Medium
23,568
https://leetcode.com/problems/maximal-network-rank/discuss/1927264/PYTHON-Intuitive-solution-with-clear-explaination-2-approaches
class Solution: def maximalNetworkRank(self, n: int, roads: List[List[int]]) -> int: if roads == []: #egde case check return 0 node_degrees = defaultdict(int) for i in roads: node_degrees[i[0]]+=1 node_degrees[i[1]]+=1 maxx1, maxx2 = 0, 0 ans = 0 for i, k in node_degrees.items(): #O(N) if k >= maxx1: maxx1 = k maxx2 = 0 for j, l in node_degrees.items(): #O(N) if l >= maxx2 and j!=i: maxx2 = l if [i, j] in roads or [j, i] in roads: #O(N) ans = max(ans, maxx1 + maxx2 - 1) else: ans = max(ans, maxx1 + maxx2 ) return ans
maximal-network-rank
[PYTHON] Intuitive solution with clear explaination [2 approaches] ✔
RaghavGupta22
3
495
maximal network rank
1,615
0.581
Medium
23,569
https://leetcode.com/problems/maximal-network-rank/discuss/1927264/PYTHON-Intuitive-solution-with-clear-explaination-2-approaches
class Solution: def maximalNetworkRank(self, n: int, roads: List[List[int]]) -> int: if roads == []: #egde case check return 0 #create adjacency matrix to check if edge present or not in O(1) time adj=[[0]*(n) for i in range(n)] for i in roads: adj[i[0]][i[1]] = 1 adj[i[1]][i[0]] = 1 node_degrees = defaultdict(int) for i in roads: node_degrees[i[0]]+=1 node_degrees[i[1]]+=1 maxx1, maxx2 = 0, 0 ans = 0 for i, k in node_degrees.items(): #O(N) if k >= maxx1: maxx1 = k maxx2 = 0 for j, l in node_degrees.items(): #O(N) if l >= maxx2 and j!=i: maxx2 = l if adj[i][j] == 1 or adj[j][i] == 1: #O(1) ans = max(ans, maxx1 + maxx2 - 1) else: ans = max(ans, maxx1 + maxx2 ) return ans
maximal-network-rank
[PYTHON] Intuitive solution with clear explaination [2 approaches] ✔
RaghavGupta22
3
495
maximal network rank
1,615
0.581
Medium
23,570
https://leetcode.com/problems/maximal-network-rank/discuss/2741024/Fast-python-solution
class Solution: def maximalNetworkRank(self, n: int, roads: List[List[int]]) -> int: indegree=[0]*n for i,j in roads: indegree[i]+=1 indegree[j]+=1 fMax,sMax=0,0 fCt,sCt=0,0 for i in indegree: if i>fMax: sMax=fMax fMax=i sCt=fCt fCt=1 elif i<fMax and i>sMax: sMax=i sCt=1 else: if i==fMax: fCt+=1 elif i==sMax: sCt+=1 # print(fMax,fCt) # print(sMax,sCt) if fCt>1: edcount=0 for road in roads: if indegree[road[0]]==fMax and indegree[road[1]]==fMax: edcount+=1 if edcount==((fCt*(fCt-1))//2): flag=1 else: flag=0 return 2*fMax-flag else: edcount=0 for road in roads: if indegree[road[0]]==fMax and indegree[road[1]]==sMax: edcount+=1 if indegree[road[1]]==fMax and indegree[road[0]]==sMax: edcount+=1 if sCt==edcount: flag=1 else: flag=0 return fMax+sMax-flag
maximal-network-rank
Fast python solution
beneath_ocean
1
308
maximal network rank
1,615
0.581
Medium
23,571
https://leetcode.com/problems/maximal-network-rank/discuss/1967490/Python-Matrix-Solution
class Solution: def maximalNetworkRank(self, n: int, roads: List[List[int]]) -> int: grid = [[0] * n for _ in range(n)] for s, d in roads: grid[s][d] = 1 grid[d][s] = 1 result = [] visited = set() for s in range(n): for d in range(n): if s != d and (d, s) not in visited: visited.add((s, d)) result.append(sum(grid[s]) + sum(grid[d]) - grid[s][d]) return max(result)
maximal-network-rank
[Python] Matrix Solution
tejeshreddy111
1
109
maximal network rank
1,615
0.581
Medium
23,572
https://leetcode.com/problems/maximal-network-rank/discuss/1812578/Self-understandable-python-with-comments-%3A
class Solution: def maximalNetworkRank(self, n: int, roads: List[List[int]]) -> int: adlist=[[] for x in range(n)] # adjacency list creation for i in roads: adlist[i[0]].append(i[1]) adlist[i[1]].append(i[0]) l=[] for i in range(len(adlist)): for j in range(i+1,len(adlist)): if i in adlist[j] and j in adlist[i]: # if both vertex are directly connected ,count only once between vertex l.append(len(adlist[i])+len(adlist[j])-1) else: # if vertex are not directly connected l.append(len(adlist[i])+len(adlist[j])) return max(l) # return maximun of all the sum of degrees
maximal-network-rank
Self understandable python with comments :
goxy_coder
1
120
maximal network rank
1,615
0.581
Medium
23,573
https://leetcode.com/problems/maximal-network-rank/discuss/2500020/Python3-clever-solution-oror-Clean-code
class Solution: def maximalNetworkRank(self, n: int, roads) -> int: max_rank = 0 connections = {i: set() for i in range(n)} for i, j in roads: connections[i].add(j) connections[j].add(i) for i in range(n - 1): for j in range(i + 1, n): max_rank = max(max_rank, len(connections[i]) + len(connections[j]) - (j in connections[i])) return max_rank
maximal-network-rank
✔️ [Python3] clever solution || Clean code
explusar
0
79
maximal network rank
1,615
0.581
Medium
23,574
https://leetcode.com/problems/maximal-network-rank/discuss/2389721/Python-simple-O(n2)
class Solution: def maximalNetworkRank(self, n: int, roads: List[List[int]]) -> int: ingresses = defaultdict(int) road_set = set() for (f, t) in roads: ingresses[f] += 1 ingresses[t] += 1 road_set.add((f,t)) road_set.add((t,f)) max_res = -sys.maxsize-1 for i in range(n): for j in range(i + 1, n): max_res = max(max_res, ingresses[i] + ingresses[j] - (1 if (i,j) in road_set else 0)) return max_res
maximal-network-rank
Python simple O(n^2)
sineslu
0
41
maximal network rank
1,615
0.581
Medium
23,575
https://leetcode.com/problems/maximal-network-rank/discuss/1840918/Python-or-Adjacency-List-Graph
class Solution: def maximalNetworkRank(self, n: int, roads: List[List[int]]) -> int: g = defaultdict(list) for u, v in roads: # create graph adjacency list g[u].append(v) g[v].append(u) res = 0 for i in range(n): for j in range(i+1, n): val = len(g[i]) + len(g[j]) # sum the amount of roads for each city if j in g[i]: # remove road connected to both cities val -= 1 res = max(res, val) return res
maximal-network-rank
Python | Adjacency List Graph
jgroszew
0
102
maximal network rank
1,615
0.581
Medium
23,576
https://leetcode.com/problems/split-two-strings-to-make-palindrome/discuss/888981/Python3-greedy
class Solution: def checkPalindromeFormation(self, a: str, b: str) -> bool: fn = lambda x: x == x[::-1] # check for palindrome i = 0 while i < len(a) and a[i] == b[~i]: i += 1 if fn(a[:i] + b[i:]) or fn(a[:-i] + b[-i:]): return True i = 0 while i < len(a) and a[~i] == b[i]: i += 1 if fn(b[:i] + a[i:]) or fn(b[:-i] + a[-i:]): return True return False
split-two-strings-to-make-palindrome
[Python3] greedy
ye15
6
299
split two strings to make palindrome
1,616
0.314
Medium
23,577
https://leetcode.com/problems/split-two-strings-to-make-palindrome/discuss/1698265/Easy-to-Understand-Python-Solution
class Solution: def checkPalindromeFormation(self, a: str, b: str) -> bool: return self.solve(a, b) or self.solve(b, a) def solve(self, a, b): i = 0 j = len(a) - 1 while i < j and a[i] == b[j]: i += 1 j -= 1 return self.isPalindrome(a[:i] + b[i:]) or self.isPalindrome(a[:j + 1] + b[j + 1:]) def isPalindrome(self, s): i = 0 j = len(s) - 1 while i < j: if s[i] != s[j]: return False i += 1 j -= 1 return True
split-two-strings-to-make-palindrome
Easy to Understand Python Solution
srihariv
1
107
split two strings to make palindrome
1,616
0.314
Medium
23,578
https://leetcode.com/problems/split-two-strings-to-make-palindrome/discuss/2728774/Python3-Solution-or-O(n)-or-Greedy
class Solution: def checkPalindromeFormation(self, A, B): n = len(A) def help(A, B): l = n // 2 - 1 while l >= 0 and A[l] == A[n - l - 1]: l -= 1 if A[:l+1] == B[:-l-2:-1] or A[:-l-2:-1] == B[:l+1]: return True return help(A, B) or help(B, A)
split-two-strings-to-make-palindrome
✔ Python3 Solution | O(n) | Greedy
satyam2001
0
7
split two strings to make palindrome
1,616
0.314
Medium
23,579
https://leetcode.com/problems/split-two-strings-to-make-palindrome/discuss/2610533/Python-Solution-or-Brute-Force-greater-2-pointers-or-Beats-100
class Solution: def checkPalindromeFormation(self, a: str, b: str) -> bool: n=len(a) # Brute Force: TLE # for i in range(n): # s1=a[:i]+b[i:] # s2=b[:i]+a[i:] # if s1==s1[::-1] or s2==s2[::-1]: # return True # return False # 2 pointers def check(s1,s2): l=0 r=n-1 while l<=r and s1[l]==s2[r]: l+=1 r-=1 if l>r or s1[l:r+1]==s1[l:r+1][::-1] or s2[l:r+1]==s2[l:r+1][::-1]: return True return False return check(a,b) or check(b,a)
split-two-strings-to-make-palindrome
Python Solution | Brute Force --> 2 pointers | Beats 100%
Siddharth_singh
0
22
split two strings to make palindrome
1,616
0.314
Medium
23,580
https://leetcode.com/problems/split-two-strings-to-make-palindrome/discuss/2467170/Easy-Python-O(N)-95-time-85-space-O(1)-space
class Solution: def checkPalindromeFormation(self, a: str, b: str) -> bool: def findLargePrefix(s1,s2): l,r = 0,len(s1)-1 while l <= r and s1[l] == s2[r]: l += 1 r -= 1 #Return True if s1 and s2 is proven to form a palidrome (l > r) midway #If s1 and s2 do not form a palidrome midway, return True if one of s1 or s2 #form a palidrome between index l and r if l > r or s1[l:r+1] == s1[l:r+1][::-1] or s2[l:r+1] == s2[l:r+1][::-1]: return True return False return findLargePrefix(a,b) or findLargePrefix(b,a)
split-two-strings-to-make-palindrome
Easy Python O(N) 95% time 85% space O(1) space
honey_grapes
0
33
split two strings to make palindrome
1,616
0.314
Medium
23,581
https://leetcode.com/problems/split-two-strings-to-make-palindrome/discuss/943124/Python3-Solution
class Solution: def check1(self,a,b,i,j): splita = a[i:j+1] splitb = b[i:j+1] return splita==splita[::-1] or splitb==splitb[::-1] def check(self,a,b): i = 0 j = len(b)-1 while(i<len(a)): if(a[i]==b[j]): i+=1 j-=1 else: break return self.check1(a,b,i,j) def checkPalindromeFormation(self, a: str, b: str) -> bool: return self.check(a,b) or self.check(b,a)
split-two-strings-to-make-palindrome
Python3 Solution
swap2001
0
156
split two strings to make palindrome
1,616
0.314
Medium
23,582
https://leetcode.com/problems/split-two-strings-to-make-palindrome/discuss/958066/Python-very-simple-solution-%3A-faster-than-99-memory-less-than-85
class Solution(object): def checkPalindromeFormation(self, a, b): """ :type a: str :type b: str :rtype: bool """ if len(a) == 1 or len(b) == 1: return True b = b[::-1] # reverse string b return (a[0] == b[0] and a[1] == b[1]) or (a[-1] == b[-1] and a[-2] == b[-2]) # search for same substrings : 1) start from head(a_prefix + b_suffix) # 2) start from tail(b_prefix + a_suffix).
split-two-strings-to-make-palindrome
Python very simple solution : faster than 99%, memory less than 85%
brianf765
-4
372
split two strings to make palindrome
1,616
0.314
Medium
23,583
https://leetcode.com/problems/count-subtrees-with-max-distance-between-cities/discuss/1068298/Python-Top-Down-DP-O(n5).-35-ms-and-faster-than-100-explained
class Solution: def countSubgraphsForEachDiameter(self, n: int, edges: List[List[int]]) -> List[int]: # Create Tree as adjacency list neigh: List[List[int]] = [[] for _ in range(n)] for u, v in edges: neigh[u - 1].append(v - 1) neigh[v - 1].append(u - 1) distance_array: List[int] = [0] * n def find_tree_center(vertices: List[int], adj_list: List[List[int]]) -> int: """Given a tree, return a central vertex (minimum radius vertex) with BFS""" num_neighbors: List[int] = list(map(len, adj_list)) leaf_nodes: Deque[int] = collections.deque((x for x in range(len(vertices)) if num_neighbors[x] == 1)) while len(leaf_nodes) > 1: leaf = leaf_nodes.popleft() for neighbor in adj_list[leaf]: num_neighbors[neighbor] -= 1 if num_neighbors[neighbor] == 1: leaf_nodes.append(neighbor) return leaf_nodes[0] def merge_into_parent(parent_subtrees: Dict[Tuple[int, int], int], child_subtrees: Dict[Tuple[int, int], int]) -> None: """ Helper function to merge two disjoint rooted trees T_parent and T_child rooted at 'parent' and 'child', into one tree rooted at 'parent', by adding an edge from 'parent' to 'child'. Called once for each edge in our tree. parent_subtrees[i, j] is the count of rooted subtrees of T_parent that contain 'parent', have diameter i, and height j. Worst case complexity: O(n^4) per call """ for (diam_for_parent, height_for_parent), count_from_parent in list(parent_subtrees.items()): for (diam_for_child, height_for_child), count_from_child in child_subtrees.items(): new_diameter = max(diam_for_parent, diam_for_child, height_for_parent + height_for_child + 1) new_height = max(height_for_parent, height_for_child + 1) parent_subtrees[new_diameter, new_height] = parent_subtrees.get((new_diameter, new_height), 0) + count_from_child * count_from_parent return None def compute_subtree_counts(current_vertex: int, last_vertex: int = -1) -> Dict[Tuple[int, int], int]: """Recursively counts subtrees rooted at current_vertex using DFS, with edge from current_vertex to 'last_vertex' (parent node) cut off""" subtree_counts: Dict[Tuple[int, int], int] = {(0, 0): 1} for child_vertex in neigh[current_vertex]: if child_vertex == last_vertex: continue merge_into_parent(parent_subtrees=subtree_counts, child_subtrees=compute_subtree_counts(current_vertex=child_vertex, last_vertex=current_vertex)) for (diameter, height), subtree_count in subtree_counts.items(): distance_array[diameter] += subtree_count return subtree_counts # Optimization: Use a max-degree vertex as our root to minimize recursion depth max_degree_vertex: int = find_tree_center(vertices=list(range(n)), adj_list=neigh) compute_subtree_counts(current_vertex=max_degree_vertex) return distance_array[1:]
count-subtrees-with-max-distance-between-cities
[Python] Top-Down DP, O(n^5). 35 ms and faster than 100%, explained
kcsquared
2
137
count subtrees with max distance between cities
1,617
0.657
Hard
23,584
https://leetcode.com/problems/count-subtrees-with-max-distance-between-cities/discuss/889069/Python3-brute-force
class Solution: def countSubgraphsForEachDiameter(self, n: int, edges: List[List[int]]) -> List[int]: def fn(edges): """ """ graph = {} # graph as adjacency list for u, v in edges: graph.setdefault(u-1, []).append(v-1) # 0-indexed graph.setdefault(v-1, []).append(u-1) group = [None]*n dist = [0]*n def dfs(x, d=0): """ """ seen.add(x) # mark visited for xx in graph.get(x, []): dist[x] = max(dist[x], d) if group[xx] is None: group[xx] = group[x] if xx not in seen: dfs(xx, d+1) for i in range(n): seen = set() if group[i] is None: group[i] = i dfs(i) return group, dist ans = {} # answer for r in range(1, len(edges)+1): for x in combinations(edges, r): temp = {} d = {} seen, dist = fn(x) for i in range(n): temp.setdefault(seen[i], []).append(i) if seen[i] not in d: d[seen[i]] = dist[i] else: d[seen[i]] = max(d[seen[i]], dist[i]) for k, v in temp.items(): if len(v) > 1: ans.setdefault(d[k], set()).add(tuple(sorted(v))) return [len(ans.get(x, set())) for x in range(1, n)]
count-subtrees-with-max-distance-between-cities
[Python3] brute force
ye15
1
64
count subtrees with max distance between cities
1,617
0.657
Hard
23,585
https://leetcode.com/problems/count-subtrees-with-max-distance-between-cities/discuss/2335187/Python3-or-Bitmask%2BFloyd-Warshall
class Solution: def countSubgraphsForEachDiameter(self, n: int, edges: List[List[int]]) -> List[int]: def maxDistance(subtree): edges,node,maxD=[0]*3 for i in range(n): if (subtree>>i)&amp;1==0:continue node+=1 for j in range(i+1,n): if (subtree>>j)&amp;1==0:continue edges+=dist[i][j]==1 maxD=max(maxD,dist[i][j]) if edges!=node-1: return 0 else: return maxD dist=[[float('inf')]*n for i in range(n)] for i,j in edges: dist[i-1][j-1]=dist[j-1][i-1]=1 for mid in range(n): for n1 in range(n): for n2 in range(n): dist[n1][n2]=min(dist[n1][n2],dist[n1][mid]+dist[mid][n2]) ans=[0]*(n-1) for i in range(1,2**n): d=maxDistance(i) if d>0: ans[d-1]+=1 return ans
count-subtrees-with-max-distance-between-cities
[Python3] | Bitmask+Floyd-Warshall
swapnilsingh421
0
32
count subtrees with max distance between cities
1,617
0.657
Hard
23,586
https://leetcode.com/problems/mean-of-array-after-removing-some-elements/discuss/1193688/2-easy-Python-Solutions
class Solution: def trimMean(self, arr: List[int]) -> float: arr.sort() return statistics.mean(arr[int(len(arr)*5/100):len(arr)-int(len(arr)*5/100)])
mean-of-array-after-removing-some-elements
2 easy Python Solutions
ayushi7rawat
6
617
mean of array after removing some elements
1,619
0.647
Easy
23,587
https://leetcode.com/problems/mean-of-array-after-removing-some-elements/discuss/1193688/2-easy-Python-Solutions
class Solution: def trimMean(self, arr: List[int]) -> float: arr.sort() n = len(arr) per = int(n*5/100) l2 = arr[per:len(arr)-per] x = sum(l2)/len(l2) return x
mean-of-array-after-removing-some-elements
2 easy Python Solutions
ayushi7rawat
6
617
mean of array after removing some elements
1,619
0.647
Easy
23,588
https://leetcode.com/problems/mean-of-array-after-removing-some-elements/discuss/2099619/PYTHON-or-Without-sorting-or-Easy-solution
class Solution: def trimMean(self, arr: List[int]) -> float: counter = 0.05*len(arr) while counter != 0: arr.remove(min(arr)) arr.remove(max(arr)) counter -= 1 return sum(arr) / len(arr)
mean-of-array-after-removing-some-elements
PYTHON | Without sorting | Easy solution
shreeruparel
3
216
mean of array after removing some elements
1,619
0.647
Easy
23,589
https://leetcode.com/problems/mean-of-array-after-removing-some-elements/discuss/1229373/Python-Easy-solution-with-comments
class Solution: def trimMean(self, arr: List[int]) -> float: arr.sort() #Sorting list per = ceil(0.05 * len(arr)) #calculating 5% of length of list while per!=0: #removing 5% of first and last elements from the list arr.pop() arr.pop(0) per-=1 return sum(arr)/len(arr) #returning mean
mean-of-array-after-removing-some-elements
[Python] Easy solution with comments
arkumari2000
2
164
mean of array after removing some elements
1,619
0.647
Easy
23,590
https://leetcode.com/problems/mean-of-array-after-removing-some-elements/discuss/1146037/Python3-Simple-Solution-44ms-runtime
class Solution: def trimMean(self, arr: List[int]) -> float: arr.sort() percent = int(len(arr)*0.05) return sum(arr[percent:-percent])/len(arr[percent:-percent])
mean-of-array-after-removing-some-elements
Python3, Simple Solution 44ms runtime
naiem_ece
2
105
mean of array after removing some elements
1,619
0.647
Easy
23,591
https://leetcode.com/problems/mean-of-array-after-removing-some-elements/discuss/1346753/Python3ororfaster-than-98.15
class Solution: def trimMean(self, arr: List[int]) -> float: #first find whats the 5% of the array size n=len(arr) remove = int(0.05*(n)) #this many integers are removed from start and end of sorted array arr.sort() peice = arr[remove:n-remove] return sum(peice)/(n-2*remove)
mean-of-array-after-removing-some-elements
Python3||faster than 98.15%
ana_2kacer
1
122
mean of array after removing some elements
1,619
0.647
Easy
23,592
https://leetcode.com/problems/mean-of-array-after-removing-some-elements/discuss/1159018/python-faster-than-99.90
class Solution: def trimMean(self, arr: List[int]) -> float: arr.sort() idx = int(len(arr)*0.05) removed_arr = arr[idx:-idx] return sum(removed_arr) / len(removed_arr)
mean-of-array-after-removing-some-elements
python faster than 99.90%
keewook2
1
195
mean of array after removing some elements
1,619
0.647
Easy
23,593
https://leetcode.com/problems/mean-of-array-after-removing-some-elements/discuss/1055478/Easy-to-understand-Python3-faster-than-97
class Solution: def trimMean(self, arr: List[int]) -> float: from math import floor from math import ceil arr_size = len(arr) lower_bound = ceil(arr_size * 0.05) upper_bound = floor(arr_size * 0.95) new_arr = sorted(arr)[lower_bound:upper_bound] return sum(new_arr) / len(new_arr)
mean-of-array-after-removing-some-elements
Easy to understand Python3, faster than 97%
fbordwell
1
124
mean of array after removing some elements
1,619
0.647
Easy
23,594
https://leetcode.com/problems/mean-of-array-after-removing-some-elements/discuss/2819652/Simple-python-solution-using-sorting-and-some-simple-iteration%3A
class Solution: def trimMean(self, arr: List[int]) -> float: n=len(arr) n1=(5*n)//100#kitne elements remove krne h(min) n2=(5*n)//100#min k1=(5*n)//100#kitne elements remove krne h(min) k2=(5*n)//100#(max) arr.sort() while k1!=0: arr.remove(arr[0]) k1-=1 while k2!=0: arr.remove(arr[-1]) k2-=1 return sum(arr)/(n-n1-n2)
mean-of-array-after-removing-some-elements
Simple python solution using sorting and some simple iteration:
insane_me12
0
1
mean of array after removing some elements
1,619
0.647
Easy
23,595
https://leetcode.com/problems/mean-of-array-after-removing-some-elements/discuss/2436810/Mean-of-Array-After-Removing-Some-Elements
class Solution: def trimMean(self, arr: List[int]) -> float: arr.sort() toBeRemoved =floor( len(arr)*5/100.0) x = arr[toBeRemoved:-toBeRemoved] return sum(x)/len(x)
mean-of-array-after-removing-some-elements
Mean of Array After Removing Some Elements
dhananjayaduttmishra
0
20
mean of array after removing some elements
1,619
0.647
Easy
23,596
https://leetcode.com/problems/mean-of-array-after-removing-some-elements/discuss/2436810/Mean-of-Array-After-Removing-Some-Elements
class Solution: def merge(self ,arr,L,R,m): i = j = k = 0 while i <len(L) and j < len(R): if L[i]<R[j]: arr[k]= L[i] i+=1 else: arr[k]=R[j] j+=1 k+=1 while i < len(L): arr[k]= L[i] i+=1 k+=1 while j < len(R): arr[k] = R[j] j+=1 k+=1 def mergeSort(self,arr): if len(arr)>1: m = len(arr)//2 L = arr[:m] R = arr[m:] self.mergeSort(L) self.mergeSort(R) self.merge(arr,L,R,m) def trimMean(self, arr: List[int]) -> float: self.mergeSort(arr) toBeRemoved =floor( len(arr)*5/100.0) x = arr[toBeRemoved:-toBeRemoved] return sum(x)/len(x)
mean-of-array-after-removing-some-elements
Mean of Array After Removing Some Elements
dhananjayaduttmishra
0
20
mean of array after removing some elements
1,619
0.647
Easy
23,597
https://leetcode.com/problems/mean-of-array-after-removing-some-elements/discuss/2393722/FASTER-than-98-in-BOTH-RUNTIME-and-MEMORY
class Solution: def trimMean(self, arr: List[int]) -> float: s=(5*len(arr))//100 arr.sort() for i in range(s): arr[i]=0 arr[-(i+1)]=0 return sum(arr)/(len(arr)-(2*s))
mean-of-array-after-removing-some-elements
FASTER than 98% in BOTH RUNTIME and MEMORY
keertika27
0
31
mean of array after removing some elements
1,619
0.647
Easy
23,598
https://leetcode.com/problems/mean-of-array-after-removing-some-elements/discuss/2284461/Mean-of-array-after-removing-some-elements
class Solution: def trimMean(self, arr: List[int]) -> float: x=sorted(arr) res=0.05*len(arr) res1=x[int(res):len(x)] fin_res=res1[0:len(res1)-int(res)] result=float(sum(fin_res)/(len(fin_res))) return result
mean-of-array-after-removing-some-elements
Mean of array after removing some elements
Faraz369
0
9
mean of array after removing some elements
1,619
0.647
Easy
23,599