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/swapping-nodes-in-a-linked-list/discuss/1304317/One-Pass-Two-pointers-approach.-Runtime%3A-1060-ms-faster-than-67.51 | class Solution:
def swapNodes(self, head: ListNode, k: int) -> ListNode:
if not head:
return
first=slow=fast=head
while fast.next:
if k>1:
fast=fast.next
first=fast
k-=1
else:
slow=slow.next
fast=fast.next
first.val,slow.val=slow.val,first.val
return head | swapping-nodes-in-a-linked-list | One Pass, Two pointers approach. Runtime: 1060 ms, faster than 67.51% | deleted_user | 1 | 124 | swapping nodes in a linked list | 1,721 | 0.677 | Medium | 24,900 |
https://leetcode.com/problems/swapping-nodes-in-a-linked-list/discuss/2768429/Easy-Python-swapping-using-two-pointers | class Solution:
def swapNodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
h1=head
count=0
while h1:
count+=1
h1=h1.next
if(k>count):
k=k%count
swap2=(count-k)+1
h2=head
h3=head
i=1
while(i<k):
h3=h3.next
i+=1
while(i<count):
h2=h2.next
i+=1
temp=h3.val
h3.val=h2.val
h2.val=temp
return head | swapping-nodes-in-a-linked-list | Easy Python swapping using two pointers | liontech_123 | 0 | 3 | swapping nodes in a linked list | 1,721 | 0.677 | Medium | 24,901 |
https://leetcode.com/problems/swapping-nodes-in-a-linked-list/discuss/2719224/Python-Easy-Intuitive-Solution | class Solution:
def swapNodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
node_list = []
new = head
while head:
node_list.append(head.val)
head = head.next
n=len(node_list)
node_list[n-k], node_list[k-1] = node_list[k-1], node_list[n-k]
cur = temp = ListNode(0)
for item in node_list:
cur.next = ListNode(item)
cur = cur.next
return temp.next | swapping-nodes-in-a-linked-list | Python Easy Intuitive Solution | katdare | 0 | 6 | swapping nodes in a linked list | 1,721 | 0.677 | Medium | 24,902 |
https://leetcode.com/problems/swapping-nodes-in-a-linked-list/discuss/2707021/Last-two-pointers-Simple-Approach | class Solution:
def swapNodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
if(not(head.next)):
return head
temp_node = ListNode(69)
temp_node.next, head = head, temp_node
first, fast, last, prev_first, prev_last = head.next, head.next, head.next, head, head
for i in range(k-1):
first = first.next
prev_first = prev_first.next
fast = fast.next
while(fast.next):
last = last.next
prev_last = prev_last.next
fast = fast.next
prev_first.next = last
prev_last.next = first
first.next, last.next = last.next, first.next
return head.next | swapping-nodes-in-a-linked-list | Last two pointers - Simple Approach | bhavesh0124 | 0 | 5 | swapping nodes in a linked list | 1,721 | 0.677 | Medium | 24,903 |
https://leetcode.com/problems/swapping-nodes-in-a-linked-list/discuss/2702567/PYTHON-Python-easy-solution | class Solution:
def swapNodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
length = 1
tmp = head
while tmp.next:
tmp = tmp.next
length += 1
if length == k or k == 1:
head.val, tmp.val = tmp.val, head.val
else:
beginning = head
for i in range(k - 1):
beginning = beginning.next
end = head
for i in range(length - k):
end = end.next
beginning.val, end.val = end.val, beginning.val
return head | swapping-nodes-in-a-linked-list | [PYTHON] Python easy solution | valera_grishko | 0 | 6 | swapping nodes in a linked list | 1,721 | 0.677 | Medium | 24,904 |
https://leetcode.com/problems/swapping-nodes-in-a-linked-list/discuss/2645216/Easy-Python-Solution-(Iterative-%2B-Recursive) | class Solution:
def swapNodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
l = r = head
# find kth node from beginning
for i in range(k-1):
l = l.next
# find kth node from end by finding tail node
tail = l
while tail.next:
r, tail = r.next, tail.next
# r reached kth node from end, swap them
l.val, r.val = r.val, l.val
return head | swapping-nodes-in-a-linked-list | Easy Python Solution (Iterative + Recursive) | rishisoni6071 | 0 | 17 | swapping nodes in a linked list | 1,721 | 0.677 | Medium | 24,905 |
https://leetcode.com/problems/swapping-nodes-in-a-linked-list/discuss/2645216/Easy-Python-Solution-(Iterative-%2B-Recursive) | class Solution:
# Recursive Approach (less faster)
def __init__(self):
self.startnode = None
self.startcount = 0
self.endcount = 0
def swapNodes(self, head, k):
if head is None:
return None
self.startcount += 1
if self.startcount == k:
self.startnode = head
node = self.swapNodes(head.next, k)
self.endcount += 1
if self.endcount == k:
self.startnode.val, head.val = head.val, self.startnode.val
head.next = node
return head | swapping-nodes-in-a-linked-list | Easy Python Solution (Iterative + Recursive) | rishisoni6071 | 0 | 17 | swapping nodes in a linked list | 1,721 | 0.677 | Medium | 24,906 |
https://leetcode.com/problems/swapping-nodes-in-a-linked-list/discuss/2383929/Python3-solution-O(N)-time-complexity-O(1)-space-complexity-33-faster | class Solution:
def swapNodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
nodeStart = head
kStart = k
#find the kth node from the beginning
while kStart - 1 > 0:
nodeStart = nodeStart.next
kStart -= 1
#initialize the fast pointer for the iteration
nodeEnd, fast = head, head
while k - 1 > 0:
fast = fast.next
k -= 1
#find the kth node from the end
while fast and fast.next:
nodeEnd = nodeEnd.next
fast = fast.next
#swap values
nodeStart.val, nodeEnd.val = nodeEnd.val, nodeStart.val
return head | swapping-nodes-in-a-linked-list | Python3 solution, O(N) time complexity, O(1) space complexity, 33% faster | matteogianferrari | 0 | 44 | swapping nodes in a linked list | 1,721 | 0.677 | Medium | 24,907 |
https://leetcode.com/problems/swapping-nodes-in-a-linked-list/discuss/2319947/Python-Solution | class Solution:
def swapNodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
tail=head
k-=1
while k:
tail=tail.next
k-=1
first,prev=tail,head
while tail.next:
tail=tail.next
prev=prev.next
second=prev
first.val,second.val=second.val,first.val
return head | swapping-nodes-in-a-linked-list | Python Solution | kanishktyagi11 | 0 | 62 | swapping nodes in a linked list | 1,721 | 0.677 | Medium | 24,908 |
https://leetcode.com/problems/swapping-nodes-in-a-linked-list/discuss/1929353/Python-Solution-84-faster | class Solution:
def swapNodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
# Get the length of the list
cur_node = head
count = 0
while cur_node:
count += 1
cur_node = cur_node.next
# Point to the node, present at kth location
cur_node, idx = head, 1
while idx < k:
idx += 1
cur_node = cur_node.next
node1 = cur_node
# Point to the node, present at len(list)-k th location
cur_node, idx = head, 1
while idx < count - k+1:
idx += 1
cur_node = cur_node.next
node2 = cur_node
# swap node values
node1.val, node2.val = node2.val, node1.val
return head | swapping-nodes-in-a-linked-list | Python Solution, 84% faster | pradeep288 | 0 | 58 | swapping nodes in a linked list | 1,721 | 0.677 | Medium | 24,909 |
https://leetcode.com/problems/swapping-nodes-in-a-linked-list/discuss/1917739/python3-or-Two-Pointer-or-Faster-than-90 | class Solution:
def swapNodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
res, first, last = head, head, head
while k > 1:
first = head.next
head = head.next
k -= 1
while head.next:
head = head.next
last = last.next
first.val, last.val = last.val, first.val
return res | swapping-nodes-in-a-linked-list | python3 | Two - Pointer | Faster than 90% | milannzz | 0 | 6 | swapping nodes in a linked list | 1,721 | 0.677 | Medium | 24,910 |
https://leetcode.com/problems/swapping-nodes-in-a-linked-list/discuss/1914552/Python-Easy-or-3-Pointer-Solution-or-O(n)-or-O(1) | class Solution:
def swapNodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
p1,p2 = head, head
if head is None:
return None
k-=1
while p1 is not None and k:
k-=1
p1 = p1.next
p3 = p1
while p3.next is not None:
p3 = p3.next
p2 = p2.next
p1.val, p2.val = p2.val, p1.val
return head | swapping-nodes-in-a-linked-list | Python Easy | 3 Pointer Solution | O(n) | O(1) | sathwickreddy | 0 | 17 | swapping nodes in a linked list | 1,721 | 0.677 | Medium | 24,911 |
https://leetcode.com/problems/swapping-nodes-in-a-linked-list/discuss/1912994/Easy-understanding-oror-Two-pointers | class Solution:
def swapNodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
p1 = head
p2 = head
for i in range(k-1):
p1 = p1.next
p2 = head
k_it = p1
while k_it.next:
p2 = p2.next
k_it = k_it.next
p1.val, p2.val = p2.val,p1.val
return head | swapping-nodes-in-a-linked-list | Easy understanding || Two pointers | testbugsk | 0 | 10 | swapping nodes in a linked list | 1,721 | 0.677 | Medium | 24,912 |
https://leetcode.com/problems/swapping-nodes-in-a-linked-list/discuss/1912990/python-easy-understanding-solution-with-comment | class Solution:
def swapNodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
dummy = prev = head
while k > 1:
head = head.next
k -= 1
node1 = head # node1 record the node kth away from head
while head.next: # head and prev will keep constant range of k
head = head.next
prev = prev.next
node2 = prev # node2 record the node kth away to tail
node1.val, node2.val = node2.val, node1.val # Swap the val of two node
return dummy | swapping-nodes-in-a-linked-list | python easy - understanding solution with comment | byroncharly3 | 0 | 4 | swapping nodes in a linked list | 1,721 | 0.677 | Medium | 24,913 |
https://leetcode.com/problems/swapping-nodes-in-a-linked-list/discuss/1912872/Readable-Python-solution-with-explantion | class Solution:
def swapNodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
# [1/2]
# First iteration over linked list
# stores k^th node in first_node variable and counts the length of linked list + 1
itr = head
i = 1 # at the end of iteration i == length + 1
first_node = None
while itr != None:
if i == k:
first_node = itr
i += 1
itr = itr.next
# [2/2]
# Second iteration over linked list
# looks for second_node and swaps its value with first_node
itr = head
j = 1
while itr != None:
# if length of linked list == 9 and k == 4 then
# i - k == 6 (remember i == length + 1)
if j == i - k:
first_node.val, itr.val = itr.val, first_node.val
break
j += 1
itr = itr.next
return head | swapping-nodes-in-a-linked-list | Readable Python solution with explantion | zebra-f | 0 | 17 | swapping nodes in a linked list | 1,721 | 0.677 | Medium | 24,914 |
https://leetcode.com/problems/swapping-nodes-in-a-linked-list/discuss/1912841/Python3-Solution-with-using-two-pointers-one-pass | class Solution:
"""
'end' node is k positions behind 'cur' node. when 'cur' node reaches the end of list => 'end' is k positions behind last element of list
when 'first' node go to target node (k postions forward begin of the list) we can start to move 'end' pointer and 'cur' in same time
"""
def swapNodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
first = end = cur = head
while cur.next:
if k > 1:
k -= 1
first = first.next
else:
end = end.next
cur = cur.next
first.val, end.val = end.val, first.val
return head | swapping-nodes-in-a-linked-list | [Python3] Solution with using two pointers, one pass | maosipov11 | 0 | 11 | swapping nodes in a linked list | 1,721 | 0.677 | Medium | 24,915 |
https://leetcode.com/problems/swapping-nodes-in-a-linked-list/discuss/1912555/Python-Simple-Intuitive-Solution-with-Explanation | class Solution:
def swapNodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
fastNode = head
slowNode = head
for _ in range(k):
currNode = fastNode
fastNode = fastNode.next
while fastNode:
slowNode = slowNode.next
fastNode = fastNode.next
slowNode.val, currNode.val = currNode.val, slowNode.val
return head | swapping-nodes-in-a-linked-list | [Python] Simple Intuitive Solution with Explanation | preetbohra | 0 | 18 | swapping nodes in a linked list | 1,721 | 0.677 | Medium | 24,916 |
https://leetcode.com/problems/swapping-nodes-in-a-linked-list/discuss/1912103/Python-or-Tc%3A-O(N)-and-space-Complexity%3A-O(N)-or-Swapping-Nodes-in-a-Linked-List | class Solution:
def swapNodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
temp = head
lst = []
count =0
while(temp != None):
lst.append(temp.val)
temp = temp.next
count += 1
k %= count
k -= 1
print(k,lst[k],lst[-k-1])
lst[k],lst[-k-1]=lst[-k-1],lst[k]
print(lst)
temp = head
inc = 0
while(temp != None):
temp.val = lst[inc]
inc += 1
temp = temp.next
return head
``` | swapping-nodes-in-a-linked-list | Python | Tc: O(N) and space Complexity: O(N) | Swapping Nodes in a Linked List | krishna_13 | 0 | 10 | swapping nodes in a linked list | 1,721 | 0.677 | Medium | 24,917 |
https://leetcode.com/problems/swapping-nodes-in-a-linked-list/discuss/1829477/slow-and-fast-pointer-python3-or-easy-solution-or-O(n) | class Solution:
def swapNodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
fast = head
slow = head
for i in range(1,k):
fast = fast.next
beg = fast
while fast.next:
fast = fast.next
slow = slow.next
tmp = beg.val
beg.val = slow.val
slow.val = tmp
return head | swapping-nodes-in-a-linked-list | slow and fast pointer python3 | easy solution | O(n) | adiljay05 | 0 | 24 | swapping nodes in a linked list | 1,721 | 0.677 | Medium | 24,918 |
https://leetcode.com/problems/minimize-hamming-distance-after-swap-operations/discuss/1982743/Python3-solution | class Solution:
def minimumHammingDistance(self, source: List[int], target: List[int], allowedSwaps: List[List[int]]) -> int:
def gen_adjacency():
adj = {}
for i in range(len(source)):
adj[i] = []
for a, b in allowedSwaps:
adj[a].append(b)
adj[b].append(a)
return adj
def dfs(i):
visited.add(i)
this_group.add(i)
for neigh in adj[i]:
if neigh not in visited:
dfs(neigh)
adj = gen_adjacency()
visited = set()
common_counts = 0
for i in adj:
if i not in visited:
this_group = set()
dfs(i)
s_counts = collections.Counter([source[i] for i in this_group])
t_counts = collections.Counter([target[i] for i in this_group])
common = set(s_counts).intersection(t_counts)
for common_int in common:
common_counts += min(s_counts[common_int], t_counts[common_int])
ans = len(source) - common_counts
return ans | minimize-hamming-distance-after-swap-operations | Python3 solution | dalechoi | 0 | 45 | minimize hamming distance after swap operations | 1,722 | 0.487 | Medium | 24,919 |
https://leetcode.com/problems/minimize-hamming-distance-after-swap-operations/discuss/1011022/Python-Union-find-(Beats-100-speed-and-memory) | class Solution:
def minimumHammingDistance(self, source: List[int], target: List[int], allowedSwaps: List[List[int]]) -> int:
# idx to group id
idx_to_group = {}
# group id to index set
group_to_idx = {}
global_group_id = 0
for swap in allowedSwaps:
foundGroups = set()
for idx in swap:
if idx in idx_to_group:
foundGroups.add(idx_to_group[idx])
if foundGroups:
pivot = min(foundGroups)
for group_id in foundGroups:
if pivot != group_id:
group_to_idx[pivot].update(group_to_idx[group_id])
group_to_idx.pop(group_id)
group_to_idx[pivot].update(swap)
for idx in group_to_idx[pivot]:
idx_to_group[idx] = pivot
else:
for idx in swap:
idx_to_group[idx] = global_group_id
group_to_idx[global_group_id] = set(swap)
global_group_id += 1
ans = 0
if group_to_idx == {}:
for i in range(len(source)):
if source[i]!=target[i]:
ans += 1
else:
for group_id in group_to_idx:
src = {}
tgt = {}
for idx in group_to_idx[group_id]:
if source[idx] not in src:
src[source[idx]] = 0
src[source[idx]] += 1
if target[idx] not in tgt:
tgt[target[idx]] = 0
tgt[target[idx]] += 1
for key in src:
if key in tgt:
if src[key] > tgt[key]:
ans += src[key] - tgt[key]
else:
ans += src[key]
for i in range(len(source)):
if i not in idx_to_group and source[i]!=target[i]:
ans += 1
return ans | minimize-hamming-distance-after-swap-operations | [Python] Union-find (Beats 100% speed and memory) | mihirrane | 0 | 96 | minimize hamming distance after swap operations | 1,722 | 0.487 | Medium | 24,920 |
https://leetcode.com/problems/find-minimum-time-to-finish-all-jobs/discuss/1009859/Python3-backtracking | class Solution:
def minimumTimeRequired(self, jobs: List[int], k: int) -> int:
jobs.sort(reverse=True)
def fn(i):
"""Assign jobs to worker and find minimum time."""
nonlocal ans
if i == len(jobs): ans = max(time)
else:
for kk in range(k):
if not kk or time[kk-1] > time[kk]:
time[kk] += jobs[i]
if max(time) < ans: fn(i+1)
time[kk] -= jobs[i]
ans = inf
time = [0]*k
fn(0)
return ans | find-minimum-time-to-finish-all-jobs | [Python3] backtracking | ye15 | 5 | 805 | find minimum time to finish all jobs | 1,723 | 0.426 | Hard | 24,921 |
https://leetcode.com/problems/find-minimum-time-to-finish-all-jobs/discuss/1009859/Python3-backtracking | class Solution:
def minimumTimeRequired(self, jobs: List[int], k: int) -> int:
def fn(i):
"""Assign jobs to worker and find minimum time."""
nonlocal ans
if i == len(jobs): ans = max(time)
else:
for kk in range(k):
if not kk or time[kk-1] != time[kk]:
time[kk] += jobs[i]
if max(time) < ans: fn(i+1)
time[kk] -= jobs[i]
ans = inf
time = [0]*k
fn(0)
return ans | find-minimum-time-to-finish-all-jobs | [Python3] backtracking | ye15 | 5 | 805 | find minimum time to finish all jobs | 1,723 | 0.426 | Hard | 24,922 |
https://leetcode.com/problems/find-minimum-time-to-finish-all-jobs/discuss/2255841/Python-implementation-of-the-theoretically-optimal-O(3N)-solution | class Solution:
def minimumTimeRequired(self, jobs: List[int], num_workers: int) -> int:
n = len(jobs)
worker_cost = [0] * (1 << n)
for state in range(1 << n):
for i in range(n):
if state & (1 << i):
worker_cost[state] += jobs[i]
@functools.cache
def compute_time(state: int, curr_workers: int) -> int:
if curr_workers == 1:
return worker_cost[state]
best = float("inf")
worker_state = state
while worker_state:
if worker_cost[worker_state] < best:
best = min(best, max(compute_time(state ^ worker_state, curr_workers - 1), worker_cost[worker_state]))
worker_state = (worker_state - 1) & state
return best
return compute_time((1 << n) - 1, num_workers) | find-minimum-time-to-finish-all-jobs | Python implementation of the theoretically optimal O(3^N) solution | pauldb89 | 1 | 210 | find minimum time to finish all jobs | 1,723 | 0.426 | Hard | 24,923 |
https://leetcode.com/problems/number-of-rectangles-that-can-form-the-largest-square/discuss/1020629/Python3-freq-table | class Solution:
def countGoodRectangles(self, rectangles: List[List[int]]) -> int:
freq = {}
for l, w in rectangles:
x = min(l, w)
freq[x] = 1 + freq.get(x, 0)
return freq[max(freq)] | number-of-rectangles-that-can-form-the-largest-square | [Python3] freq table | ye15 | 3 | 222 | number of rectangles that can form the largest square | 1,725 | 0.787 | Easy | 24,924 |
https://leetcode.com/problems/number-of-rectangles-that-can-form-the-largest-square/discuss/2710494/pythonoror-O(N) | class Solution:
def countGoodRectangles(self, rectangles: List[List[int]]) -> int:
max_len = float('-inf')
count = 0
for item in rectangles:
min_len = min(item)
if min_len == max_len:
count += 1
elif min_len > max_len:
max_len = min_len
count = 1
return count | number-of-rectangles-that-can-form-the-largest-square | [python|| O(N)] | Sneh713 | 1 | 57 | number of rectangles that can form the largest square | 1,725 | 0.787 | Easy | 24,925 |
https://leetcode.com/problems/number-of-rectangles-that-can-form-the-largest-square/discuss/1681779/O(n)-time-or-O(1)-space-or-one-pass | class Solution:
def countGoodRectangles(self, rectangles: List[List[int]]) -> int:
max_size = 0
max_count = 0
for rect in rectangles:
sq_size = min(rect[0], rect[1])
if sq_size > max_size:
max_size = sq_size
max_count = 1
elif sq_size == max_size:
max_count+=1
return max_count | number-of-rectangles-that-can-form-the-largest-square | O(n) time | O(1) space | one pass | snagsbybalin | 1 | 94 | number of rectangles that can form the largest square | 1,725 | 0.787 | Easy | 24,926 |
https://leetcode.com/problems/number-of-rectangles-that-can-form-the-largest-square/discuss/1371295/python3 | class Solution:
def countGoodRectangles(self, rectangles: List[List[int]]) -> int:
maxLength = 0
maxes = []
for rect in rectangles:
minimum = min(rect)
maxes.append(minimum)
maxLength = max(maxes)
return maxes.count(maxLength) | number-of-rectangles-that-can-form-the-largest-square | python3 | RobertObrochta | 1 | 65 | number of rectangles that can form the largest square | 1,725 | 0.787 | Easy | 24,927 |
https://leetcode.com/problems/number-of-rectangles-that-can-form-the-largest-square/discuss/1095964/Simple-Python3-Solution-Easy-to-understand | class Solution:
def countGoodRectangles(self, rectangles: List[List[int]]) -> int:
squares = []
for rectangle in rectangles:
squares.append(min(rectangle[0], rectangle[1]))
squares.sort()
count = 1
length = len(squares) - 1
while length > 0:
if squares[length] != squares[length-1]:
break
count += 1
length -= 1
return count | number-of-rectangles-that-can-form-the-largest-square | Simple Python3 Solution - Easy to understand | nematov_olimjon | 1 | 121 | number of rectangles that can form the largest square | 1,725 | 0.787 | Easy | 24,928 |
https://leetcode.com/problems/number-of-rectangles-that-can-form-the-largest-square/discuss/1059458/Easy-to-understand-python-3-solution | class Solution:
def countGoodRectangles(self, rectangles: List[List[int]]) -> int:
arr = []
count = 0
for i in rectangles:
x = min(i)
arr.append(x)
for j in range(len(arr)):
if arr[j] == max(arr):
count+=1
return count | number-of-rectangles-that-can-form-the-largest-square | Easy to understand python 3 solution | harshitkd | 1 | 63 | number of rectangles that can form the largest square | 1,725 | 0.787 | Easy | 24,929 |
https://leetcode.com/problems/number-of-rectangles-that-can-form-the-largest-square/discuss/1020627/Easy-and-Clear-Solution-Python-3 | class Solution:
def countGoodRectangles(self, rectangles: List[List[int]]) -> int:
mx,cmp=0,0
for i in rectangles:
if min(i)>mx:
mx=min(i)
cmp=1
elif min(i)==mx:
cmp+=1
return cmp | number-of-rectangles-that-can-form-the-largest-square | Easy & Clear Solution Python 3 | moazmar | 1 | 61 | number of rectangles that can form the largest square | 1,725 | 0.787 | Easy | 24,930 |
https://leetcode.com/problems/number-of-rectangles-that-can-form-the-largest-square/discuss/2707776/easy-solution-oror-Python | class Solution:
def countGoodRectangles(self, rectangles: List[List[int]]) -> int:
squares=[min(i) for i in rectangles]
return squares.count(max(squares)) | number-of-rectangles-that-can-form-the-largest-square | easy solution || Python | MaryLuz | 0 | 3 | number of rectangles that can form the largest square | 1,725 | 0.787 | Easy | 24,931 |
https://leetcode.com/problems/number-of-rectangles-that-can-form-the-largest-square/discuss/2675539/Python-or-TIME-COMPLEXITY%3A-O(N)-or-Space-Complexity-%3A-O(1) | class Solution:
def countGoodRectangles(self, rectangles: List[List[int]]) -> int:
mx = -1
count = 0
for i in rectangles:
temp = min(i[0],i[1])
if temp>mx:
mx = temp
count = 0
if temp == mx:
count+=1
return count | number-of-rectangles-that-can-form-the-largest-square | Python | TIME COMPLEXITY: O(N) | Space Complexity : O(1) | tanaydwivedi095 | 0 | 3 | number of rectangles that can form the largest square | 1,725 | 0.787 | Easy | 24,932 |
https://leetcode.com/problems/number-of-rectangles-that-can-form-the-largest-square/discuss/2583155/SIMPLE-PYTHON3-SOLUTION-easy-to-understand | class Solution:
def countGoodRectangles(self, rectangles: List[List[int]]) -> int:
c = []
count = 0
for i in rectangles:
c.append(min(i))
ans = max(c)
for j in range(len(c)):
if c[j] == ans:
count = count+1
return count | number-of-rectangles-that-can-form-the-largest-square | ✅✔ SIMPLE PYTHON3 SOLUTION ✅✔easy to understand | rajukommula | 0 | 37 | number of rectangles that can form the largest square | 1,725 | 0.787 | Easy | 24,933 |
https://leetcode.com/problems/number-of-rectangles-that-can-form-the-largest-square/discuss/2489159/Simple-and-concise-python-solution | class Solution:
def countGoodRectangles(self, rectangles: List[List[int]]) -> int:
min_sides = []
for rect in rectangles:
min_sides.append(min(rect))
max_length = max(min_sides)
return min_sides.count(max_length) | number-of-rectangles-that-can-form-the-largest-square | Simple and concise python solution | aruj900 | 0 | 11 | number of rectangles that can form the largest square | 1,725 | 0.787 | Easy | 24,934 |
https://leetcode.com/problems/number-of-rectangles-that-can-form-the-largest-square/discuss/2421554/Easy-python-solution | class Solution:
def countGoodRectangles(self, rectangles: List[List[int]]) -> int:
square_counts = {}
for rectangle in rectangles:
min_length = min(rectangle)
if min_length in square_counts:
square_counts[min_length] += 1
else:
square_counts[min_length] = 1
maxi = max(square_counts)
return square_counts[maxi] | number-of-rectangles-that-can-form-the-largest-square | Easy python solution | samanehghafouri | 0 | 15 | number of rectangles that can form the largest square | 1,725 | 0.787 | Easy | 24,935 |
https://leetcode.com/problems/number-of-rectangles-that-can-form-the-largest-square/discuss/2296674/3-Liner-oror-Python-Easy-solution | '''class Solution:
def countGoodRectangles(self, rectangles: List[List[int]]) -> int:
sq=[]
for r in rectangles:
sq.append(min(r))
return sq.count(max(sq))''' | number-of-rectangles-that-can-form-the-largest-square | 3 Liner || Python Easy solution | keertika27 | 0 | 16 | number of rectangles that can form the largest square | 1,725 | 0.787 | Easy | 24,936 |
https://leetcode.com/problems/number-of-rectangles-that-can-form-the-largest-square/discuss/1923247/easy-python-code | class Solution:
def countGoodRectangles(self, rectangles: List[List[int]]) -> int:
max = 0
count = 0
for i in rectangles:
if max < min(i[0],i[1]):
max = min(i[0],i[1])
for i in rectangles:
if max == min(i[0],i[1]):
count += 1
return count | number-of-rectangles-that-can-form-the-largest-square | easy python code | dakash682 | 0 | 27 | number of rectangles that can form the largest square | 1,725 | 0.787 | Easy | 24,937 |
https://leetcode.com/problems/number-of-rectangles-that-can-form-the-largest-square/discuss/1847880/Python-dollarolution | class Solution:
def countGoodRectangles(self, rectangles: List[List[int]]) -> int:
maximum = 0
for i in rectangles:
x = min(i)
if x > maximum:
maximum = x
count = 1
elif x == maximum:
count += 1
return count | number-of-rectangles-that-can-form-the-largest-square | Python $olution | AakRay | 0 | 40 | number of rectangles that can form the largest square | 1,725 | 0.787 | Easy | 24,938 |
https://leetcode.com/problems/number-of-rectangles-that-can-form-the-largest-square/discuss/1829258/1-Line-Python-Solution-oror-20-Faster-oror-Memory-less-than-80 | class Solution:
def countGoodRectangles(self, rectangles: List[List[int]]) -> int:
return sorted(Counter([min(rectangle) for rectangle in rectangles]).items(), reverse=True)[0][1] | number-of-rectangles-that-can-form-the-largest-square | 1-Line Python Solution || 20% Faster || Memory less than 80% | Taha-C | 0 | 36 | number of rectangles that can form the largest square | 1,725 | 0.787 | Easy | 24,939 |
https://leetcode.com/problems/number-of-rectangles-that-can-form-the-largest-square/discuss/1829258/1-Line-Python-Solution-oror-20-Faster-oror-Memory-less-than-80 | class Solution:
def countGoodRectangles(self, rectangles: List[List[int]]) -> int:
squares = [min(x) for x in rectangles]
return squares.count(max(squares)) | number-of-rectangles-that-can-form-the-largest-square | 1-Line Python Solution || 20% Faster || Memory less than 80% | Taha-C | 0 | 36 | number of rectangles that can form the largest square | 1,725 | 0.787 | Easy | 24,940 |
https://leetcode.com/problems/number-of-rectangles-that-can-form-the-largest-square/discuss/1751152/Easy-Python-Solution | class Solution:
def countGoodRectangles(self, rectangles: List[List[int]]) -> int:
maxr = 0
count = 0
for i in rectangles:
if maxr == min(i):
count += 1
elif min(i) > maxr:
count = 1
maxr = min(i)
return count | number-of-rectangles-that-can-form-the-largest-square | Easy Python Solution | MengyingLin | 0 | 21 | number of rectangles that can form the largest square | 1,725 | 0.787 | Easy | 24,941 |
https://leetcode.com/problems/number-of-rectangles-that-can-form-the-largest-square/discuss/1627681/Python3or-96.33-fast-91-storageor-one-pass-O(n) | class Solution:
def countGoodRectangles(self, rectangles: List[List[int]]) -> int:
maxlen=-1
curr_count=0
for i in range(len(rectangles)):
#find side length of square
rect=min(rectangles[i][0],rectangles[i][1])
#if new maximum length side found set count to 1 ,
#if same side encountered again increment,
#if new max len side is found again count is set to 1
if rect>maxlen:
maxlen=rect
curr_count=1
elif rect==maxlen:
curr_count+=1
return curr_count | number-of-rectangles-that-can-form-the-largest-square | Python3| 96.33% fast 91% storage| one pass O(n) | kritigoel | 0 | 52 | number of rectangles that can form the largest square | 1,725 | 0.787 | Easy | 24,942 |
https://leetcode.com/problems/number-of-rectangles-that-can-form-the-largest-square/discuss/1600521/Python-O(n)-time-and-O(1)-space | class Solution:
def countGoodRectangles(self, rectangles: List[List[int]]) -> int:
smax=-1
ans=0
for i in rectangles:
mn = min(i[0],i[1])
if mn<smax:
continue
elif mn==smax:
ans+=1
else:
ans=1
smax = mn
return ans | number-of-rectangles-that-can-form-the-largest-square | Python O(n) time and O(1) space | dsalgobros | 0 | 46 | number of rectangles that can form the largest square | 1,725 | 0.787 | Easy | 24,943 |
https://leetcode.com/problems/number-of-rectangles-that-can-form-the-largest-square/discuss/1594998/Python-3-easy-solution | class Solution:
def countGoodRectangles(self, rectangles: List[List[int]]) -> int:
res = maxLen = 0
for length, width in rectangles:
squareLen = min(length, width)
if squareLen > maxLen:
res = 1
maxLen = squareLen
elif squareLen == maxLen:
res += 1
return res | number-of-rectangles-that-can-form-the-largest-square | Python 3 easy solution | dereky4 | 0 | 47 | number of rectangles that can form the largest square | 1,725 | 0.787 | Easy | 24,944 |
https://leetcode.com/problems/number-of-rectangles-that-can-form-the-largest-square/discuss/1543250/Counter-for-min-97-speed | class Solution:
def countGoodRectangles(self, rectangles: List[List[int]]) -> int:
cnt = Counter(min(a, b) for a, b in rectangles)
return cnt[max(cnt.keys())] | number-of-rectangles-that-can-form-the-largest-square | Counter for min, 97% speed | EvgenySH | 0 | 42 | number of rectangles that can form the largest square | 1,725 | 0.787 | Easy | 24,945 |
https://leetcode.com/problems/number-of-rectangles-that-can-form-the-largest-square/discuss/1326202/Easy-Python-Solution | class Solution:
def countGoodRectangles(self, rectangles: List[List[int]]) -> int:
arr=[]
count=0
for i in rectangles:
arr.append(min(i))
MAX=max(arr)
for i in arr:
if MAX==i:
count+=1
return coun | number-of-rectangles-that-can-form-the-largest-square | Easy Python Solution | sangam92 | 0 | 43 | number of rectangles that can form the largest square | 1,725 | 0.787 | Easy | 24,946 |
https://leetcode.com/problems/number-of-rectangles-that-can-form-the-largest-square/discuss/1140199/Python3-Simple-Solution-with-94-better-running-time | class Solution:
def countGoodRectangles(self, rectangles: List[List[int]]) -> int:
mins = [min(rectangle) for rectangle in rectangles] #storing the minimum dimension of each rectangle
return mins.count(max(mins)) #returning the number of occurrences of the maximum element in the list | number-of-rectangles-that-can-form-the-largest-square | Python3 Simple Solution with 94% better running time | bPapan | 0 | 54 | number of rectangles that can form the largest square | 1,725 | 0.787 | Easy | 24,947 |
https://leetcode.com/problems/number-of-rectangles-that-can-form-the-largest-square/discuss/1113627/Python-oror-Simple-2-Liner | class Solution:
def countGoodRectangles(self, rectangles: List[List[int]]) -> int:
largest = max([min(k) for k in rectangles])
return len([k for k in rectangles if largest in k and k[0]>=largest and k[1]>=largest]) | number-of-rectangles-that-can-form-the-largest-square | Python || Simple 2 Liner | bharatgg | 0 | 23 | number of rectangles that can form the largest square | 1,725 | 0.787 | Easy | 24,948 |
https://leetcode.com/problems/number-of-rectangles-that-can-form-the-largest-square/discuss/1080807/easy-simple-python-code | class Solution:
def countGoodRectangles(self, rectangles: List[List[int]]) -> int:
res=[]
for i in rectangles:
res.append(min(i))
z=max(max(res),min(i))
return res.count(z) | number-of-rectangles-that-can-form-the-largest-square | easy simple python code | yashwanthreddz | 0 | 30 | number of rectangles that can form the largest square | 1,725 | 0.787 | Easy | 24,949 |
https://leetcode.com/problems/number-of-rectangles-that-can-form-the-largest-square/discuss/1029023/Python-3-easy-to-understand-and-faster-than-98.66 | class Solution:
def countGoodRectangles(self, rectangles: List[List[int]]) -> int:
array = []
for r in rectangles:
array.append(min(r))
return array.count(max(array)) | number-of-rectangles-that-can-form-the-largest-square | Python 3 easy to understand and faster than 98.66% | WiseLin | 0 | 59 | number of rectangles that can form the largest square | 1,725 | 0.787 | Easy | 24,950 |
https://leetcode.com/problems/number-of-rectangles-that-can-form-the-largest-square/discuss/1020891/Python3-2-lines-O(n) | class Solution:
def countGoodRectangles(self, rectangles: List[List[int]]) -> int:
maxLen = [min(rectangle) for rectangle in rectangles]
return maxLen.count(max(maxLen)) | number-of-rectangles-that-can-form-the-largest-square | Python3, 2 lines, O(n) | kwy518 | 0 | 20 | number of rectangles that can form the largest square | 1,725 | 0.787 | Easy | 24,951 |
https://leetcode.com/problems/number-of-rectangles-that-can-form-the-largest-square/discuss/1123527/WEEB-DOES-PYTHON-WITH-99.41-SPEED | class Solution:
def countGoodRectangles(self, rectangles: List[List[int]]) -> int:
maxlen = -float("inf")
count = 1
for i in range(len(rectangles)):
cur_max = min(rectangles[i])
if cur_max > maxlen:
maxlen = cur_max
count = 1
elif cur_max == maxlen:
count+=1
return count | number-of-rectangles-that-can-form-the-largest-square | WEEB DOES PYTHON WITH 99.41% SPEED | Skywalker5423 | -1 | 72 | number of rectangles that can form the largest square | 1,725 | 0.787 | Easy | 24,952 |
https://leetcode.com/problems/number-of-rectangles-that-can-form-the-largest-square/discuss/1241884/python-easy | class Solution:
def countGoodRectangles(self, r: List[List[int]]) -> int:
an=0
ans=0
for j in r:
a=min(j)
if a > an:
an= a
ans=1
elif a==an:
ans+=1
return ans | number-of-rectangles-that-can-form-the-largest-square | python easy | chikushen99 | -2 | 59 | number of rectangles that can form the largest square | 1,725 | 0.787 | Easy | 24,953 |
https://leetcode.com/problems/tuple-with-same-product/discuss/1020657/Python3-freq-table | class Solution:
def tupleSameProduct(self, nums: List[int]) -> int:
ans = 0
freq = {}
for i in range(len(nums)):
for j in range(i+1, len(nums)):
key = nums[i] * nums[j]
ans += freq.get(key, 0)
freq[key] = 1 + freq.get(key, 0)
return 8*ans | tuple-with-same-product | [Python3] freq table | ye15 | 31 | 2,100 | tuple with same product | 1,726 | 0.608 | Medium | 24,954 |
https://leetcode.com/problems/tuple-with-same-product/discuss/1020621/Simple-Python3-or-6-Lines-or-Detailed-Explanation | class Solution:
def tupleSameProduct(self, nums: List[int]) -> int:
count, ans, n = collections.Counter(), 0, len(nums)
for i in range(n):
for j in range(i+1, n):
ans += 8 * count[nums[i]*nums[j]]
count[nums[i]*nums[j]] += 1
return ans | tuple-with-same-product | Simple Python3 | 6 Lines | Detailed Explanation | sushanthsamala | 13 | 972 | tuple with same product | 1,726 | 0.608 | Medium | 24,955 |
https://leetcode.com/problems/tuple-with-same-product/discuss/1020745/Python-Hashmap-with-explanation | class Solution:
def tupleSameProduct(self, nums: List[int]) -> int:
product_count = collections.defaultdict(int)
n = len(nums)
for i in range(n-1):
for j in range(i+1, n):
product = nums[i] * nums[j]
product_count[product] += 1
res = 0
for k, v in product_count.items():
if v > 1:
res += (v*(v-1)//2) * (2**3)
return res | tuple-with-same-product | [Python] Hashmap with explanation | SonicM | 10 | 519 | tuple with same product | 1,726 | 0.608 | Medium | 24,956 |
https://leetcode.com/problems/tuple-with-same-product/discuss/1470720/Dictionary-of-Python-and-small-maths | class Solution:
def tupleSameProduct(self, nums: List[int]) -> int:
hasmap = collections.defaultdict(int)
n = len(nums)
for i in range(n):
for j in range(i+1,n):
hasmap[nums[i]*nums[j]] += 1
ans = 0
for val in hasmap.values():
ans += (8*val*(val-1))//2
return ans | tuple-with-same-product | Dictionary of Python and small maths | Sanjaychandak95 | 1 | 66 | tuple with same product | 1,726 | 0.608 | Medium | 24,957 |
https://leetcode.com/problems/tuple-with-same-product/discuss/2284299/Python-Easy-to-Understand | class Solution:
def tupleSameProduct(self, nums: List[int]) -> int:
temp = []
for i in range(len(nums)):
for j in range(i+1, len(nums)):
temp.append(nums[i] * nums[j])
temp = collections.Counter(temp)
ans = 0
for i, j in temp.items():
if j >= 2:
ans += j * (j-1) // 2
return ans * 8 | tuple-with-same-product | Python Easy to Understand | G_Venkatesh | 0 | 50 | tuple with same product | 1,726 | 0.608 | Medium | 24,958 |
https://leetcode.com/problems/tuple-with-same-product/discuss/1439786/Python3-solution-using-dictionary | class Solution:
def tupleSameProduct(self, nums: List[int]) -> int:
d = {}
for i in range(len(nums)-1):
for j in range(i+1,len(nums)):
d[nums[i]*nums[j]] = d.get(nums[i]*nums[j],[]) + [nums[i],nums[j]]
count = 0
for i,j in d.items():
x = len(j)//2
count += 8*(x*(x-1)//2)
return count | tuple-with-same-product | Python3 solution using dictionary | EklavyaJoshi | 0 | 54 | tuple with same product | 1,726 | 0.608 | Medium | 24,959 |
https://leetcode.com/problems/tuple-with-same-product/discuss/1059766/Python-Hashmap-or-Optimized-space-or-O(N2)-Time-O(N)-Space-or-95-%2B-85 | class Solution:
def tupleSameProduct(self, nums: List[int]) -> int:
hmap = {}
output = 0
for i in range(len(nums)):
for j in range(i):
# Skip if same number
if i == j:
continue
candidate = nums[i] * nums[j]
if candidate in hmap:
curLen = len(hmap[candidate])
output += curLen * 8
hmap[candidate].append([nums[i], nums[j]])
else:
hmap[candidate] = []
hmap[candidate].append([nums[i], nums[j]])
return output | tuple-with-same-product | [Python] Hashmap | Optimized space | O(N^2) Time O(N) Space | 95% + 85% | jayzern | 0 | 106 | tuple with same product | 1,726 | 0.608 | Medium | 24,960 |
https://leetcode.com/problems/tuple-with-same-product/discuss/1059766/Python-Hashmap-or-Optimized-space-or-O(N2)-Time-O(N)-Space-or-95-%2B-85 | class Solution:
def tupleSameProduct(self, nums: List[int]) -> int:
hmap = {}
output = 0
for i in range(len(nums)):
for j in range(i):
# Skip if same number
if i == j:
continue
candidate = nums[i] * nums[j]
if candidate in hmap:
output += hmap[candidate] * 8
hmap[candidate] += 1
else:
hmap[candidate] = 1
return output | tuple-with-same-product | [Python] Hashmap | Optimized space | O(N^2) Time O(N) Space | 95% + 85% | jayzern | 0 | 106 | tuple with same product | 1,726 | 0.608 | Medium | 24,961 |
https://leetcode.com/problems/largest-submatrix-with-rearrangements/discuss/1020589/Simple-Python3-or-9-Lines-or-Beats-100-or-Detailed-Explanation | class Solution:
def largestSubmatrix(self, matrix: List[List[int]]) -> int:
m, n, ans = len(matrix), len(matrix[0]), 0
for j in range(n):
for i in range(1, m):
matrix[i][j] += matrix[i-1][j] if matrix[i][j] else 0
for i in range(m):
matrix[i].sort(reverse=1)
for j in range(n):
ans = max(ans, (j+1)*matrix[i][j])
return ans | largest-submatrix-with-rearrangements | Simple Python3 | 9 Lines | Beats 100% | Detailed Explanation | sushanthsamala | 9 | 627 | largest submatrix with rearrangements | 1,727 | 0.61 | Medium | 24,962 |
https://leetcode.com/problems/largest-submatrix-with-rearrangements/discuss/1020779/Python3-Faster-than-100-Easy-Explanation-%2B-Comments | class Solution:
def largestSubmatrix(self, matrix: List[List[int]]) -> int:
d = {} # dictionary storing row number and corresponding list of the number of ones
m, n = len(matrix), len(matrix[0])
for col in range(n): # for each column
start = -1 # start is initialized to -1, when we will encounter streak ones it will be initialized
for row in range(m):
if matrix[row][col]: # when the cell contains 1
if start == -1: # when the first one is encountered
start = row # set start to the row number
else: # when the cell contains a 0
if start!=-1: # if there was a streak ones encountered before
end = row
for row_index in range(start, end):
# iterate over the beginning of the streak till the end
# for each row index in the streak assign the key to be row index and the corresponding length of streak starting from that point.
if row_index not in d: # if the row index is not present in the dictionary
d[row_index] = [] # create an empty list for the row index
d[row_index].append(end - row_index) # append the length of the streak from the row index
start = -1 # re-initialize start to -1 as the streak is over
if start!=-1: # if the column has ended but the streak was present uptil the end
# repeat the same process we did above with an exception, end = m
end = m
for row_index in range(start, end):
if row_index not in d:
d[row_index] = []
d[row_index].append(end - row_index)
## finding the max area
area = 0 # initialize area to be 0
for key in d: # for each key -> row index
l = sorted(d[key], reverse = True) # sort the list of streak lengths
ht = l[0] # initialize height with the max height
for i in range(len(l)): # iterate over the list
ht = min(ht, l[i]) # maximum height possible
width = i + 1 # width = i + 1
area = max(area, ht*width) # area = height x width
return area | largest-submatrix-with-rearrangements | [Python3] Faster than 100% - Easy [Explanation + Comments] | mihirrane | 2 | 226 | largest submatrix with rearrangements | 1,727 | 0.61 | Medium | 24,963 |
https://leetcode.com/problems/largest-submatrix-with-rearrangements/discuss/1020779/Python3-Faster-than-100-Easy-Explanation-%2B-Comments | class Solution:
def largestSubmatrix(self, matrix: List[List[int]]) -> int:
m,n = len(matrix), len(matrix[0])
res = 0
dp = [0]*n
for i in range(m):
for j in range(n):
dp[j] = matrix[i][j]*(dp[j] + 1)
cnt = 1
for x in sorted(dp, reverse = True):
res = max(x*cnt, res)
cnt += 1
return res | largest-submatrix-with-rearrangements | [Python3] Faster than 100% - Easy [Explanation + Comments] | mihirrane | 2 | 226 | largest submatrix with rearrangements | 1,727 | 0.61 | Medium | 24,964 |
https://leetcode.com/problems/largest-submatrix-with-rearrangements/discuss/1020679/Python3-histogram-model | class Solution:
def largestSubmatrix(self, matrix: List[List[int]]) -> int:
m, n = len(matrix), len(matrix[0]) # dimensions
ans = 0
hist = [0] * n
for i in range(m):
for j in range(n):
hist[j] = hist[j] + 1 if matrix[i][j] else 0
for i, x in enumerate(sorted(hist, reverse=True)):
ans = max(ans, x*(i+1))
return ans | largest-submatrix-with-rearrangements | [Python3] histogram model | ye15 | 1 | 136 | largest submatrix with rearrangements | 1,727 | 0.61 | Medium | 24,965 |
https://leetcode.com/problems/cat-and-mouse-ii/discuss/1020616/Python3-Clean-and-Commented-Top-down-DP-with-the-early-stopping-trick | class Solution:
def canMouseWin(self, grid: List[str], catJump: int, mouseJump: int) -> bool:
dirs = [[1, 0], [-1, 0], [0, 1], [0, -1]]
m, n = len(grid), len(grid[0])
mouse_pos = cat_pos = None
available = 0 # available steps for mouse and cat
# Search the start pos of mouse and cat
for i in range(m):
for j in range(n):
if grid[i][j] != '#':
available += 1
if grid[i][j] == 'M':
mouse_pos = (i, j)
elif grid[i][j] == 'C':
cat_pos = (i, j)
@functools.lru_cache(None)
def dp(turn, mouse_pos, cat_pos):
# if turn == m * n * 2:
# We already search the whole grid (9372 ms 74.3 MB)
if turn == available * 2:
# We already search the whole touchable grid (5200 ms 57.5 MB)
return False
if turn % 2 == 0:
# Mouse
i, j = mouse_pos
for di, dj in dirs:
for jump in range(mouseJump + 1):
# Note that we want to do range(mouseJump + 1) instead of range(1, mouseJump + 1)
# considering the case that we can stay at the same postion for next turn.
new_i, new_j = i + di * jump, j + dj * jump
if 0 <= new_i < m and 0 <= new_j < n and grid[new_i][new_j] != '#':
# Valid pos
if dp(turn + 1, (new_i, new_j), cat_pos) or grid[new_i][new_j] == 'F':
return True
else:
# Stop extending the jump since we cannot go further
break
return False
else:
# Cat
i, j = cat_pos
for di, dj in dirs:
for jump in range(catJump + 1):
new_i, new_j = i + di * jump, j + dj * jump
if 0 <= new_i < m and 0 <= new_j < n and grid[new_i][new_j] != '#':
if not dp(turn + 1, mouse_pos, (new_i, new_j)) or (new_i, new_j) == mouse_pos or grid[new_i][new_j] == 'F':
# This condition will also handle the case that the cat cannot jump through the mouse
return False
else:
break
return True
return dp(0, mouse_pos, cat_pos) | cat-and-mouse-ii | Python3 Clean & Commented Top-down DP with the early stopping trick | GBLin5566 | 48 | 4,000 | cat and mouse ii | 1,728 | 0.402 | Hard | 24,966 |
https://leetcode.com/problems/cat-and-mouse-ii/discuss/1020953/Python3-dp | class Solution:
def canMouseWin(self, grid: List[str], catJump: int, mouseJump: int) -> bool:
m, n = len(grid), len(grid[0]) # dimensions
walls = set()
for i in range(m):
for j in range(n):
if grid[i][j] == "F": food = (i, j)
elif grid[i][j] == "C": cat = (i, j)
elif grid[i][j] == "M": mouse = (i, j)
elif grid[i][j] == "#": walls.add((i, j))
@lru_cache(None)
def fn(cat, mouse, turn):
"""Return True if mouse wins."""
if cat == food or cat == mouse or turn >= m*n*2: return False
if mouse == food: return True # mouse reaching food
if not turn & 1: # mouse moving
x, y = mouse
for dx, dy in (-1, 0), (0, 1), (1, 0), (0, -1):
for jump in range(0, mouseJump+1):
xx, yy = x+jump*dx, y+jump*dy
if not (0 <= xx < m and 0 <= yy < n) or (xx, yy) in walls: break
if fn(cat, (xx, yy), turn+1): return True
return False
else: # cat moving
x, y = cat
for dx, dy in (-1, 0), (0, 1), (1, 0), (0, -1):
for jump in range(0, catJump+1):
xx, yy = x+jump*dx, y+jump*dy
if not (0 <= xx < m and 0 <= yy < n) or (xx, yy) in walls: break
if not fn((xx, yy), mouse, turn+1): return False
return True
return fn(cat, mouse, 0) | cat-and-mouse-ii | [Python3] dp | ye15 | 3 | 255 | cat and mouse ii | 1,728 | 0.402 | Hard | 24,967 |
https://leetcode.com/problems/find-the-highest-altitude/discuss/1223440/24ms-Python-(with-comments) | class Solution(object):
def largestAltitude(self, gain):
"""
:type gain: List[int]
:rtype: int
"""
#initialize a variable to store the end output
result = 0
#initialize a variable to keep track of the altitude at each iteration
current_altitude=0
#looping through each of the gains
for g in gain:
#updating the current altitude based on the gain
current_altitude += g
#if the current altitude is greater than the highest altitude recorded then assign it as the result. This done iteratively, allows us to find the highest altitude
if current_altitude > result:
result = current_altitude
return result | find-the-highest-altitude | 24ms, Python (with comments) | Akshar-code | 7 | 575 | find the highest altitude | 1,732 | 0.787 | Easy | 24,968 |
https://leetcode.com/problems/find-the-highest-altitude/discuss/2047584/Easy-python-solution | class Solution:
def largestAltitude(self, gain: List[int]) -> int:
ans=[0]
for i in range(len(gain)):
ans.append(ans[i]+gain[i])
return max(ans) | find-the-highest-altitude | Easy python solution | tusharkhanna575 | 5 | 136 | find the highest altitude | 1,732 | 0.787 | Easy | 24,969 |
https://leetcode.com/problems/find-the-highest-altitude/discuss/1866677/Python-easy-to-read-and-understand | class Solution:
def largestAltitude(self, gain: List[int]) -> int:
ans = max(0, gain[0])
for i in range(1, len(gain)):
gain[i] = gain[i-1] + gain[i]
if gain[i] > ans:
ans = gain[i]
return ans | find-the-highest-altitude | Python easy to read and understand | sanial2001 | 1 | 48 | find the highest altitude | 1,732 | 0.787 | Easy | 24,970 |
https://leetcode.com/problems/find-the-highest-altitude/discuss/1862067/Python-(Simple-Approach-and-Beginner-Friendly) | class Solution:
def largestAltitude(self, gain: List[int]) -> int:
new_arr = [0]
a = 0
for i in gain:
a+=i
new_arr.append(a)
return max(new_arr) | find-the-highest-altitude | Python (Simple Approach and Beginner-Friendly) | vishvavariya | 1 | 52 | find the highest altitude | 1,732 | 0.787 | Easy | 24,971 |
https://leetcode.com/problems/find-the-highest-altitude/discuss/1609688/Python-3-oror-Prefix-Sum-based-approach-oror-O(n)-time-oror-O(1)-space | class Solution:
def largestAltitude(self, gain: List[int]) -> int:
high = max(0,gain[0])
tmp = gain[0]
for i in range(1,len(gain)):
tmp += gain[i]
high = max(tmp,high)
return high | find-the-highest-altitude | Python 3 || Prefix Sum based approach || O(n) time || O(1) space | s_m_d_29 | 1 | 90 | find the highest altitude | 1,732 | 0.787 | Easy | 24,972 |
https://leetcode.com/problems/find-the-highest-altitude/discuss/1361594/PYTHON-Simple-and-Straightforward.-Explained-without-using-inbuilt-functions.-O(1)-SC | class Solution:
def largestAltitude(self, gain: List[int]) -> int:
"""
Intuition is to iterate through the list and keep adding
previous element. for 1st element previous element is 0.
and at the end return largest element encountered.
To optimize it I have not initialised a new list instead
maintained a variable h_alt to store the largest
element encountered. This brings down space complexity to O(1).
And since we are iterating through the list once time
complexity is O(n).
Time complexity : O(n)
Space complexity: O(1)
"""
h_alt = next_alt = 0
for i,v in enumerate(gain):
next_alt = next_alt + v
if next_alt > h_alt:
h_alt = next_alt
return h_alt | find-the-highest-altitude | [PYTHON] Simple & Straightforward. Explained without using inbuilt functions. O(1) SC | er1shivam | 1 | 282 | find the highest altitude | 1,732 | 0.787 | Easy | 24,973 |
https://leetcode.com/problems/find-the-highest-altitude/discuss/1219087/Python-3-Easy-to-understand-by-a-NOOB.-!! | class Solution:
def largestAltitude(self, gain: List[int]) -> int:
nums =[0]
for i in range(len(gain)):
num = nums[i] + gain[i]
nums.append(num)
return max(nums)
''' | find-the-highest-altitude | Python 3 Easy to understand by a NOOB. !! | joelG24 | 1 | 111 | find the highest altitude | 1,732 | 0.787 | Easy | 24,974 |
https://leetcode.com/problems/find-the-highest-altitude/discuss/1038061/Python-3-Short-One-Pass-Solution-(30ms) | class Solution:
def largestAltitude(self, gain: List[int]) -> int:
arr = [0, gain[0]] # Initialise array.
for i in range(1, len(gain)):
arr.append(arr[i] + gain[i]) # Compute sum and append.
return max(arr) | find-the-highest-altitude | [Python 3] - Short One Pass Solution (30ms) | mb557x | 1 | 165 | find the highest altitude | 1,732 | 0.787 | Easy | 24,975 |
https://leetcode.com/problems/find-the-highest-altitude/discuss/2850359/Easy-Python-Solution-1732.-Find-the-Highest-Altitude | class Solution:
def largestAltitude(self, gain: List[int]) -> int:
ans = []
gain.insert(0, 0)
for i in range(1, int(len(gain))):
gain[i] = gain[i-1] + gain[i]
return max(gain) | find-the-highest-altitude | ✅ Easy Python Solution - 1732. Find the Highest Altitude | Brian_Daniel_Thomas | 0 | 1 | find the highest altitude | 1,732 | 0.787 | Easy | 24,976 |
https://leetcode.com/problems/find-the-highest-altitude/discuss/2838550/Python-Solution-Faster-than-63-of-solutions | class Solution:
def largestAltitude(self, gain: list[int]):
altitudes = []
altitudes.append(0)
for i in range(1, len(gain) + 1):
sum = altitudes[i - 1] + gain[i - 1]
altitudes.append(sum)
return max(altitudes) | find-the-highest-altitude | Python Solution - Faster than 63% of solutions | heli_kolambekar | 0 | 1 | find the highest altitude | 1,732 | 0.787 | Easy | 24,977 |
https://leetcode.com/problems/find-the-highest-altitude/discuss/2833763/Python-or-Easy-Solution-or-Loops-or-Lists | class Solution:
def largestAltitude(self, gain: List[int]) -> int:
alti = [0]
curr = 0
for i in gain:
alti.append(curr+i)
curr += i
return max(alti) | find-the-highest-altitude | Python | Easy Solution | Loops | Lists | atharva77 | 0 | 1 | find the highest altitude | 1,732 | 0.787 | Easy | 24,978 |
https://leetcode.com/problems/find-the-highest-altitude/discuss/2790465/Python3-Simple-Solution | class Solution:
def largestAltitude(self, gain: List[int]) -> int:
alt_points = [0]
current_alt = 0
for i in range(len(gain)):
current_alt += gain[i]
alt_points.append(current_alt)
return max(alt_points) | find-the-highest-altitude | Python3 Simple Solution | curtiswyman123 | 0 | 4 | find the highest altitude | 1,732 | 0.787 | Easy | 24,979 |
https://leetcode.com/problems/find-the-highest-altitude/discuss/2774654/Easy-Python-Solution | class Solution:
def largestAltitude(self, gain: List[int]) -> int:
lst =[0]
for i in range(len(gain)):
lst.append(lst[-1] + gain[i])
return max(lst) | find-the-highest-altitude | Easy Python Solution | danishs | 0 | 3 | find the highest altitude | 1,732 | 0.787 | Easy | 24,980 |
https://leetcode.com/problems/find-the-highest-altitude/discuss/2744972/Python-3-or-Find-Minimum | class Solution:
def largestAltitude(self, gain: List[int]) -> int:
high,current = 0,0
while len(gain)>0:
current += gain.pop(0)
if current>high: high = current
return high | find-the-highest-altitude | Python 3 | Find Minimum | keioon | 0 | 2 | find the highest altitude | 1,732 | 0.787 | Easy | 24,981 |
https://leetcode.com/problems/find-the-highest-altitude/discuss/2733135/1732.-Find-the-Highest-Altitude | class Solution:
def largestAltitude(self, gain: List[int]) -> int:
n = len(gain)
res = [0]
Max = 0
for i in range (len(gain)):
temp = res[i] + gain[i]
res.append(temp)
Max = max(Max,temp)
return Max
#TC: O(n), SC: O(1) | find-the-highest-altitude | 1732. Find the Highest Altitude | rishabh_055 | 0 | 1 | find the highest altitude | 1,732 | 0.787 | Easy | 24,982 |
https://leetcode.com/problems/find-the-highest-altitude/discuss/2726670/Python-easy-solutionoror-36ms-runtime | class Solution:
def largestAltitude(self, gain: List[int]) -> int:
length=len(gain)
altitude=[]
altitude.append(0)
for i in range(length):
altitude.append(gain[i]+altitude[i])
#print(altitude)
return max(altitude) | find-the-highest-altitude | Python easy solution|| 36ms runtime | deepali_04 | 0 | 3 | find the highest altitude | 1,732 | 0.787 | Easy | 24,983 |
https://leetcode.com/problems/find-the-highest-altitude/discuss/2726046/Python-oror-Simple-Approach-oror-Beats-99 | class Solution:
def largestAltitude(self, gain: List[int]) -> int:
gain.insert(0,0)
for i in range(1,len(gain)):
gain[i]=gain[i-1]+gain[i]
return max(gain) | find-the-highest-altitude | Python || Simple Approach || Beats 99% | shivammenda2002 | 0 | 2 | find the highest altitude | 1,732 | 0.787 | Easy | 24,984 |
https://leetcode.com/problems/find-the-highest-altitude/discuss/2648612/Pyhton3-Solution-oror-Easy-and-Simple-oror-O(N) | class Solution:
def largestAltitude(self, gain: List[int]) -> int:
new = []
new.append(0)
for i in range(len(gain)):
new.append(new[-1]+gain[i])
return max(new) | find-the-highest-altitude | Pyhton3 Solution || Easy & Simple || O(N) | shashank_shashi | 0 | 14 | find the highest altitude | 1,732 | 0.787 | Easy | 24,985 |
https://leetcode.com/problems/find-the-highest-altitude/discuss/2627107/Python3-or-Solved-Using-Prefix-Sum-Using-a-Counter-Variable-and-Did-it-in-O(N)-Time-and-O(1)-Space! | class Solution:
#Let n = len(gain)!
#Time-Complexity: O(n)
#Space-Complexity: O(1)
def largestAltitude(self, gain: List[int]) -> int:
#Approach: Utilize prefix sum on the gain input array in order to cumulatively
#take account changes for each and every gain and calculate each point's height!
#We will do this by utilizing a counter!
#As you are doing so, keep track of maximum altitude seen so far!
#At the end of linear traversal, you should have the answer!
#initialize these variables!
counter = 0
max_seen_so_far = 0
#loop through each gain!
for g in gain:
counter += g
max_seen_so_far = max(max_seen_so_far, counter)
return max_seen_so_far | find-the-highest-altitude | Python3 | Solved Using Prefix Sum Using a Counter Variable and Did it in O(N) Time and O(1) Space! | JOON1234 | 0 | 7 | find the highest altitude | 1,732 | 0.787 | Easy | 24,986 |
https://leetcode.com/problems/find-the-highest-altitude/discuss/2619045/PYTHON3-EXTREMELY-CLEANSIMPLEEASY-SOLUTION | class Solution:
def largestAltitude(self, gain: List[int]) -> int:
alt = []
val = 0
largest = 0
for i in range(len(gain)):
val += gain[i]
alt.append(val)
for j in alt:
if j > largest:
largest = j
return largest | find-the-highest-altitude | 🔥PYTHON3 EXTREMELY CLEAN/SIMPLE/EASY SOLUTION🔥 | YuviGill | 0 | 31 | find the highest altitude | 1,732 | 0.787 | Easy | 24,987 |
https://leetcode.com/problems/find-the-highest-altitude/discuss/2583109/SIMPLE-PYTHON3-SOLUTION-easy-to-understand | class Solution:
def largestAltitude(self, gain: List[int]) -> int:
res = [0]
for i in range(len(gain)):
res.append(res[-1] + gain[i])
return max(res) | find-the-highest-altitude | ✅✔ SIMPLE PYTHON3 SOLUTION ✅✔ easy to understand | rajukommula | 0 | 21 | find the highest altitude | 1,732 | 0.787 | Easy | 24,988 |
https://leetcode.com/problems/find-the-highest-altitude/discuss/2489191/Python-simple-solution | class Solution:
def largestAltitude(self, gain: List[int]) -> int:
start = 0
res = [0]
for i in gain:
start += i
res.append(start)
return max(res) | find-the-highest-altitude | Python simple solution | aruj900 | 0 | 25 | find the highest altitude | 1,732 | 0.787 | Easy | 24,989 |
https://leetcode.com/problems/find-the-highest-altitude/discuss/2421618/Easy-python-solution | class Solution:
def largestAltitude(self, gain: List[int]) -> int:
li_altitude = [0, gain[0]]
count_altitudes = gain[0]
for altitude in range(len(gain) - 1):
count_altitudes += gain[altitude+1]
li_altitude.append(count_altitudes)
return max(li_altitude) | find-the-highest-altitude | Easy python solution | samanehghafouri | 0 | 9 | find the highest altitude | 1,732 | 0.787 | Easy | 24,990 |
https://leetcode.com/problems/find-the-highest-altitude/discuss/2401735/Python-in-Easy-Way-O(N) | class Solution:
def largestAltitude(self, gain: List[int]) -> int:
height, maxh = 0, 0
for i in gain:
height += i
maxh = max(maxh, height)
return maxh | find-the-highest-altitude | Python in Easy Way O(N) | YangJenHao | 0 | 20 | find the highest altitude | 1,732 | 0.787 | Easy | 24,991 |
https://leetcode.com/problems/find-the-highest-altitude/discuss/2399432/98-FASTER | class Solution:
def largestAltitude(self, gain: List[int]) -> int:
gain.insert(0,0)
for i in range(1,len(gain)):gain[i]=gain[i-1]+gain[i]
return max(gain) | find-the-highest-altitude | 98% FASTER | keertika27 | 0 | 13 | find the highest altitude | 1,732 | 0.787 | Easy | 24,992 |
https://leetcode.com/problems/find-the-highest-altitude/discuss/2347964/Python-23-ms-solution | class Solution:
def largestAltitude(self, gain: List[int]) -> int:
highest = gain[0]
for i in range(1,len(gain)):
gain[i] += gain[i-1]
highest = max(gain[i], highest)
return max(0, highest) | find-the-highest-altitude | Python 23 ms solution | hochunlin | 0 | 18 | find the highest altitude | 1,732 | 0.787 | Easy | 24,993 |
https://leetcode.com/problems/find-the-highest-altitude/discuss/2313057/Python-99.23-faster-or-Simplest-solution-with-explanation-or-Beg-to-Adv-or-Prefix-Sum | class Solution:
def largestAltitude(self, gain: List[int]) -> int:
res = [ ] # taking a list to save the resulting elem after performing our logic.
elem = nums[0] # assigning first element of nums in an element.
for i in range(1,len(nums)): # running a loop from 1 as we already added first element of nums in resulting list.
res.append(elem) # appending first element in the resulting list, as per the requirement(that first elem of nums should be there)
elem += nums[i] # adding nums element in the previous nums element.
res.append(elem) # appnding the sum in the resulting list.
return max(res) # returning max of the list, as we have to Return the highest altitude of a point. | find-the-highest-altitude | Python 99.23% faster | Simplest solution with explanation | Beg to Adv | Prefix Sum | rlakshay14 | 0 | 33 | find the highest altitude | 1,732 | 0.787 | Easy | 24,994 |
https://leetcode.com/problems/find-the-highest-altitude/discuss/2125367/python-solution-easy | class Solution:
def largestAltitude(self, gain: List[int]) -> int:
res=[0]
for i in range(len(gain)):
res.append(res[i]+gain[i])
return max(res) | find-the-highest-altitude | python solution easy | anil5829354 | 0 | 16 | find the highest altitude | 1,732 | 0.787 | Easy | 24,995 |
https://leetcode.com/problems/find-the-highest-altitude/discuss/2092000/Python-solution-simple | class Solution:
def largestAltitude(self, gain: List[int]) -> int:
res, height = 0, 0
for i in range(len(gain)):
height += gain[i]
res = max(res, height)
return res | find-the-highest-altitude | Python solution simple | shreeruparel | 0 | 32 | find the highest altitude | 1,732 | 0.787 | Easy | 24,996 |
https://leetcode.com/problems/find-the-highest-altitude/discuss/1915821/Very-easy-and-using-DP-solve-the-problem | class Solution:
def largestAltitude(self, gain: List[int]) -> int:
dp = [0] * (len(gain) + 1)
for index in range(1, len(gain)+1):
dp[index] = dp[index - 1] + gain[index-1]
return max(dp) | find-the-highest-altitude | Very easy and using DP solve the problem | shreeyansh | 0 | 27 | find the highest altitude | 1,732 | 0.787 | Easy | 24,997 |
https://leetcode.com/problems/find-the-highest-altitude/discuss/1847898/Python-dollarolution | class Solution:
def largestAltitude(self, gain: List[int]) -> int:
count, maximum = 0, 0
for i in gain:
count += i
if count > maximum:
maximum = count
return maximum | find-the-highest-altitude | Python $olution | AakRay | 0 | 24 | find the highest altitude | 1,732 | 0.787 | Easy | 24,998 |
https://leetcode.com/problems/find-the-highest-altitude/discuss/1829261/1-Line-Python-Solution-oror-50-Faster-oror-Memory-less-than-50 | class Solution:
def largestAltitude(self, gain: List[int]) -> int:
return max([0]+[sum(gain[:i+1]) for i in range(len(gain))]) | find-the-highest-altitude | 1-Line Python Solution || 50% Faster || Memory less than 50% | Taha-C | 0 | 29 | find the highest altitude | 1,732 | 0.787 | Easy | 24,999 |
Subsets and Splits
Top 2 Solutions by Upvotes
Identifies the top 2 highest upvoted Python solutions for each problem, providing insight into popular approaches.