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/contains-duplicate-ii/discuss/2834879/PYTHON-SOLUTION-HASHMAP-oror-EXPLAINED
class Solution: def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool: if len(nums)<=k: #if not totally k values then check the duplicates only if len(set(nums))!=len(nums): return True d={} for i in range(len(nums)): #store the indeces of occurences of particular number in nums if nums[i] in d: #if number already present in d for j in d[nums[i]]: #check the indeces difference from current index of nums if abs(i - j) <= k: return True #found duplicate and abs(i - j) <= k d[nums[i]].append(i) #otherwise store the index else: d[nums[i]]=[i] return False
contains-duplicate-ii
PYTHON SOLUTION - HASHMAP || EXPLAINED βœ”
T1n1_B0x1
0
7
contains duplicate ii
219
0.423
Easy
3,900
https://leetcode.com/problems/contains-duplicate-ii/discuss/2829584/Python-Solution
class Solution: def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool: hmap = {} for index in range(0, len(nums)): if nums[index] in hmap: if abs(index - hmap.get(nums[index])) <= k: return True else: hmap[nums[index]] = index else: hmap[nums[index]] = index return False
contains-duplicate-ii
Python Solution
Antoine703
0
1
contains duplicate ii
219
0.423
Easy
3,901
https://leetcode.com/problems/contains-duplicate-ii/discuss/2800959/Easy-to-understand-python-solution.
class Solution: def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool: val_idxs = dict() for idx in range(len(nums)): val = nums[idx] if val in val_idxs: for another_idx in val_idxs[val]: if abs(idx - another_idx) <= k: return True val_idxs[val].append(idx) else: val_idxs[val] = [idx] return False
contains-duplicate-ii
Easy to understand python solution.
shanemmay
0
2
contains duplicate ii
219
0.423
Easy
3,902
https://leetcode.com/problems/contains-duplicate-ii/discuss/2793898/Python-beats-91-(iterative-approach)
class Solution: def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool: dups = {} for i, n in enumerate(nums): if n in dups.keys(): idx = dups.get(n) if i - idx <= k: return True dups.update({ n: i }) else: dups[n] = i return False
contains-duplicate-ii
Python beats 91% (iterative approach)
farruhzokirov00
0
12
contains duplicate ii
219
0.423
Easy
3,903
https://leetcode.com/problems/contains-duplicate-ii/discuss/2780477/Python3-100-faster-with-explanation
class Solution: def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool: if len(nums) == len(set(nums)): return False imap = {} for i in range(len(nums)): if nums[i] in imap: #run check for True for item in imap[nums[i]]: if abs(item - i) <= k: return True imap[nums[i]].append(i) else: imap[nums[i]] = [i] return False
contains-duplicate-ii
Python3, 100% faster with explanation
cvelazquez322
0
14
contains duplicate ii
219
0.423
Easy
3,904
https://leetcode.com/problems/contains-duplicate-ii/discuss/2780357/Python3-hashing-or-best-solution
class Solution: def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool: d = {} for i in range(len(nums)): if nums[i] in d and abs(i - d[nums[i]]) <= k: return True d[nums[i]] = i return False
contains-duplicate-ii
Python3 - hashing | best solution
sandeepmatla
0
1
contains duplicate ii
219
0.423
Easy
3,905
https://leetcode.com/problems/contains-duplicate-ii/discuss/2752571/Simple-Python3-Solution-Beats-97-in-runtime-using-dictionary-concept
class Solution: def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool: temp_dict = {} for x in range(0, len(nums)): if nums[x] in temp_dict and abs(temp_dict[nums[x]] - x) <= k: return True temp_dict[nums[x]] = x return False
contains-duplicate-ii
Simple Python3 Solution Beats 97% in runtime using dictionary concept
vivekrajyaguru
0
10
contains duplicate ii
219
0.423
Easy
3,906
https://leetcode.com/problems/contains-duplicate-ii/discuss/2732409/BRUTEFORCE-EASY-SOLUTION
class Solution: # calculating min distance between same numbers def helper(self,arr): mini = float("infinity") for i in range(1,len(arr)): #minimum window between two elements if (arr[i] - arr[i-1]) < mini: mini = arr[i] - arr[i-1] return mini def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool: # list element maps to their index dist = {} res = float("infinity") for i in range(len(nums)): try: dist[nums[i]].append(i) except: dist[nums[i]] = [i] for arr,index in dist.items(): if len(index) > 1: res = self.helper(index) return True if res<=k else False
contains-duplicate-ii
BRUTEFORCE EASY SOLUTION
azar1
0
13
contains duplicate ii
219
0.423
Easy
3,907
https://leetcode.com/problems/contains-duplicate-ii/discuss/2730638/Fastest-Solution-In-Python-Python-Simple-Python-Solution-100-Optimal-Solution
class Solution: def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool: n = len(nums) dd = {} for i in range(n): if nums[i] in dd.keys(): if abs(dd[nums[i]] - i) <= k: return True else: dd[nums[i]] = i else: dd[nums[i]] = i return False
contains-duplicate-ii
Fastest Solution In Python [ Python ] βœ… Simple Python Solution βœ…βœ…βœ… 100% Optimal Solution
vaibhav0077
0
9
contains duplicate ii
219
0.423
Easy
3,908
https://leetcode.com/problems/contains-duplicate-ii/discuss/2730527/Python-90-Faster-than-other-Python-Solutions
class Solution: def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool: returnVal = False numDict = {} for i in range(len(nums)): if nums[i] in numDict: if abs(numDict[nums[i]] - i) <= k: returnVal = True return returnVal numDict[nums[i]] = i return returnVal
contains-duplicate-ii
Python 90% Faster than other Python Solutions
FarazAli584682
0
5
contains duplicate ii
219
0.423
Easy
3,909
https://leetcode.com/problems/contains-duplicate-ii/discuss/2730165/Simple-Solution-O(n)
class Solution: def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool: result = {} # [val, ind] n = len(nums) for i in range(n): if nums[i] in result: target, index = nums[i], result[nums[i]] if abs(index - i) <= k: return True result[nums[i]] = i return False
contains-duplicate-ii
Simple Solution - O(n)
Vedant-G
0
8
contains duplicate ii
219
0.423
Easy
3,910
https://leetcode.com/problems/contains-duplicate-ii/discuss/2730013/Python-easy-solution-with-while-loop
class Solution: def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool: i = 0 seen = {} while i < len(nums): if nums[i] not in seen.keys(): seen[nums[i]] = i else: if abs(i-seen[nums[i]]) <= k: return True else: seen[nums[i]] = i i += 1 return False
contains-duplicate-ii
Python easy solution with while loop
vegancyberpunk
0
6
contains duplicate ii
219
0.423
Easy
3,911
https://leetcode.com/problems/contains-duplicate-ii/discuss/2729982/Stupid-simple-python-solution-O(n-min(nk))-time-or-vertical-oror-bars-or
class Solution: def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool: memo = {} for i, num in enumerate(nums): # Created a list of seen indices for the number if seen if num in memo: # scan sub list for sub_num in memo[num]: if abs(sub_num - i) <= k: return True memo[num] = memo[num] + [i] # If not seen, start the list else: memo[num] = [i] return False
contains-duplicate-ii
Stupid simple python solution O(n min(n,k)) time | vertical || bars |
vdz1192
0
5
contains duplicate ii
219
0.423
Easy
3,912
https://leetcode.com/problems/contains-duplicate-ii/discuss/2729812/python-with-dictionary-2-loops-80
class Solution: def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool: if len(nums) < 2: return False di = {} for ind, num in enumerate(nums): if di.get(num) is None: di[num] = [ind] else: di[num].append(ind) for idxes in di.values(): if len(idxes) > 1: for i_ind in range(len(idxes)): for j_ind in range(i_ind+1, len(idxes)): if abs(idxes[i_ind] - idxes[j_ind]) <= k: return True return False return False
contains-duplicate-ii
python with dictionary 2 loops 80%
m-s-dwh-bi
0
3
contains duplicate ii
219
0.423
Easy
3,913
https://leetcode.com/problems/contains-duplicate-ii/discuss/2729612/Beginner's-Friendly-Solution-or-Python
class Solution(object): def containsNearbyDuplicate(self, nums, k): hashT = {} for i in range(len(nums)): if nums[i] in hashT: if abs(i - hashT[nums[i]]) <= k: return True hashT[nums[i]] = i return False
contains-duplicate-ii
Beginner's Friendly Solution | Python
its_krish_here
0
12
contains duplicate ii
219
0.423
Easy
3,914
https://leetcode.com/problems/contains-duplicate-ii/discuss/2729525/PYTHON-Easy-python-solution
class Solution: def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool: length = len(nums) if k >= length - 1: return True if len(set(nums)) < len(nums) else False hash_table = dict() for counter in range(length): if nums[counter] not in hash_table: hash_table[nums[counter]] = counter elif counter - hash_table[nums[counter]] <= k: return True else: hash_table[nums[counter]] = counter return False
contains-duplicate-ii
[PYTHON] Easy python solution
valera_grishko
0
7
contains duplicate ii
219
0.423
Easy
3,915
https://leetcode.com/problems/contains-duplicate-ii/discuss/2729332/Easy-HashMap-in-Python
class Solution: # simple HashMap Solution # Proof -> If n exists before and the indices differnce is <= k then it must be from # the last occurence of n in the array nums. def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool: hm = defaultdict(int) for i, n in enumerate(nums): if n in hm and abs(hm[n] - i) <= k: return True hm[n] = i return False
contains-duplicate-ii
Easy HashMap in PythonπŸ₯Ά
shiv-codes
0
3
contains duplicate ii
219
0.423
Easy
3,916
https://leetcode.com/problems/contains-duplicate-ii/discuss/2729326/Simple-python-solution-using-dictionary
class Solution: def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool: d = defaultdict(int) for i, num in enumerate(nums): if num in d and i - d[num] <= k: return True d[num] = i return False
contains-duplicate-ii
Simple python solution using dictionary
Jaykant
0
3
contains duplicate ii
219
0.423
Easy
3,917
https://leetcode.com/problems/contains-duplicate-ii/discuss/2729126/Intuitive-Python-Set-Approach-(With-explanation)
class Solution: def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool: # if k was bigger than the array, we anyways need to look inside the array only k = min(k, len(nums)) # building the seen set seen = set() for i in range(k): if nums[i] in seen: return True seen.add(nums[i]) l = 0 # the lower bound of the window for i in range(k, len(nums)): if nums[i] in seen: return True seen.add(nums[i]) seen.remove(nums[l]) l += 1 return False
contains-duplicate-ii
Intuitive Python Set Approach (With explanation)
g_aswin
0
7
contains duplicate ii
219
0.423
Easy
3,918
https://leetcode.com/problems/contains-duplicate-ii/discuss/2729005/Python-Simple-Python-Solution-Using-Hashmap-or-Dictionary
class Solution: def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool: d={} for i in range(len(nums)): if nums[i] in d and abs(i-d[nums[i]])<=k: return True d[nums[i]]=i return False
contains-duplicate-ii
[ Python ] βœ…βœ… Simple Python Solution Using Hashmap or Dictionary πŸ₯³βœŒπŸ‘
ASHOK_KUMAR_MEGHVANSHI
0
10
contains duplicate ii
219
0.423
Easy
3,919
https://leetcode.com/problems/contains-duplicate-ii/discuss/2729005/Python-Simple-Python-Solution-Using-Hashmap-or-Dictionary
class Solution: def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool: hashmap = {} for index in range(len(nums)): if nums[index] not in hashmap: hashmap[nums[index]] = [index] else: hashmap[nums[index]].append(index) for key in hashmap: array = hashmap[key] if len(array) != 1: for i in range(len(array) - 1): for j in range(i+1,len(array)): if abs(array[i] - array[j]) <= k: return True return False
contains-duplicate-ii
[ Python ] βœ…βœ… Simple Python Solution Using Hashmap or Dictionary πŸ₯³βœŒπŸ‘
ASHOK_KUMAR_MEGHVANSHI
0
10
contains duplicate ii
219
0.423
Easy
3,920
https://leetcode.com/problems/contains-duplicate-iii/discuss/825267/Python3-summarizing-Contain-Duplicates-I-II-III
class Solution: def containsDuplicate(self, nums: List[int]) -> bool: seen = set() for x in nums: if x in seen: return True seen.add(x) return False
contains-duplicate-iii
[Python3] summarizing Contain Duplicates I, II, III
ye15
22
689
contains duplicate iii
220
0.22
Hard
3,921
https://leetcode.com/problems/contains-duplicate-iii/discuss/825267/Python3-summarizing-Contain-Duplicates-I-II-III
class Solution: def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool: seen = {} for i, x in enumerate(nums): if x in seen and i - seen[x] <= k: return True seen[x] = i return False
contains-duplicate-iii
[Python3] summarizing Contain Duplicates I, II, III
ye15
22
689
contains duplicate iii
220
0.22
Hard
3,922
https://leetcode.com/problems/contains-duplicate-iii/discuss/825267/Python3-summarizing-Contain-Duplicates-I-II-III
class Solution: def containsNearbyAlmostDuplicate(self, nums: List[int], k: int, t: int) -> bool: if t < 0: return False # edge case seen = {} for i, x in enumerate(nums): bkt = x//(t+1) if bkt in seen and i - seen[bkt][0] <= k: return True if bkt-1 in seen and i - seen[bkt-1][0] <= k and abs(x - seen[bkt-1][1]) <= t: return True if bkt+1 in seen and i - seen[bkt+1][0] <= k and abs(x - seen[bkt+1][1]) <= t: return True seen[bkt] = (i, x) return False
contains-duplicate-iii
[Python3] summarizing Contain Duplicates I, II, III
ye15
22
689
contains duplicate iii
220
0.22
Hard
3,923
https://leetcode.com/problems/contains-duplicate-iii/discuss/825606/Python-3-or-Official-Solution-in-Python-3-or-2-Methods-or-Explanation
class Solution: def containsNearbyAlmostDuplicate(self, nums: List[int], k: int, t: int) -> bool: from sortedcontainers import SortedSet if not nums or t < 0: return False # Handle special cases ss, n = SortedSet(), 0 # Create SortedSet. `n` is the size of sortedset, max value of `n` is `k` from input for i, num in enumerate(nums): ceiling_idx = ss.bisect_left(num) # index whose value is greater than or equal to `num` floor_idx = ceiling_idx - 1 # index whose value is smaller than `num` if ceiling_idx < n and abs(ss[ceiling_idx]-num) <= t: return True # check right neighbour if 0 <= floor_idx and abs(ss[floor_idx]-num) <= t: return True # check left neighbour ss.add(num) n += 1 if i - k >= 0: # maintain the size of sortedset by finding &amp; removing the earliest number in sortedset ss.remove(nums[i-k]) n -= 1 return False
contains-duplicate-iii
Python 3 | Official Solution in Python 3 | 2 Methods | Explanation
idontknoooo
16
2,600
contains duplicate iii
220
0.22
Hard
3,924
https://leetcode.com/problems/contains-duplicate-iii/discuss/825606/Python-3-or-Official-Solution-in-Python-3-or-2-Methods-or-Explanation
class Solution: def containsNearbyAlmostDuplicate(self, nums: List[int], k: int, t: int) -> bool: if not nums or t < 0: return False min_val = min(nums) bucket_key = lambda x: (x-min_val) // (t+1) # A lambda function generate buckey key given a value d = collections.defaultdict(lambda: sys.maxsize) # A bucket simulated with defaultdict for i, num in enumerate(nums): key = bucket_key(num) # key for current number `num` for nei in [d[key-1], d[key], d[key+1]]: # check left bucket, current bucket and right bucket if abs(nei - num) <= t: return True d[key] = num if i >= k: d.pop(bucket_key(nums[i-k])) # maintain a size of `k` return False
contains-duplicate-iii
Python 3 | Official Solution in Python 3 | 2 Methods | Explanation
idontknoooo
16
2,600
contains duplicate iii
220
0.22
Hard
3,925
https://leetcode.com/problems/contains-duplicate-iii/discuss/2298891/Two-Python-Solutions%3A-Memory-Optimization-Speed-Optimization
class Solution: def containsNearbyAlmostDuplicate(self, nums: List[int], k: int, t: int) -> bool: if t == 0 and len(set(nums)) == len(nums): return False bucket = {} width = t + 1 for i, n in enumerate(nums): bucket_i = n // width if bucket_i in bucket: return True elif bucket_i + 1 in bucket and abs(n - bucket[bucket_i + 1]) < width: return True elif bucket_i - 1 in bucket and abs(n - bucket[bucket_i - 1]) < width: return True bucket[bucket_i] = n if i >= k: del bucket[ nums[i-k] //width ] return False
contains-duplicate-iii
Two Python Solutions: Memory Optimization, Speed Optimization
zip_demons
3
417
contains duplicate iii
220
0.22
Hard
3,926
https://leetcode.com/problems/contains-duplicate-iii/discuss/748483/Python3-via-bucketing
class Solution: def containsDuplicate(self, nums: List[int]) -> bool: seen = set() for x in nums: if x in seen: return True seen.add(x) return False
contains-duplicate-iii
[Python3] via bucketing
ye15
2
364
contains duplicate iii
220
0.22
Hard
3,927
https://leetcode.com/problems/contains-duplicate-iii/discuss/748483/Python3-via-bucketing
class Solution: def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool: seen = {} for i, x in enumerate(nums): if x in seen and i - seen[x] <= k: return True seen[x] = i return False
contains-duplicate-iii
[Python3] via bucketing
ye15
2
364
contains duplicate iii
220
0.22
Hard
3,928
https://leetcode.com/problems/contains-duplicate-iii/discuss/748483/Python3-via-bucketing
class Solution: def containsNearbyAlmostDuplicate(self, nums: List[int], k: int, t: int) -> bool: if t < 0: return False # edge case seen = {} for i, x in enumerate(nums): bkt = x//(t+1) if bkt in seen and i - seen[bkt][0] <= k: return True if bkt-1 in seen and i - seen[bkt-1][0] <= k and abs(x - seen[bkt-1][1]) <= t: return True if bkt+1 in seen and i - seen[bkt+1][0] <= k and abs(x - seen[bkt+1][1]) <= t: return True seen[bkt] = (i, x) return False
contains-duplicate-iii
[Python3] via bucketing
ye15
2
364
contains duplicate iii
220
0.22
Hard
3,929
https://leetcode.com/problems/contains-duplicate-iii/discuss/2789561/python-oror-sliding-window-%2B-BST%3A-O(n*log(k))
class Solution: def containsNearbyAlmostDuplicate(self, nums: List[int], indexDiff: int, valueDiff: int) -> bool: """Sliding window + BST: O(N*log(indexDiff))""" bst = BinarySearchTree() for i in range(len(nums)): if i > 0: closest = bst.search_closest(nums[i]) if abs(nums[i] - closest) <= valueDiff: return True if i >= indexDiff: bst.delete(nums[i - indexDiff]) bst.insert(nums[i]) return False class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class BinarySearchTree: def __init__(self): self.root = None def search_closest(self, val: int) -> int: if not self.root: return None closest = self.root.val node = self.root while node: if abs(node.val - val) < abs(closest - val): closest = node.val if node.val == val: break elif val < node.val: node = node.left else: node = node.right return closest def insert(self, val: int): if not self.root: self.root = TreeNode(val) return node = self.root while node: if val < node.val: if not node.left: node.left = TreeNode(val) break else: node = node.left else: if not node.right: node.right = TreeNode(val) break else: node = node.right def delete(self, key: int): def __deleteNode(root, key): if not root: return None if root.val == key: if not root.right: return root.left if not root.left: return root.right temp = root.right while temp.left: temp = temp.left root.val = temp.val root.right = __deleteNode(root.right, root.val) elif key < root.val: root.left = __deleteNode(root.left, key) else: root.right = __deleteNode(root.right, key) return root self.root = __deleteNode(self.root, key)
contains-duplicate-iii
python || sliding window + BST: O(n*log(k))
ivan-luchko
0
7
contains duplicate iii
220
0.22
Hard
3,930
https://leetcode.com/problems/contains-duplicate-iii/discuss/505508/Python3-simple-solution-faster-than-99.85
class Solution: def containsNearbyAlmostDuplicate(self, nums: List[int], k: int, t: int) -> bool: if not nums or k<1 or t<0 or (t==0 and len(nums)==len(set(nums))): return False for i in range(len(nums)): for j in range(1,k+1): if (i+j)>=len(nums): break if abs(nums[i+j]-nums[i])<=t: return True return False
contains-duplicate-iii
Python3 simple solution, faster than 99.85%
jb07
0
364
contains duplicate iii
220
0.22
Hard
3,931
https://leetcode.com/problems/maximal-square/discuss/1632285/Python-1D-Array-DP-Optimisation-Process-Explained
class Solution: def maximalSquare(self, matrix: List[List[str]]) -> int: result = 0 for i in range(len(matrix)): for j in range(len(matrix[0])): curr = 0 # current length of the square at (i, j) flag = True # indicates if there still exists a valid square while flag: for k in range(curr+1): # check outer border of elements for '1's. """ eg curr = 2, ie a valid 2x2 square exists 'O' is valid, check 'X': X X X X O O X O O """ if i < curr or j < curr or \ matrix[i-curr][j-k] == '0' or \ matrix[i-k][j-curr] == '0': flag = False break curr += flag if curr > result: # new maximum length of square obtained result = curr return result*result # area = length x length
maximal-square
[Python] 1D-Array DP - Optimisation Process Explained
zayne-siew
9
610
maximal square
221
0.446
Medium
3,932
https://leetcode.com/problems/maximal-square/discuss/1632285/Python-1D-Array-DP-Optimisation-Process-Explained
class Solution: def maximalSquare(self, matrix: List[List[str]]) -> int: m, n = len(matrix), len(matrix[0]) result = 0 dp = [[0]*n for _ in range(m)] # dp[x][y] is the length of the maximal square at (x, y) for i in range(m): for j in range(n): if matrix[i][j] == '1': # ensure this condition first # perform computation, mind border restrictions dp[i][j] = min(dp[i-1][j] if i > 0 else 0, dp[i][j-1] if j > 0 else 0, dp[i-1][j-1] if i > 0 and j > 0 else 0) + 1 if dp[i][j] > result: result = dp[i][j] return result*result
maximal-square
[Python] 1D-Array DP - Optimisation Process Explained
zayne-siew
9
610
maximal square
221
0.446
Medium
3,933
https://leetcode.com/problems/maximal-square/discuss/1632285/Python-1D-Array-DP-Optimisation-Process-Explained
class Solution: def maximalSquare(self, matrix: List[List[str]]) -> int: m, n = len(matrix), len(matrix[0]) result = 0 prev, curr = [0]*n, [0]*n for i in range(m): for j in range(n): if matrix[i][j] == '1': curr[j] = min(curr[j-1] if j > 0 else 0, prev[j-1] if j > 0 else 0, prev[j]) + 1 if curr[j] > result: result = curr[j] prev, curr = curr, [0]*n return result*result
maximal-square
[Python] 1D-Array DP - Optimisation Process Explained
zayne-siew
9
610
maximal square
221
0.446
Medium
3,934
https://leetcode.com/problems/maximal-square/discuss/1632285/Python-1D-Array-DP-Optimisation-Process-Explained
class Solution: def maximalSquare(self, matrix: List[List[str]]) -> int: m, n = len(matrix), len(matrix[0]) result = 0 prev, curr = [0]*n, [0]*n for i in range(m): for j in range(n): if matrix[i][j] == '1': curr[j] = min(curr[j-1] if j > 0 else 0, prev[j-1] if j > 0 else 0, prev[j]) + 1 else: curr[j] = 0 # reset curr[j] if curr[j] > result: result = curr[j] prev, curr = curr, prev return result*result
maximal-square
[Python] 1D-Array DP - Optimisation Process Explained
zayne-siew
9
610
maximal square
221
0.446
Medium
3,935
https://leetcode.com/problems/maximal-square/discuss/1632285/Python-1D-Array-DP-Optimisation-Process-Explained
class Solution: def maximalSquare(self, matrix: List[List[str]]) -> int: m, n = len(matrix), len(matrix[0]) result = 0 dp = [[0]*n for _ in range(2)] # 2-rowed dp array for i in range(m): for j in range(n): # i%2 (or i&amp;1) alternates between dp[0] and dp[1] dp[i%2][j] = 0 if matrix[i][j] == '0' else \ (min(dp[i%2][j-1] if j > 0 else 0, dp[1-i%2][j-1] if j > 0 else 0, dp[1-i%2][j]) + 1) result = dp[i%2][j] if dp[i%2][j] > result else result return result*result
maximal-square
[Python] 1D-Array DP - Optimisation Process Explained
zayne-siew
9
610
maximal square
221
0.446
Medium
3,936
https://leetcode.com/problems/maximal-square/discuss/1632285/Python-1D-Array-DP-Optimisation-Process-Explained
class Solution: def maximalSquare(self, matrix: List[List[str]]) -> int: m, n, result = len(matrix), len(matrix[0]), 0 dp = [0]*n # 1D array for i in range(m): prev = 0 # stores dp[i-1][j-1] for j in range(n): dp[j], prev = 0 if matrix[i][j] == '0' else \ (min(dp[j], # dp[j] -> dp[i-1][j] dp[j-1] if j > 0 else 0, # dp[j-1] -> dp[i][j-1] prev) # prev -> dp[i-1][j-1] + 1), dp[j] result = dp[j] if dp[j] > result else result return result*result
maximal-square
[Python] 1D-Array DP - Optimisation Process Explained
zayne-siew
9
610
maximal square
221
0.446
Medium
3,937
https://leetcode.com/problems/maximal-square/discuss/518951/Python-O(m*n)-sol.-by-DP.-with-Demo
class Solution: def maximalSquare(self, matrix: List[List[str]]) -> int: if not matrix: return 0 dp_table = [ [ int(x) for x in row] for row in matrix] h, w = len(matrix), len(matrix[0]) max_edge_of_square = 0 for y in range(h): for x in range(w): if y and x and int(matrix[y][x]): dp_table[y][x] = 1 + min( dp_table[y][x-1], dp_table[y-1][x-1], dp_table[y-1][x] ) max_edge_of_square = max(max_edge_of_square, dp_table[y][x]) return max_edge_of_square*max_edge_of_square
maximal-square
Python O(m*n) sol. by DP. [ with Demo ]
brianchiang_tw
7
753
maximal square
221
0.446
Medium
3,938
https://leetcode.com/problems/maximal-square/discuss/518951/Python-O(m*n)-sol.-by-DP.-with-Demo
class Solution: def maximalSquare(self, matrix: List[List[str]]) -> int: if not matrix: return 0 h, w = len(matrix), len(matrix[0]) # in-place update dp_table = matrix max_edge_length = 0 for x in range(w): matrix[0][x] = int( matrix[0][x] ) for y in range(h): matrix[y][0] = int( matrix[y][0] ) for y in range(h): for x in range(w): if y > 0 and x > 0: if matrix[y][x] == '1': matrix[y][x] = 1 + min( matrix[y][x-1], matrix[y-1][x-1], matrix[y-1][x]) else: matrix[y][x] = 0 max_edge_length = max(max_edge_length, matrix[y][x]) return max_edge_length*max_edge_length
maximal-square
Python O(m*n) sol. by DP. [ with Demo ]
brianchiang_tw
7
753
maximal square
221
0.446
Medium
3,939
https://leetcode.com/problems/maximal-square/discuss/2826866/in-M*N-time
class Solution: def maximalSquare(self, matrix: List[List[str]]) -> int: mx=0 for i in range(len(matrix)): for j in range(len(matrix[0])): if(matrix[i][j]=="0"): matrix[i][j]=0 else: if(i==0 or j==0): matrix[i][j]=1 else: matrix[i][j]=min(matrix[i][j-1],matrix[i-1][j],matrix[i-1][j-1])+1 mx=max(mx,matrix[i][j]) # print(matrix[i]) # print(matrix) return mx**2
maximal-square
in M*N time
droj
5
51
maximal square
221
0.446
Medium
3,940
https://leetcode.com/problems/maximal-square/discuss/944753/python-DP-probably-without-using-extra-space
class Solution: def maximalSquare(self, matrix: List[List[str]]) -> int: if len(matrix) < 1: return 0 rows,cols,max_size = len(matrix),len(matrix[0]),0 for row in range(rows): for col in range(cols): matrix[row][col] = int(matrix[row][col]) if matrix[row][col] >= 1: if row-1 >= 0 and col-1 >= 0: matrix[row][col] = min(matrix[row-1][col],matrix[row][col-1],matrix[row-1][col-1])+1 max_size = max(max_size,matrix[row][col]) return max_size*max_size
maximal-square
[python] DP probably without using extra space
Rakesh301
3
436
maximal square
221
0.446
Medium
3,941
https://leetcode.com/problems/maximal-square/discuss/1632249/2D-Range-sum-and-binary-search-time%3A-O(R*C*log(min(R-C)))
class Solution: def maximalSquare(self, matrix: List[List[str]]) -> int: def exist(k): for i in range(R): if i + k - 1 >= R: break for j in range(C): if j + k - 1 >= C: break a = sum_matrix[i + k - 1][j + k - 1] b = sum_matrix[i - 1][j - 1] if i > 0 and j > 0 else 0 c = sum_matrix[i - 1][j + k - 1] if i > 0 else 0 d = sum_matrix[i + k - 1][j - 1] if j > 0 else 0 if a + b - c - d == k ** 2: return True return False R, C = len(matrix), len(matrix[0]) #create sum_matrix sum_matrix = [[0 for _ in range(C)] for _ in range(R)] sum_matrix[0][0] = (matrix[0][0] == '1') for j in range(1, C): sum_matrix[0][j] = sum_matrix[0][j - 1] + (matrix[0][j] == '1') for i in range(1, R): sum_matrix[i][0] = sum_matrix[i - 1][0] + (matrix[i][0] == '1') for i in range(1, R): for j in range(1, C): sum_matrix[i][j] = sum_matrix[i - 1][j] + sum_matrix[i][j - 1] - sum_matrix[i - 1][j - 1] + (matrix[i][j] == '1') #binary search l, r = 0, min(R, C) while l < r: mid = (l + r + 1) // 2 if exist(mid): l = mid else: r = mid - 1 return l ** 2
maximal-square
2D-Range sum & binary search, time: O(R*C*log(min(R, C)))
kryuki
2
66
maximal square
221
0.446
Medium
3,942
https://leetcode.com/problems/maximal-square/discuss/600192/Python3-dp
class Solution: def maximalSquare(self, matrix: List[List[str]]) -> int: @lru_cache(None) def fn(i, j): """Return length of max square ending at (i, j)""" if i < 0 or j < 0 or matrix[i][j] == "0": return 0 return 1 + min(fn(i-1, j), fn(i-1, j-1), fn(i, j-1)) return max((fn(i, j) for i in range(len(matrix)) for j in range(len(matrix[0]))), default=0)**2
maximal-square
[Python3] dp
ye15
2
130
maximal square
221
0.446
Medium
3,943
https://leetcode.com/problems/maximal-square/discuss/600192/Python3-dp
class Solution: def maximalSquare(self, matrix: List[List[str]]) -> int: ans = 0 for i in range(len(matrix)): for j in range(len(matrix[0])): matrix[i][j] = int(matrix[i][j]) if i > 0 and j > 0 and matrix[i][j]: matrix[i][j] = 1 + min(matrix[i-1][j], matrix[i-1][j-1], matrix[i][j-1]) ans = max(ans, matrix[i][j]) return ans*ans #area
maximal-square
[Python3] dp
ye15
2
130
maximal square
221
0.446
Medium
3,944
https://leetcode.com/problems/maximal-square/discuss/600192/Python3-dp
class Solution: def maximalSquare(self, matrix: List[List[str]]) -> int: m, n = len(matrix), len(matrix[0]) dp = [[0]*n for _ in range(m)] for i in range(m): for j in range(n): if matrix[i][j] == "1": if i == 0 or j == 0: dp[i][j] = 1 else: dp[i][j] = 1 + min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]) return max(map(max, dp))**2
maximal-square
[Python3] dp
ye15
2
130
maximal square
221
0.446
Medium
3,945
https://leetcode.com/problems/maximal-square/discuss/600192/Python3-dp
class Solution: def maximalSquare(self, matrix: List[List[str]]) -> int: m, n = len(matrix), len(matrix[0]) ans = 0 dp = [0]*n tmp = [0]*n for i in range(m): tmp, dp = dp, tmp for j in range(n): if matrix[i][j] == "1": if i == 0 or j == 0: dp[j] = 1 else: dp[j] = 1 + min(dp[j-1], tmp[j-1], tmp[j]) else: dp[j] = 0 ans = max(ans, dp[j]) return ans*ans
maximal-square
[Python3] dp
ye15
2
130
maximal square
221
0.446
Medium
3,946
https://leetcode.com/problems/maximal-square/discuss/465001/Python3-simple-solution-using-dynamic-programming
class Solution: def maximalSquare(self, matrix: List[List[str]]) -> int: max_val = 0 for i in range(len(matrix)): for j in range(len(matrix[i])): matrix[i][j]=int(matrix[i][j]) if matrix[i][j] and i and j: matrix[i][j] = min(matrix[i-1][j],matrix[i][j-1],matrix[i-1][j-1])+1 max_val = max(max_val,matrix[i][j]) return len(matrix) and max_val ** 2
maximal-square
Python3 simple solution using dynamic programming
jb07
2
191
maximal square
221
0.446
Medium
3,947
https://leetcode.com/problems/maximal-square/discuss/1538349/Python-oror-Easy-Solution
class Solution: def maximalSquare(self, lst: List[List[str]]) -> int: n, m = len(lst), len(lst[0]) dp = [[0 for j in range(m)] for i in range(n)] maxi = 0 for i in range(n - 1, -1, -1): for j in range(m - 1, -1, -1): if lst[i][j] == "0": dp[i][j] = 0 elif i == n - 1: dp[i][j] = int(lst[i][j]) elif j == m - 1: dp[i][j] = int(lst[i][j]) else: dp[i][j] = 1 + min(dp[i + 1][j + 1], dp[i + 1][j], dp[i][j + 1]) if dp[i][j] > maxi: maxi = dp[i][j] return maxi * maxi
maximal-square
Python || Easy Solution
naveenrathore
1
301
maximal square
221
0.446
Medium
3,948
https://leetcode.com/problems/maximal-square/discuss/633057/Idiomatic-Python-Solution-with-DP-O(mn)-Time-O(mn)-Space
class Solution: def maximalSquare(self, matrix: List[List[str]]) -> int: if not matrix: return 0 dp = [[0] * len(matrix[0]) for _ in range(len(matrix))] max_side = 0 for i, row in enumerate(matrix): for j, val in enumerate(row): if val == '0': continue left = 0 if j-1 >= 0: left = dp[i][j-1] top = 0 if i-1 >= 0: top = dp[i-1][j] diag = 0 if i-1 >= 0 and j-1 >= 0: # is this check redundant? diag = dp[i-1][j-1] dp[i][j] = min(left, top, diag) + 1 max_side = max(max_side, dp[i][j]) return max_side * max_side
maximal-square
Idiomatic Python Solution with DP - O(mn) Time, O(mn) Space
schedutron
1
160
maximal square
221
0.446
Medium
3,949
https://leetcode.com/problems/maximal-square/discuss/442360/Python-3-(DP)-(five-lines)-(beats-98)
class Solution: def maximalSquare(self, G: List[List[str]]) -> int: if not G: return 0 M, N = len(G) + 1, len(G[0]) + 1 G = [[0]*N] + [[0,*G[i]] for i in range(M-1)] for i,j in itertools.product(range(1,M),range(1,N)): G[i][j] = int(G[i][j]) and 1 + min(G[i-1][j],G[i][j-1],G[i-1][j-1]) return max(map(max,G))**2 - Junaid Mansuri - Chicago, IL
maximal-square
Python 3 (DP) (five lines) (beats 98%)
junaidmansuri
1
419
maximal square
221
0.446
Medium
3,950
https://leetcode.com/problems/maximal-square/discuss/439087/One-line-change-from-the-85.-Maximal-Rectangle-solution
class Solution: def maximalSquare(self, matrix: List[List[str]]) -> int: if not matrix: return 0 n = len(matrix[0]) prev = [0] * n ans = 0 for row in matrix: curr = [e + 1 if cell == '1' else 0 for e, cell in zip(prev, row)] curr.append(0) stack = [(0, -1)] for i, e in enumerate(curr): while e < stack[-1][0]: length, _ = stack.pop() ans = max(ans, min(length, i - stack[-1][1] - 1) ** 2) stack.append((e, i)) curr.pop() prev = curr return ans
maximal-square
One line change from the 85. Maximal Rectangle solution
chuan-chih
1
172
maximal square
221
0.446
Medium
3,951
https://leetcode.com/problems/maximal-square/discuss/2841585/MaximalSquare-of-1
class Solution: def maximalSquare(self, matrix: List[List[str]]) -> int: row_len = len(matrix) col_len = len(matrix[0]) matrix2 = [[0]*(col_len) for _ in matrix] max_one = 0 for i in range(row_len): for j in range(col_len): if matrix[i][j] == "1": if 0 in [i, j]: matrix2[i][j] = 1 max_one = max(max_one, 1) else: matrix2[i][j] = min(matrix2[i-1][j-1], matrix2[i-1][j], matrix2[i][j-1]) + 1 max_one = max(max_one, matrix2[i][j]) max_square = max_one**2 return max_square
maximal-square
MaximalSquare of 1
dexck7770
0
3
maximal square
221
0.446
Medium
3,952
https://leetcode.com/problems/maximal-square/discuss/2840578/**NO-NEED-FOR-DP**-O(MN)-solution-or-sliding-window.-Easiest-solution-yet.
class Solution: def maximalSquare(self, matrix: List[List[str]]) -> int: heights = {len(matrix[0]): float('-inf')} max_square = float('-inf') for row in matrix: for i, el in enumerate(row): heights[i] = heights.setdefault(i, 0) + 1 if el == "1" else 0 # sliding window minimum stack = collections.deque([(heights[0], 0)]) lo, hi = 0, 0 while hi < len(row): width = hi - lo + 1 min_height = stack[0][0] if heights[hi] == 0: lo = hi = hi + 1 stack = collections.deque([(heights[hi], hi)]) elif width <= min_height: max_square = max(max_square, width ** 2) hi += 1 while stack and stack[-1][0] > heights[hi]: stack.pop() stack.append((heights[hi], hi)) else: if stack[0][1] == lo: stack.popleft() lo += 1 return 0 if max_square == float('-inf') else max_square
maximal-square
**NO NEED FOR DP** O(MN) solution | sliding window. Easiest solution yet.
DijkstrianProtoge
0
8
maximal square
221
0.446
Medium
3,953
https://leetcode.com/problems/maximal-square/discuss/2819395/python3-soln
class Solution: def maximalSquare(self, matrix: List[List[str]]) -> int: dp = [[0]*len(matrix[0]) for _ in range(len(matrix))] maxl = -1 for i in range(len(matrix)): for j in range(len(matrix[0])): if matrix[i][j] == '1': dp[i][j] = 1 if (i-1) >= 0 and (j-1) >= 0: dp[i][j] += min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]) else: dp[i][j] = 0 maxl = max(dp[i][j], maxl) return maxl*maxl
maximal-square
python3 soln
misterman1234
0
7
maximal square
221
0.446
Medium
3,954
https://leetcode.com/problems/maximal-square/discuss/2814174/O(n)-space-detailed-explanation-with-intuition.
class Solution: def maximalSquare(self, matrix: List[List[str]]) -> int: ''' we pad the matrix so that we will always have an empty monotonic stack. ''' for rw in range(len(matrix)): matrix[rw].append("0") height = [0] * len(matrix[0]) max_area = 0 for rw, row in enumerate(matrix): stack = [-1] for col, val in enumerate(row): height[col] = 0 if not int(val) else height[col] + 1 while stack and height[stack[-1]] > height[col]: prev_col = stack.pop() right= col - prev_col left = prev_col - stack[-1] - 1 width = right + left area = min(width,height[prev_col]) ** 2 max_area = max(area, max_area) stack.append(col) return max_area
maximal-square
O(n) space detailed explanation with intuition.
Henok2011
0
7
maximal square
221
0.446
Medium
3,955
https://leetcode.com/problems/maximal-square/discuss/2726461/Python3-Simple-2D-DP-(Bottom-Up)
class Solution: def maximalSquare(self, matrix: List[List[str]]) -> int: ROWS, COLS = len(matrix), len(matrix[0]) dp = [[0] * (COLS+1) for _ in range(ROWS+1)] res = 0 for r in range(ROWS-1, -1, -1): for c in range(COLS-1, -1, -1): if int(matrix[r][c]) != 0: dp[r][c] = int(matrix[r][c]) + min(dp[r+1][c], dp[r][c+1], dp[r+1][c+1]) res = max(res, dp[r][c]) return res**2
maximal-square
Python3 Simple 2D DP (Bottom-Up)
jonathanbrophy47
0
12
maximal square
221
0.446
Medium
3,956
https://leetcode.com/problems/maximal-square/discuss/2718229/Python-or-2-d-dynamic-programming-solution
class Solution: def maximalSquare(self, mat: List[List[str]]) -> int: m, n = len(mat[0]), len(mat) dp = [[0 for _ in range(m)] for _ in range(n)] ans = 0 # Initialize dp matrix with values from mat for i in range(m): dp[0][i] = int(mat[0][i]) ans = max(ans, dp[0][i]) for j in range(n): dp[j][0] = int(mat[j][0]) ans = max(ans, dp[j][0]) for i in range(1, n): for j in range(1, m): # Get minimum number from surrounding cell and calculate value for dp-cell if mat[i][j] != "0": dp[i][j] = min([dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1],]) + int(mat[i][j]) # Recalculate result after each step ans = max(ans, dp[i][j]**2) return ans
maximal-square
Python | 2-d dynamic programming solution
LordVader1
0
18
maximal square
221
0.446
Medium
3,957
https://leetcode.com/problems/maximal-square/discuss/2636784/Python-DP
class Solution: def maximalSquare(self, matrix: List[List[str]]) -> int: r = len(matrix) c = len(matrix[0]) dp = [[0]*(c+1) for _ in range(r+1)] mx = 0 for i in range(r): for j in range(c): if matrix[i][j]!='0': dp[i+1][j+1] = min(dp[i][j], dp[i][j+1], dp[i+1][j]) + 1 mx = max(mx, int(dp[i+1][j+1])) return int(mx)**2
maximal-square
Python - DP
lokeshsenthilkumar
0
20
maximal square
221
0.446
Medium
3,958
https://leetcode.com/problems/maximal-square/discuss/2069194/Python-or-DP
class Solution: def maximalSquare(self, ma: List[List[str]]) -> int: n = len(ma) m = len(ma[0]) t = [[0 for i in range(m)]for j in range(n)] ans = 0 for i in range(n): for j in range(m): if i==0 or j==0: if ma[i][j] == "1": t[i][j] = 1 else: if ma[i][j] == "1": t[i][j] = 1+min(t[i-1][j],t[i-1][j-1],t[i][j-1]) ans = max(ans,(t[i][j])**2) return ans
maximal-square
Python | DP
Shivamk09
0
61
maximal square
221
0.446
Medium
3,959
https://leetcode.com/problems/maximal-square/discuss/2027833/python3-or-DP-or-Faster-than-95.62...
class Solution: def maximalSquare(self, matrix: List[List[str]]) -> int: m, n = len(matrix), len(matrix[0]) dp = [int(i) for i in matrix[0]] res = max(dp) for i in range(1, m): curr = dp[:] dp[0] = int(matrix[i][0]) for j in range(1, n): if matrix[i][j] == "0": dp[j] = 0 else: dp[j] = min((curr[j], curr[j-1], dp[j-1])) + 1 res = max(res, max(dp)) return res ** 2
maximal-square
python3 | DP | Faster than 95.62%...
anels
0
72
maximal square
221
0.446
Medium
3,960
https://leetcode.com/problems/maximal-square/discuss/1836298/70-faster-and-memory-efficient-or-DP-or-O(m*n)-or-easy-solution
class Solution: def maximalSquare(self, matrix: List[List[str]]) -> int: rows, cols = len(matrix), len(matrix[0]) # dp: look up table dp = [0] * (rows+1) for i in range(len(dp)): dp[i] = [0] * (cols+1) maxx = 0 # max length for i in range(rows): for j in range(cols): if matrix[i][j] == '1': left = dp[i][j-1] up = dp[i-1][j] diag = dp[i-1][j-1] dp[i][j] = 1 + min(left, up, diag) maxx = max(dp[i][j], maxx) return(maxx ** 2)
maximal-square
70% faster and memory efficient | DP | O(m*n) | easy solution
aamir1412
0
56
maximal square
221
0.446
Medium
3,961
https://leetcode.com/problems/maximal-square/discuss/1804796/Python-easy-to-read-and-understand-or-DP
class Solution: def maximalSquare(self, matrix: List[List[str]]) -> int: m, n = len(matrix), len(matrix[0]) matrix = [[int(matrix[i][j]) for j in range(n)] for i in range(m)] t = [] for val in matrix: t.append(val) for i in range(m-2, -1, -1): for j in range(n-2, -1, -1): if t[i][j] == 1: t[i][j] = min(t[i+1][j], t[i][j+1], t[i+1][j+1]) + 1 max_val = 0 for val in t: max_val = max(max_val, max(val)) return max_val**2
maximal-square
Python easy to read and understand | DP
sanial2001
0
135
maximal square
221
0.446
Medium
3,962
https://leetcode.com/problems/maximal-square/discuss/1755384/Java-Python3-Simple-DP-Solution-(Bottom-Up)
class Solution: def maximalSquare(self, matrix: List[List[str]]) -> int: m, n = len(matrix), len(matrix[0]) dp = [[0]*(n+1) for _ in range(m+1)] maxlen = 0 for i in range(1, m+1): for j in range(1, n+1): if matrix[i-1][j-1] == '1': dp[i][j] = min(dp[i-1][j-1], dp[i-1][j], dp[i][j-1]) + 1 maxlen = max(maxlen, dp[i][j]) return maxlen*maxlen
maximal-square
βœ… [Java / Python3] Simple DP Solution (Bottom-Up)
JawadNoor
0
117
maximal square
221
0.446
Medium
3,963
https://leetcode.com/problems/maximal-square/discuss/1632597/Python3-DP-solution
class Solution: def maximalSquare(self, matrix: List[List[str]]) -> int: dp = [[0 for _ in range(len(matrix[0]) + 1)] for _ in range(len(matrix) + 1)] max_sq_len = 0 for i in range(len(matrix)): for j in range(len(matrix[0])): if matrix[i][j] == '1': dp[i + 1][j + 1] = min(dp[i + 1][j], dp[i][j + 1], dp[i][j]) + 1 max_sq_len = max(max_sq_len, dp[i + 1][j + 1]) return max_sq_len * max_sq_len
maximal-square
[Python3] DP solution
maosipov11
0
37
maximal square
221
0.446
Medium
3,964
https://leetcode.com/problems/maximal-square/discuss/1632106/Python3-DP-Explained
class Solution: def maximalSquare(self, m: List[List[str]]) -> int: rows, cols = len(m), len(m[0]) dp = [[0] * cols for i in range(rows)] for row in range(rows): combo = 0 for col in range(cols): if m[row][col] == "1": combo += 1 else: combo = 0 dp[row][col] = combo res = 0 for row in reversed(range(rows)): for col in reversed(range(cols)): if m[row][col] == "0": continue square, offset, side = 0, 0, float("inf") while row - offset > -1: side = min(side, dp[row - offset][col]) if side < offset + 1: break square = (offset + 1) ** 2 offset += 1 res = max(res, square) return res
maximal-square
βœ”οΈ[Python3] DP, Explained
artod
0
49
maximal square
221
0.446
Medium
3,965
https://leetcode.com/problems/maximal-square/discuss/1458252/PyPy3-Solution-using-only-for-loops-w-comments
class Solution: def maximalSquare(self, matrix: List[List[str]]) -> int: # Init m = len(matrix) n = len(matrix[0]) max_len = 0 # Convert matrix value of string to int for row in range(m): for col in range(n): matrix[row][col] = int(matrix[row][col]) # Scan first row for col in range(n): max_len = max(max_len, matrix[0][col]) # Scan first column for row in range(m): max_len = max(max_len, matrix[row][0]) # For each row starting from second row for i in range(1,m): # For each col starting from second column for j in range(1,n): # If the current element is non-zero if matrix[i][j]: # If all three of it's adjacent elements are non-zero # Three elements are: # a) element in the previous row "[i-1][j]" # b) element in the previous column "[i][j-1]" # c) element in previous diagonal "[i-1][j-1]" if matrix[i-1][j] and matrix[i][j-1] and matrix[i-1][j-1]: # Get the minimum of all three adjacent elements and add one to it # This updates length of the element w.r.t how many adjacent ones # are available in the original matrix matrix[i][j] = min(matrix[i-1][j], matrix[i][j-1], matrix[i-1][j-1]) + 1 # Calc max len w.r.t the updated length of the current element max_len = max(max_len, matrix[i][j]) return max_len**2 # Area of a square of length "l" is l*l = l^2
maximal-square
[Py/Py3] Solution using only for loops w/ comments
ssshukla26
0
242
maximal square
221
0.446
Medium
3,966
https://leetcode.com/problems/maximal-square/discuss/1332034/Python-DP-solution-using-tabulation-beats-70
class Solution: def maximalSquare(self, matrix: List[List[str]]) -> int: #initiate a DP matrix DP = [] N = len(matrix) for row in range(N+1): DP.append([0]*(len(matrix[0])+1)) currentMax = 0 #meat for row in range(N): for col in range(len(matrix[0])): if matrix[row][col] == "0": continue else: DP[row][col] = min(DP[row-1][col], DP[row][col-1], DP[row-1][col-1]) + 1 currentMax = max(DP[row][col], currentMax) return currentMax*currentMax
maximal-square
Python DP solution using tabulation beats 70%
dee7
0
232
maximal square
221
0.446
Medium
3,967
https://leetcode.com/problems/maximal-square/discuss/1082581/AC-Python
class Solution: def maximalSquare(self, matrix: List[List[str]]) -> int: def square_sum(i, j, size): result = 0 for row in range(i, i+size): try: result += sum([1 if x == "1" else 0 for x in matrix[row][j:j+size]]) except: return 0 return result def expand(i, j): best = 0 size = 1 expected_sum = 1 while True: result = square_sum(i, j, size) if result != expected_sum: return best best = result size += 1 expected_sum = size ** 2 best = 0 for i in range(len(matrix)): for j in range(len(matrix[0])): best = max(best, expand(i, j)) return best
maximal-square
AC Python
dev-josh
0
138
maximal square
221
0.446
Medium
3,968
https://leetcode.com/problems/maximal-square/discuss/1082581/AC-Python
class Solution: def maximalSquare(self, matrix: List[List[str]]) -> int: R, C = len(matrix), len(matrix[0]) dp = [[0]*(C+1) for _ in range(R+1)] for r in range(R): for c in range(C): if matrix[r][c] == '1': dp[r+1][c+1] = min(dp[r][c+1], dp[r+1][c], dp[r][c]) + 1 return max([max(row) for row in dp]) ** 2
maximal-square
AC Python
dev-josh
0
138
maximal square
221
0.446
Medium
3,969
https://leetcode.com/problems/maximal-square/discuss/1077012/classic-DP-python-and-brute-force
class Solution: def maximalSquare(self, matrix: List[List[str]]) -> int: row_len, col_len = len(matrix), len(matrix[0]) max_sum = 0 dp = [[0]* (col_len+1) for _ in range(row_len + 1)] for row in range(row_len): for col in range(col_len): if matrix[row][col] == "1": dp[row][col] = min(dp[row-1][col], dp[row][col-1], dp[row-1][col-1]) + 1 max_sum = max(max_sum ,dp[row][col]) return max_sum * max_sum
maximal-square
classic DP python and brute force
xavloc
0
104
maximal square
221
0.446
Medium
3,970
https://leetcode.com/problems/maximal-square/discuss/739039/Python-DFS%2Bmemoization
class Solution: def maximalSquare(self, matrix: List[List[str]]) -> int: if not matrix:return 0 if len(matrix)==1:return int("1" in matrix[0]) row,col=len(matrix),len(matrix[0]) viewed=[[False]*col for _ in range(row)] ans=0 def dfs(matrix:List[List[str]],row:int,col:int)->int: viewed[row][col]=True if matrix[row][col]=="0":return 0 ans=1 itr=1 while (row+itr<len(matrix)) and (col+itr<len(matrix[0])): if helper(matrix,row,col,itr+1): ans+=1 itr+=1 else:break return ans**2 def helper(matrix:List[List[str]],row:int,col:int,curr:int)->bool: if row+curr>len(matrix):return False target=True for i in range(curr): if matrix[row+curr-1][col+i]=="0": target=False break if matrix[row+i][col+curr-1]=="0": target=False break if target: for i in range(curr): viewed[row][i]=True viewed[i][col]=True return target for i in range(row): for j in range(col): #print([i,j]) #print(ans) if viewed[i][j]:continue ans=max(ans,dfs(matrix,i,j)) #print(dfs(matrix,2,1)) return ans
maximal-square
Python DFS+memoization
752937603
0
276
maximal square
221
0.446
Medium
3,971
https://leetcode.com/problems/maximal-square/discuss/503087/Easy-understand-dp-Python-3
class Solution: def maximalSquare(self, matrix: List[List[str]]) -> int: #dp[i, j] is the max edge length of the square with i, j as right-bottom point if not matrix: return 0 num_rows = len(matrix) num_cols = len(matrix[0]) dp = [[0 for i in range(num_cols+1)] for j in range(num_rows+1)] area = 0 for i in range(1, num_rows+1): for j in range(1, num_cols+1): if matrix[i-1][j-1] == '1': dp[i][j] = min(dp[i-1][j-1], dp[i-1][j], dp[i][j-1])+1 area = max(area, dp[i][j]*dp[i][j]) return area
maximal-square
Easy understand dp Python 3
Liowen
0
218
maximal square
221
0.446
Medium
3,972
https://leetcode.com/problems/maximal-square/discuss/387196/Python-Solution-(DP)
class Solution: def maximalSquare(self, matrix: List[List[str]]) -> int: if not matrix: return 0 m, n = len(matrix), len(matrix[0]) dp = [[0 for _ in range(n)] for _ in range(m)] dp[0][0] = int(matrix[0][0]) max_log = dp[0][0] for i in range(1, m): dp[i][0] = int(matrix[i][0]) max_log = max(max_log, dp[i][0]) for j in range(1, n): dp[0][j] = int(matrix[0][j]) max_log = max(max_log, dp[0][j]) for i in range(1,m): for j in range(1,n): if matrix[i][j] != '0': dp[i][j] = min(dp[i-1][j], dp[i-1][j-1], dp[i][j-1]) + 1 max_log = max(max_log, dp[i][j]) return max_log*max_log
maximal-square
Python Solution (DP)
FFurus
0
345
maximal square
221
0.446
Medium
3,973
https://leetcode.com/problems/maximal-square/discuss/359781/My-easy-to-understand-Python-Solution
class Solution: def maximalSquare(self, matrix: List[List[str]]) -> int: if len(matrix) == 0: return 0 n = len(matrix[0]) up = [0]*n left = [0]*n dia = [0]*n square = [0]*n maxl = -1 for i in range(len(matrix)): presquare = [x for x in square] for j in range(n): if matrix[i][j]=='1': if i-1 >= 0 and matrix[i-1][j]=='1': up[j] = up[j] + 1 else: up[j] = 1 if i-1 >= 0 and j-1 >= 0 and matrix[i-1][j-1]=='1': dia[j] = dia[j-1] + 1 else: dia[j] = 1 if j-1 >= 0 and matrix[i][j-1]=='1': left[j] = left[j-1] + 1 else: left[j] = 1 square[j] = min(up[j],dia[j],left[j]) else: up[j] = dia[j] = left[j] = square[j] = 0 if j-1>=0: tt = square[j]-presquare[j-1] if tt > 1: square[j] = presquare[j-1]+1 maxl = max(square[j], maxl) return maxl*maxl
maximal-square
My easy to understand Python Solution
des_jasmine
0
342
maximal square
221
0.446
Medium
3,974
https://leetcode.com/problems/maximal-square/discuss/432601/Not-sure-if-anyone-else-has-come-up-with-something-like-this
class Solution: def maximalSquare(self, matrix: List[List[str]]) -> int: for y, row in enumerate(matrix): count_x = 1 for x, val in enumerate(row): if val is '1': matrix[y][x] = count_x count_x += 1 else: matrix[y][x] = 0 count_x = 1 # transpose best = 0 matrix = list(zip(*matrix)) popper = list() for i in range(10000): flag = False for j, col in enumerate(matrix): count = 0 for val in col: if val > i: count += 1 if count > i: best = i + 1 flag = True break else: count = 0 if flag: break else: popper.append(j) if flag: matrix = [col for j, col in enumerate(matrix) if j not in popper] popper.clear() else: break return best ** 2
maximal-square
Not sure if anyone else has come up with something like this
SkookumChoocher
-1
128
maximal square
221
0.446
Medium
3,975
https://leetcode.com/problems/count-complete-tree-nodes/discuss/701577/PythonPython3-Count-Complete-Tree-Nodes
class Solution: def countNodes(self, root: TreeNode) -> int: if not root: return 0 return 1 + self.countNodes(root.left) + self.countNodes(root.right)
count-complete-tree-nodes
[Python/Python3] Count Complete Tree Nodes
newborncoder
4
336
count complete tree nodes
222
0.598
Medium
3,976
https://leetcode.com/problems/count-complete-tree-nodes/discuss/2816979/Python-Simple-Python-Solution-Using-Two-Approach-BFS-or-DFS
class Solution: def countNodes(self, root: Optional[TreeNode]) -> int: self.result = 0 def DFS(node): if node == None: return None self.result = self.result + 1 DFS(node.left) DFS(node.right) DFS(root) return self.result
count-complete-tree-nodes
[ Python ] βœ…βœ… Simple Python Solution Using Two Approach BFS | DFSπŸ₯³βœŒπŸ‘
ASHOK_KUMAR_MEGHVANSHI
3
55
count complete tree nodes
222
0.598
Medium
3,977
https://leetcode.com/problems/count-complete-tree-nodes/discuss/2816979/Python-Simple-Python-Solution-Using-Two-Approach-BFS-or-DFS
class Solution: def countNodes(self, root: Optional[TreeNode]) -> int: def BFS(node): if node == None: return 0 queue = [node] self.result = 0 while queue: current_node = queue.pop() self.result = self.result + 1 if current_node.left != None: queue.append(current_node.left) if current_node.right != None: queue.append(current_node.right) return self.result return BFS(root)
count-complete-tree-nodes
[ Python ] βœ…βœ… Simple Python Solution Using Two Approach BFS | DFSπŸ₯³βœŒπŸ‘
ASHOK_KUMAR_MEGHVANSHI
3
55
count complete tree nodes
222
0.598
Medium
3,978
https://leetcode.com/problems/count-complete-tree-nodes/discuss/2813529/Two-Methods-or-Easy-to-Understand-or-Beginners-Friendly-Code-Python
class Solution: def countNodes(self, root: Optional[TreeNode]) -> int: queue = [] if not root: return 0 queue.append(root) count = 0 while queue: node = queue.pop(0) count += 1 if node.left: queue.append(node.left) if node.right: queue.append(node.right) return count
count-complete-tree-nodes
Two Methods | Easy to Understand | Beginners Friendly Code [Python]
tushgaurav
1
122
count complete tree nodes
222
0.598
Medium
3,979
https://leetcode.com/problems/count-complete-tree-nodes/discuss/2813529/Two-Methods-or-Easy-to-Understand-or-Beginners-Friendly-Code-Python
class Solution: def countNodes(self, root: Optional[TreeNode]) -> int: if not root: return 0 leftNodes = self.countNodes(root.left) rightNodes = self.countNodes(root.right) return leftNodes + rightNodes + 1
count-complete-tree-nodes
Two Methods | Easy to Understand | Beginners Friendly Code [Python]
tushgaurav
1
122
count complete tree nodes
222
0.598
Medium
3,980
https://leetcode.com/problems/count-complete-tree-nodes/discuss/702258/Python3-two-O(logN-*-logN)-approaches
class Solution: def countNodes(self, root: TreeNode) -> int: if not root: return 0 h = self.height(root) if self.height(root.right) == h-1: return 2**(h-1) + self.countNodes(root.right) else: return 2**(h-2) + self.countNodes(root.left) def height(self, node: TreeNode) -> int: """Return height of given node""" ans = 0 while node: ans, node = ans+1, node.left return ans
count-complete-tree-nodes
[Python3] two O(logN * logN) approaches
ye15
1
42
count complete tree nodes
222
0.598
Medium
3,981
https://leetcode.com/problems/count-complete-tree-nodes/discuss/702258/Python3-two-O(logN-*-logN)-approaches
class Solution: def countNodes(self, root: TreeNode) -> int: n, node = 0, root while node: n, node = n+1, node.left def fn(i): """Return ith node on level n""" node = root for k in reversed(range(n-1)): tf, i = divmod(i, 2**k) node = node.right if tf else node.left return node lo, hi = 0, 2**(n-1) while lo < hi: mid = (lo + hi)//2 if (fn(mid)): lo = mid+1 else: hi = mid return 2**(n-1) - 1 + lo if n else 0
count-complete-tree-nodes
[Python3] two O(logN * logN) approaches
ye15
1
42
count complete tree nodes
222
0.598
Medium
3,982
https://leetcode.com/problems/count-complete-tree-nodes/discuss/701579/summary-2-methods%3A-recursion-and-binary-search-both-O(logN*logN)
class Solution: def get_height(self, root): # O(logN) height = -1 node = root while node: height += 1 node = node.left return height def countNodes_binarySearch(self, root: TreeNode): height = self.get_height(root) # O(logN) if height <= 0: return height + 1 def num2node(num, step = height): # logN node = root mask = 1 << (step-1) for _ in range(step): node = node.right if num &amp; mask else node.left mask >>= 1 return False if node is None else True # O(logN * logN) lo, hi = 0, (1 << height) - 1 if num2node(hi): lo = hi while lo + 1 < hi: mi = (lo + hi) >> 1 if num2node(mi): lo = mi else: hi = mi return lo + (1 << height)
count-complete-tree-nodes
[summary] 2 methods: recursion & binary-search, both O(logN*logN)
newRuanXY
1
68
count complete tree nodes
222
0.598
Medium
3,983
https://leetcode.com/problems/count-complete-tree-nodes/discuss/701579/summary-2-methods%3A-recursion-and-binary-search-both-O(logN*logN)
class Solution: def get_height(self, root): # O(logN) height = -1 node = root while node: height += 1 node = node.left return height def countNodes_recursion(self, root: TreeNode) -> int: # O(logN * logN) height = self.get_height(root) # O(logN) if height <= 0: return height + 1 if self.get_height(root.right) == height - 1: # O(logN) return (1 << height) + self.countNodes_recursion(root.right) else: return (1 << (height-1)) + self.countNodes_recursion(root.left)
count-complete-tree-nodes
[summary] 2 methods: recursion & binary-search, both O(logN*logN)
newRuanXY
1
68
count complete tree nodes
222
0.598
Medium
3,984
https://leetcode.com/problems/count-complete-tree-nodes/discuss/252426/Easy-to-follow-Python3%3A-find-of-missing-nodes-first
class Solution: def countNodes(self, root: TreeNode) -> int: max_level = 0 temp = root while temp: max_level += 1 temp = temp.left num_missing = 0 q = [] cur_level = 1 while q or root: while root: q.append([root, cur_level]) root = root.right cur_level += 1 # print([x.val for x, _ in q]) root, cur_level = q.pop() if cur_level == max_level: return 2**(max_level) - 1 - num_missing else: if not root.right: num_missing += 1 if not root.left: num_missing += 1 root = root.left cur_level += 1 return 0
count-complete-tree-nodes
Easy to follow Python3: find # of missing nodes first
qqzzqq
1
144
count complete tree nodes
222
0.598
Medium
3,985
https://leetcode.com/problems/count-complete-tree-nodes/discuss/2833775/Python-Recursion-by-complete-and-full-binary-tree-or-binary-search
class Solution: def countNodes(self, root): if root is None: return 0 # compute the depth of the tree. cur = root depth = 0 while cur.left is not None: cur = cur.left depth += 1 if depth == 0: return 1 def contains(num): # the tree contains the num node at the leaf nodes nonlocal root, depth cur = root left, right = 0, 2 ** depth - 1 while left < right: pivot = left + (right - left) // 2 if num <= pivot: cur = cur.left right = pivot else: cur = cur.right left = pivot + 1 return cur is not None # conduct binary search on the depest level left, right = 0, 2 ** depth - 1 while left <= right: pivot = left + (right - left) // 2 if contains(pivot): left = pivot + 1 else: right = pivot - 1 return 2 ** depth - 1 + left
count-complete-tree-nodes
[Python] Recursion by complete and full binary tree | binary search
i-hate-covid
0
5
count complete tree nodes
222
0.598
Medium
3,986
https://leetcode.com/problems/count-complete-tree-nodes/discuss/2833775/Python-Recursion-by-complete-and-full-binary-tree-or-binary-search
class Solution: def countNodes(self, root): def get_full_height(root): # check if the tree is a full binary tree, return None if it's not, else return the height left_cur, right_cur = root, root height = 0 while right_cur is not None: left_cur = left_cur.left right_cur = right_cur.right height += 1 if left_cur is not None: return None else: return height height = get_full_height(root) if height is not None: # is full binary tree return 2 ** height - 1 else: return 1 + self.countNodes(root.left) + self.countNodes(root.right)
count-complete-tree-nodes
[Python] Recursion by complete and full binary tree | binary search
i-hate-covid
0
5
count complete tree nodes
222
0.598
Medium
3,987
https://leetcode.com/problems/count-complete-tree-nodes/discuss/2821674/80-ms-and-21.4-MB-Python-German
class Solution: #Takes 2*ceil(ld(n)) #Returns MaxHeight and MinHeight from a Node #Works because a complete tree is garanteed def heights(self, root: TreeNode): max, min = -1, -1 root2 = root #save it for the second treeclimb while root: #Get maxHeight max += 1 #started or reached a Node root = root.left while root2: #Get minHeight min += 1 #started or reached a Node root2 = root2.right return max, min #The number of nodes in the tree is in the range [0, 5 * 10^4]. #0 <= Node.val <= 5 * 10^4 #The tree is guaranteed to be complete. def countNodes(self, root: TreeNode) -> int: #Find the maxDepths left and right in the tree to compare maxH, minH = self.heights(root) if maxH == minH: #Check if the last layer is filled return 2**(maxH+1)-1 #calc the max nodes for given height #Now the last layer must be partially filled possible = 2**maxH #how much could fit in the last layer n = possible - 1 #start counting all above last layer #use a ld(N) search on lowest level to find last elem... #but i need also ld(N) steps to get down there => O(ldΒ²(N)) while root.left != None: #None signals done, there are no more nodes left possible = possible>>1 #possibles in subtrees left and right #Look at the left subtree to check for heigths lmax, lmin = self.heights(root.left) if lmax == 0 and lmin == 0: #Last node found! n += possible #should be always 1 here! break elif lmin == lmax and possible > 1: #left subtree is filled! n += possible #add elems found left a,b = self.heights(root.right) #check for more work to do if a>b: #if the rest is uneven, there are uncounted nodes root = root.right #check the right subtree continue else: break #this subtree has no uncounted nodes left elif lmax > lmin: #! root = root.left #go left continue return n
count-complete-tree-nodes
80 ms & 21.4 MB Python German
lucasscodes
0
4
count complete tree nodes
222
0.598
Medium
3,988
https://leetcode.com/problems/count-complete-tree-nodes/discuss/2821361/Optimal-Iterative-Solution-in-O(1)-Space-The-Best
class Solution: def countNodes(self, root: Optional[TreeNode]) -> int: if not root: return 0 depth = self.depth(root) bit = 1 << depth sum = bit while root.left: depth -= 1 bit >>= 1 if depth != self.depth(root.right): root = root.left else: root = root.right sum |= bit return sum def depth(self, root): depth = -1 while root: depth += 1 root = root.left return depth
count-complete-tree-nodes
Optimal Iterative Solution in O(1) Space, The Best
Triquetra
0
6
count complete tree nodes
222
0.598
Medium
3,989
https://leetcode.com/problems/count-complete-tree-nodes/discuss/2818854/Python3-oror-One-line-oror-Faster-than-89.9
class Solution: def countNodes(self, root: Optional[TreeNode]) -> int: return self.countNodes(root.left) + self.countNodes(root.right) + 1 if root else 0
count-complete-tree-nodes
βœ… Python3 || One line || Faster than 89.9%
PabloVE2001
0
7
count complete tree nodes
222
0.598
Medium
3,990
https://leetcode.com/problems/count-complete-tree-nodes/discuss/2818560/Python-3-Line-Solution
class Solution: def countNodes(self, root: Optional[TreeNode]) -> int: if root==None: return 0 return 1+self.countNodes(root.left)+ self.countNodes(root.right)
count-complete-tree-nodes
Python-3 Line Solution
smritiaspires
0
5
count complete tree nodes
222
0.598
Medium
3,991
https://leetcode.com/problems/count-complete-tree-nodes/discuss/2818412/Python-1-line-solution
class Solution: def countNodes(self, root: Optional[TreeNode]) -> int: return self.countNodes(root.left) + self.countNodes(root.right) + 1 if root else 0
count-complete-tree-nodes
Python 1 line solution
padamenko
0
6
count complete tree nodes
222
0.598
Medium
3,992
https://leetcode.com/problems/count-complete-tree-nodes/discuss/2818258/Python-Solution-in-O(logn2)
class Solution: def countNodes(self, root: Optional[TreeNode]) -> int: if not root: return 0 left = root.left right = root.right left_level = 1 right_level = 1 while left: left_level += 1 left = left.left while right: right_level +=1 right =right.right #if level are equal then we can simply calculate based on height of tree, because it will be perfect binary tree if left_level==right_level: return (2**left_level)-1 #else we can divide the tree and check for subtree return 1 + self.countNodes(root.left) + self.countNodes(root.right) ```
count-complete-tree-nodes
Python Solution in O(logn^2)
sameer96
0
6
count complete tree nodes
222
0.598
Medium
3,993
https://leetcode.com/problems/count-complete-tree-nodes/discuss/2818103/Python3-Binary-Search-Recursion-Bitmask
class Solution: def countNodes(self, root: Optional[TreeNode]) -> int: if root is None: return 0 @lru_cache(None) def seek(k): nonlocal root if k == 1: return root else: if (k &amp; 1) == 1: n = seek(k>>1).right else: n = seek(k>>1).left return n k = 1 while seek(k) is not None: k <<= 1 l = (k >> 1) r = k - 1 while l < r: # find the last populated node, binary search m = (l + r) // 2 if seek(m) is None: r = m - 1 elif l != m: l = m else: if seek(l+1) is not None: l = l + 1 else: return l return l
count-complete-tree-nodes
Python3 - Binary Search, Recursion, Bitmask
godshiva
0
3
count complete tree nodes
222
0.598
Medium
3,994
https://leetcode.com/problems/count-complete-tree-nodes/discuss/2817412/Python-or-Cheating-O(n)-%2B-Accepted-Sub-O(n)
class Solution: def countNodes(self, root: Optional[TreeNode], total = 0) -> int: # Brute Force: Visit all Nodes if not root: return total if root: total += 1 left = self.countNodes(root.left) if root.left else 0 right = self.countNodes(root.right) if root.right else 0 return total + left + right
count-complete-tree-nodes
Python | Cheating O(n) + Accepted Sub-O(n)
jessewalker2010
0
3
count complete tree nodes
222
0.598
Medium
3,995
https://leetcode.com/problems/count-complete-tree-nodes/discuss/2817412/Python-or-Cheating-O(n)-%2B-Accepted-Sub-O(n)
class Solution: def countNodes(self, root: Optional[TreeNode], total = 0) -> int: def penult(node): if not node.left and not node.right: return 1 if node.left: if node.left.left or node.left.right: return 1 if node.right: if node.right.left or node.right.right: return 1 return 3 if node.left and node.right else 2 if not root: return total check = penult(root) if check == 1: left = self.countNodes(root.left) right = self.countNodes(root.right) return check + left + right return total + check
count-complete-tree-nodes
Python | Cheating O(n) + Accepted Sub-O(n)
jessewalker2010
0
3
count complete tree nodes
222
0.598
Medium
3,996
https://leetcode.com/problems/count-complete-tree-nodes/discuss/2817374/Simple-solution-dfs-Time-O(n)-Space-O(1)
class Solution: def countNodes(self, root: Optional[TreeNode]) -> int: if(root is None): return 0 return self.countNodes(root.left) + self.countNodes(root.right) + 1
count-complete-tree-nodes
Simple solution dfs Time O(n), Space O(1)
danhtran-dev
0
5
count complete tree nodes
222
0.598
Medium
3,997
https://leetcode.com/problems/count-complete-tree-nodes/discuss/2817090/O(log(n)2)-solution-with-explanation
class Solution: def countNodes(self, root: Optional[TreeNode]) -> int: # Lets try in O(log(n)) (or something like that) # Go down left to get the depth. depth_left = 0 node = root while node: node = node.left depth_left += 1 # Ditto for right depth_right = 0 node = root while node: node = node.right depth_right += 1 # There are now two cases to consider: # - depth_left == depth_right and the tree is perfect # - depth_left != depth_right and we need to figure out how many nodes miss at the bottom layer. # For the first case it's O(log(n) + log(n) + 1) = O(log(n)) # For the second case we will go down both subtrees. Either # of these subtrees will be perfect which takes O(log(n)) time. # Since the depth of a complete binary tree is log(n) it will # take O(log(n) * log(n)) = O(log(n) ^ 2) time to determine # the amount of nodes. if depth_left == depth_right: # depth = log(n) <=> n = 2^depth # Except not quite, consider 1, 3, 7, 15 ... # so basically 2^depth - 1 return 2**depth_left - 1 else: # Count the root and both subtrees return 1 + Solution().countNodes(root.left) + Solution().countNodes(root.right)
count-complete-tree-nodes
O(log(n)^2) solution with explanation
demindiro
0
5
count complete tree nodes
222
0.598
Medium
3,998
https://leetcode.com/problems/count-complete-tree-nodes/discuss/2817031/O(binary-search)-*-O(depth)-~-logN*logN-(%2B-bit-manipulation)
class Solution: def countNodes(self, root: Optional[TreeNode]) -> int: if not root: return 0 minDepth = 1 current = root while current.left: current = current.left minDepth += 1 r = 2**(minDepth) l = 2**(minDepth-1) while l < r: mid = (r+l) // 2 midBin = bin(mid)[3:] #removing first bit and "0b" prefix current = root for c in midBin: if c == "1": current = current.right else: current = current.left if current: l = mid+1 else: r = mid return l-1 #Look binary number digits and see that it controls the direction of exact place of Nth node #1| #1|0 #1|1 #1|00 #1|01 #1|10 #1|11
count-complete-tree-nodes
O(binary search) * O(depth) ~ logN*logN (+ bit manipulation)
Posni_Sir_60g_Proteina
0
6
count complete tree nodes
222
0.598
Medium
3,999