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/minimum-elements-to-add-to-form-a-given-sum/discuss/1107126/Python-Greedy-Solution-Without-using-Loop | class Solution:
def minElements(self, nums: List[int], limit: int, goal: int) -> int:
s = sum(nums)
if s == goal :
return 0
val = abs(goal - s)
if val <= limit :
return 1
q = val // limit
r = val % limit
if r == 0 :
return q
return q + 1 | minimum-elements-to-add-to-form-a-given-sum | Python Greedy Solution Without using Loop | jainabhi128 | 0 | 49 | minimum elements to add to form a given sum | 1,785 | 0.424 | Medium | 25,600 |
https://leetcode.com/problems/minimum-elements-to-add-to-form-a-given-sum/discuss/1103151/Easy-python3-100-timeandspace | class Solution:
def minElements(self, nums: List[int], limit: int, goal: int) -> int:
total = sum(nums)
diff = goal - total
ans=0
ans, rem = divmod(abs(diff),limit)
return ans+1 if rem!=0 else ans | minimum-elements-to-add-to-form-a-given-sum | Easy python3 100% time&space | harshitCode13 | 0 | 57 | minimum elements to add to form a given sum | 1,785 | 0.424 | Medium | 25,601 |
https://leetcode.com/problems/minimum-elements-to-add-to-form-a-given-sum/discuss/1100467/Easy-one-line-python3-beats-100 | class Solution:
def minElements(self, nums: List[int], limit: int, goal: int) -> int:
return abs(goal-sum(nums))//limit+(abs(goal-sum(nums))%limit!=0)*1 | minimum-elements-to-add-to-form-a-given-sum | Easy one line python3 beats 100% | svr300 | 0 | 32 | minimum elements to add to form a given sum | 1,785 | 0.424 | Medium | 25,602 |
https://leetcode.com/problems/number-of-restricted-paths-from-first-to-last-node/discuss/1097219/Python3-Dijkstra-%2B-dp | class Solution:
def countRestrictedPaths(self, n: int, edges: List[List[int]]) -> int:
graph = {} # graph as adjacency list
for u, v, w in edges:
graph.setdefault(u, []).append((v, w))
graph.setdefault(v, []).append((u, w))
queue = [n]
dist = {n: 0}
while queue:
newq = []
for u in queue:
for v, w in graph[u]:
if v not in dist or dist[u] + w < dist[v]:
dist[v] = dist[u] + w
newq.append(v)
queue = newq
@cache
def fn(u):
"""Return number of restricted paths from u to n."""
if u == n: return 1 # boundary condition
ans = 0
for v, _ in graph[u]:
if dist[u] > dist[v]: ans += fn(v)
return ans
return fn(1) % 1_000_000_007 | number-of-restricted-paths-from-first-to-last-node | [Python3] Dijkstra + dp | ye15 | 4 | 401 | number of restricted paths from first to last node | 1,786 | 0.393 | Medium | 25,603 |
https://leetcode.com/problems/number-of-restricted-paths-from-first-to-last-node/discuss/1097219/Python3-Dijkstra-%2B-dp | class Solution:
def countRestrictedPaths(self, n: int, edges: List[List[int]]) -> int:
graph = {} # graph as adjacency list
for u, v, w in edges:
graph.setdefault(u-1, []).append((v-1, w))
graph.setdefault(v-1, []).append((u-1, w))
# dijkstra's algo
pq = [(0, n-1)]
dist = [inf]*(n-1) + [0]
while pq:
d, u = heappop(pq)
for v, w in graph[u]:
if dist[u] + w < dist[v]:
dist[v] = dist[u] + w
heappush(pq, (dist[v], v))
@cache
def fn(u):
"""Return number of restricted paths from u to n."""
if u == n-1: return 1 # boundary condition
ans = 0
for v, _ in graph[u]:
if dist[u] > dist[v]: ans += fn(v)
return ans
return fn(0) % 1_000_000_007 | number-of-restricted-paths-from-first-to-last-node | [Python3] Dijkstra + dp | ye15 | 4 | 401 | number of restricted paths from first to last node | 1,786 | 0.393 | Medium | 25,604 |
https://leetcode.com/problems/number-of-restricted-paths-from-first-to-last-node/discuss/1432248/Python-3-or-Dijkstra-DFS-DAG-pruning-or-Explanation | class Solution:
def countRestrictedPaths(self, n: int, edges: List[List[int]]) -> int:
graph = collections.defaultdict(list) # build graph
for a, b, w in edges:
graph[a].append((w, b))
graph[b].append((w, a))
heap = graph[n]
heapq.heapify(heap)
d = {n: 0}
while heap: # Dijkstra from node `n` to other nodes, record shortest distance to each node
cur_w, cur = heapq.heappop(heap)
if cur in d: continue
d[cur] = cur_w
for w, nei in graph[cur]:
heapq.heappush(heap, (w+cur_w, nei))
graph = collections.defaultdict(list)
for a, b, w in edges: # pruning based on `restricted` condition, make undirected graph to directed-acyclic graph
if d[a] > d[b]:
graph[a].append(b)
elif d[a] < d[b]:
graph[b].append(a)
ans, mod = 0, int(1e9+7)
@cache
def dfs(node): # use DFS to find total number of paths
if node == n:
return 1
cur = 0
for nei in graph[node]:
cur = (cur + dfs(nei)) % mod
return cur
return dfs(1) | number-of-restricted-paths-from-first-to-last-node | Python 3 | Dijkstra, DFS, DAG pruning | Explanation | idontknoooo | 3 | 284 | number of restricted paths from first to last node | 1,786 | 0.393 | Medium | 25,605 |
https://leetcode.com/problems/number-of-restricted-paths-from-first-to-last-node/discuss/2840621/Python-3-solution-with-comments | class Solution:
def countRestrictedPaths(self, n: int, edges: List[List[int]]) -> int:
dct_nd = {}
dist_to_n = {}
queue = deque() # from n-node to 1-node
visited = set()
# 1 step: create dictionary with nodes and nodes' distances to n
# create dictionary with format (weight, node_to)
# heap will automatically sort weight and node_to in ascending order
for l, r, w in edges:
dct_nd[l] = dct_nd.get(l, []) + [(w, r)]
dct_nd[r] = dct_nd.get(r, []) + [(w, l)]
dist_to_n[n] = 0
queue.append(n)
visited.add(n)
hpf = dct_nd[n].copy() # without '.copy()' hpf will be only pointer and dct_nd[n] could change
heapify(hpf)
while hpf:
el_w, el_nd = heappop(hpf)
if el_nd in visited: continue
dist_to_n[el_nd] = el_w
visited.add(el_nd)
queue.append(el_nd)
if el_nd == 1: break # you don't need to traverse more if you've reached 1-node
# other distances will be more than distance of 1-node
for (i_w, i_nd) in dct_nd[el_nd]:
if i_nd not in visited:
heappush(hpf, (el_w + i_w, i_nd))
# step 1: end
# add to dictionary one more field: number of routes to n
dist_to_n = {k: [v, 0] for k, v in dist_to_n.items()}
dist_to_n[n] = [dist_to_n[n][0], 1] # for n-node number of routes = 1
# step 2: Dynamic Programming
visited.clear()
while queue:
# start from n and traverse futher and futher
nd_prv = queue.popleft()
visited.add(nd_prv)
for (w_cur, nd_cur) in dct_nd[nd_prv]:
if nd_cur not in visited and \
nd_cur in dist_to_n.keys() and dist_to_n[nd_cur][0] > dist_to_n[nd_prv][0]:
# to current node add number of routes from previous node
dist_to_n[nd_cur][1] += dist_to_n[nd_prv][1]
# !!! careful !!! you need to add modulo operation (as said in the task)
dist_to_n[nd_cur][1] = int(dist_to_n[nd_cur][1] % (1e9+7))
# step 2: End
return dist_to_n[1][1] # return number of routes for 1-node | number-of-restricted-paths-from-first-to-last-node | Python 3 - solution with comments | noob_in_prog | 0 | 1 | number of restricted paths from first to last node | 1,786 | 0.393 | Medium | 25,606 |
https://leetcode.com/problems/number-of-restricted-paths-from-first-to-last-node/discuss/1098738/Python3-Dijkstar's-%2B-Bottom-up-DP-clean-with-detailed-explanation | class Solution:
def countRestrictedPaths(self, n: int, edges: List[List[int]]) -> int:
# Dijkstra's algorithm
distances = {i: float('inf') for i in range(1, n+1)}
distances[n] = 0
graph = defaultdict(list)
for edge in edges:
graph[edge[0]].append((edge[1], edge[2]))
graph[edge[1]].append((edge[0], edge[2]))
pq = [(0, n)]
while len(pq) > 0:
curDistance, curVertex = heapq.heappop(pq)
# skip the following steps if we've already visited the vertex
if curDistance > distances[curVertex]:
continue
for edge in graph[curVertex]:
neighbor = edge[0]
weight = edge[1]
distance = curDistance + weight
# update neighbor's distance if the path via cur node has a shorter distance
if distance < distances[neighbor]:
distances[neighbor] = distance
heapq.heappush(pq, (distance, neighbor))
# Bottom-up DP
# initialize dp array, which stores how many restricted paths between endnode and curnode
dp = [0]*(n+1)
dp[n] = 1
dist = sorted(list(distances.keys()), key=lambda item:distances[item])
for index in dist:
neighbors = [edge[0] for edge in graph[index]]
for neighbor in neighbors:
if distances[neighbor] < distances[index]:
dp[index] += dp[neighbor]
dp[index] = int(dp[index]%(1e9+7))
# when we've reached node 1 (start node), we could return the result
if index == 1:
return dp[1]
return -1 | number-of-restricted-paths-from-first-to-last-node | Python3 Dijkstar's + Bottom-up DP, clean with detailed explanation | cathy1012 | 0 | 58 | number of restricted paths from first to last node | 1,786 | 0.393 | Medium | 25,607 |
https://leetcode.com/problems/make-the-xor-of-all-segments-equal-to-zero/discuss/1100417/Python3-dp | class Solution:
def minChanges(self, nums: List[int], k: int) -> int:
freq = defaultdict(lambda: defaultdict(int))
for i, x in enumerate(nums): freq[i%k][x] += 1 # freq by row
n = 1 << 10
dp = [0] + [-inf]*(n-1)
for i in range(k):
mx = max(dp)
tmp = [0]*n
for x, c in enumerate(dp):
for xx, cc in freq[i].items():
tmp[x^xx] = max(tmp[x^xx], c + cc, mx)
dp = tmp
return len(nums) - dp[0] | make-the-xor-of-all-segments-equal-to-zero | [Python3] dp | ye15 | 3 | 184 | make the xor of all segments equal to zero | 1,787 | 0.395 | Hard | 25,608 |
https://leetcode.com/problems/check-if-one-string-swap-can-make-strings-equal/discuss/1108295/Python3-check-diff | class Solution:
def areAlmostEqual(self, s1: str, s2: str) -> bool:
diff = [[x, y] for x, y in zip(s1, s2) if x != y]
return not diff or len(diff) == 2 and diff[0][::-1] == diff[1] | check-if-one-string-swap-can-make-strings-equal | [Python3] check diff | ye15 | 67 | 5,900 | check if one string swap can make strings equal | 1,790 | 0.456 | Easy | 25,609 |
https://leetcode.com/problems/check-if-one-string-swap-can-make-strings-equal/discuss/2793410/python-easiest-soln | class Solution:
def areAlmostEqual(self, s1: str, s2: str) -> bool:
if s1==s2: #strings are equal no swapping required
return True
if sorted(s1)!=sorted(s2): #if alphabets of strings are not equal
return False
countof=0
for i in range(len(s1)):
if s1[i]!=s2[i]:#checking diff aplphabets of both the strings
countof +=1
if countof!=2:
return False
return True | check-if-one-string-swap-can-make-strings-equal | [python]--\easiest soln\ | user9516zM | 2 | 129 | check if one string swap can make strings equal | 1,790 | 0.456 | Easy | 25,610 |
https://leetcode.com/problems/check-if-one-string-swap-can-make-strings-equal/discuss/1905267/Python-O(n)-time-O(1)-space-easy-understanding | class Solution:
def areAlmostEqual(self, s1: str, s2: str) -> bool:
size1, size2 = len(s1), len(s2)
if size1 != size2:
return False
pos1 = pos2 = -1
for i in range(size1):
if s1[i] != s2[i]:
if pos1 == -1:
pos1 = i
elif pos2 == -1:
pos2 = i
else:
return False
return (pos1 == -1 and pos2 == -1) or (pos1 != -1 and pos2 != -1 and s1[pos1] == s2[pos2] and s1[pos2] == s2[pos1]) | check-if-one-string-swap-can-make-strings-equal | Python O(n) time O(1) space easy understanding | llawwaii2 | 2 | 199 | check if one string swap can make strings equal | 1,790 | 0.456 | Easy | 25,611 |
https://leetcode.com/problems/check-if-one-string-swap-can-make-strings-equal/discuss/2319334/Easy-python-track-mismatch | class Solution:
def areAlmostEqual(self, s1: str, s2: str) -> bool:
c=0
set_1 = set()
set_2 = set()
l = len(s1)
for i in range(l):
if s1[i]!=s2[i]:
set_1.add(s2[i])
set_2.add(s1[i])
c+=1
if c>2:
return False
if set_1 != set_2:
return False
return True | check-if-one-string-swap-can-make-strings-equal | Easy python - track mismatch | sunakshi132 | 1 | 40 | check if one string swap can make strings equal | 1,790 | 0.456 | Easy | 25,612 |
https://leetcode.com/problems/check-if-one-string-swap-can-make-strings-equal/discuss/2081248/Simple-Python-Solution | class Solution:
def areAlmostEqual(self, s1: str, s2: str) -> bool:
if s1 == s2: # i.e diff = 0
return True
if sorted(s1) != sorted(s2):
return False
diff = 0
for i, j in zip(s1, s2):
if i != j:
diff += 1
return True if diff == 2 else False | check-if-one-string-swap-can-make-strings-equal | Simple Python Solution | pe-mn | 1 | 60 | check if one string swap can make strings equal | 1,790 | 0.456 | Easy | 25,613 |
https://leetcode.com/problems/check-if-one-string-swap-can-make-strings-equal/discuss/1988618/Python-Easy-Solution-or-beats-99.37 | class Solution:
def areAlmostEqual(self, s1: str, s2: str) -> bool:
if s1 == s2:
return True
count = 0
length = len(s1)
if length != len(s2):
return False
elif sorted(s1) != sorted(s2):
return False
for i in range(length):
if s1[i] != s2[i]:
count += 1
if count > 2:
return False
return True if count == 2 else False | check-if-one-string-swap-can-make-strings-equal | [Python] Easy Solution | beats 99.37% | jamil117 | 1 | 121 | check if one string swap can make strings equal | 1,790 | 0.456 | Easy | 25,614 |
https://leetcode.com/problems/check-if-one-string-swap-can-make-strings-equal/discuss/1205561/Python3-simple-solution-using-set-beats-90-users | class Solution:
def areAlmostEqual(self, s1: str, s2: str) -> bool:
if not set(s1) == set(s2):
return False
return sum(1 for i in range(len(s1)) if not s1[i] == s2[i]) in [0, 2] | check-if-one-string-swap-can-make-strings-equal | Python3 simple solution using set beats 90% users | EklavyaJoshi | 1 | 167 | check if one string swap can make strings equal | 1,790 | 0.456 | Easy | 25,615 |
https://leetcode.com/problems/check-if-one-string-swap-can-make-strings-equal/discuss/2850345/python-Solution-time-O(n)-space-O(1) | class Solution:
def areAlmostEqual(self, s1: str, s2: str) -> bool:
i , j =0 , len(s1)-1
count=0
while(i<=j):
while(i<j):
if s2[i]!=s1[i]:
break
else:
i+=1
while(i<j):
if s2[j]!=s1[j]:
break
else:
j-=1
if i<j:
if s1[i]==s2[j] and s2[i]==s1[j]:
count+=1
else:
return False
if i==j and s1[i]!=s2[i]:
return False
i+=1
j-=1
# print(count)
return count<=1 | check-if-one-string-swap-can-make-strings-equal | python Solution time O(n) , space O(1) | sintin1310 | 0 | 1 | check if one string swap can make strings equal | 1,790 | 0.456 | Easy | 25,616 |
https://leetcode.com/problems/check-if-one-string-swap-can-make-strings-equal/discuss/2837312/Clean-and-Easy-to-Understand-Python-3. | class Solution:
def areAlmostEqual(self, s1: str, s2: str) -> bool:
swaps = []
if s1 == s2:
return True
mismatch = 0
for index, letter in enumerate(s1):
if letter != s2[index]:
mismatch += 1
swaps.append((index, s2[index])) #Save the mismatch index and letter.
#print(swaps)
s2_list = list(s2) #We convert to list because swapping with strings is icky.
if mismatch == 2: #Perform swaps and check if the strings are really swappable!
s2_list[swaps[0][0]] = swaps[1][1] #Swap first letter with last letter.
s2_list[swaps[1][0]] = swaps[0][1] #Swap last letter with first letter.
#print(s2_list)
if "".join(s2_list) == s1: #Convert back to string and check for equality.
return True
return False | check-if-one-string-swap-can-make-strings-equal | Clean and Easy to Understand Python 3. | mephiticfire | 0 | 2 | check if one string swap can make strings equal | 1,790 | 0.456 | Easy | 25,617 |
https://leetcode.com/problems/check-if-one-string-swap-can-make-strings-equal/discuss/2829027/Runtime%3A-56-ms-faster-than-55.86-of-Python3-online-submissions-or-Easy-or-Hashmap | class Solution:
def areAlmostEqual(self, s1: str, s2: str) -> bool:
if s1==s2:
return True
if Counter(s1)!=Counter(s2):
return False
else:
count=0
for i,j in zip(s1,s2):
if i!=j:
count+=1
if(count==2):
return True
else:
return False | check-if-one-string-swap-can-make-strings-equal | Runtime: 56 ms, faster than 55.86% of Python3 online submissions | Easy | Hashmap | liontech_123 | 0 | 2 | check if one string swap can make strings equal | 1,790 | 0.456 | Easy | 25,618 |
https://leetcode.com/problems/check-if-one-string-swap-can-make-strings-equal/discuss/2793431/python-Easiest-with-comments | class Solution:
def areAlmostEqual(self, s1: str, s2: str) -> bool:
if s1==s2: #strings are equal no swapping required
return True
if sorted(s1)!=sorted(s2): #if alphabets of strings are not equal
return False
countof=0
for i in range(len(s1)):
if s1[i]!=s2[i]:#checking diff aplphabets of both the strings
countof +=1
#minimum count_of_diff_alphabets=2 is required in order
# to do atleast one swapping
if countof!=2:
return False
return True | check-if-one-string-swap-can-make-strings-equal | [python]-Easiest\ \ with comments | user9516zM | 0 | 3 | check if one string swap can make strings equal | 1,790 | 0.456 | Easy | 25,619 |
https://leetcode.com/problems/check-if-one-string-swap-can-make-strings-equal/discuss/2759262/Simple-Python3-Solution | class Solution:
def areAlmostEqual(self, s1: str, s2: str) -> bool:
count=0
if s1 == s2:
return True
if sorted(s1) != sorted(s2):
return False
for i in range(len(s1)):
if s1[i] != s2[i]:
count += 1
if count != 2:
return False
return True | check-if-one-string-swap-can-make-strings-equal | Simple Python3 Solution | vivekrajyaguru | 0 | 8 | check if one string swap can make strings equal | 1,790 | 0.456 | Easy | 25,620 |
https://leetcode.com/problems/check-if-one-string-swap-can-make-strings-equal/discuss/2730506/Check-if-One-String-Swap-Can-Make-Strings-Equal-or-Python-Solution | class Solution:
def areAlmostEqual(self, s1: str, s2: str) -> bool:
if s1 == s2:
return True
for i in range(len(s2)-1):
for j in range(i+1,len(s2)):
s = list(s2)
temp = s[i]
s[i] = s[j]
s[j] = temp
if s1 == "".join(s):
return True
return False | check-if-one-string-swap-can-make-strings-equal | Check if One String Swap Can Make Strings Equal | Python Solution | ygygupta0 | 0 | 8 | check if one string swap can make strings equal | 1,790 | 0.456 | Easy | 25,621 |
https://leetcode.com/problems/check-if-one-string-swap-can-make-strings-equal/discuss/2705644/Python-(beats-99) | class Solution:
def areAlmostEqual(self, s1: str, s2: str) -> bool:
indices = []
for i in range(len(s1)):
if s1[i] != s2[i]:
indices.append(i)
if len(indices) > 2:
return False
if len(indices) == 1:
return False
elif len(indices) == 0:
return True
if s1[indices[0]] == s2[indices[1]] and s1[indices[1]] == s2[indices[0]]:
return True
elif s2[indices[0]] == s1[indices[1]] and s2[indices[1]] == s1[indices[0]]:
return True
return False | check-if-one-string-swap-can-make-strings-equal | ✅ Python (beats 99%) | anandanshul001 | 0 | 5 | check if one string swap can make strings equal | 1,790 | 0.456 | Easy | 25,622 |
https://leetcode.com/problems/check-if-one-string-swap-can-make-strings-equal/discuss/2698399/Python3-solution-clean-code-with-full-comments. | class Solution:
def areAlmostEqual(self, s1: str, s2: str) -> bool:
dict_1 = str_to_dict(s1)
dict_2 = str_to_dict(s2)
if not is_dictionaries_equal(dict_1, dict_2) :
return False
return check_letter_position(s1, s2)
# Define helper method that convert string int dictionary.
def str_to_dict(string: str):
dic = {}
for i in string:
if i in dic:
dic[i] += 1
else:
dic[i] = 1
return dic
# Define helper method that check if two dictionaries are equal.
# This method, by checking equality also indirectly check if the strings that make
# the dictionaries have the same length, and have the same characters.
def is_dictionaries_equal(dict_1, dict_2):
for key in dict_1.keys():
if not key in dict_2:
return False
if dict_1[key] != dict_2[key]:
return False
return True
# This method check if given two strings can become equal by swaping ONLY ONE character
# that is misplaced (if at all), as the problem states.
def check_letter_position(s1: str, s2: str):
# Counter for misplaced characters.
count = 0
# Variables for remembering the mispalced characters.
temp_1 = ''
temp_2 = ''
# Iterate one of the strings and check if the characters of both string are the same,
# notice that by now we know that the length of the strings is equal.
for i in range(len(s1)):
# If the characters of the strings at a specific index are not the same,
# and they are not equal to their opposite copy (temp_1 or temp_2), then
# make a copy of each, and count the event.
if (s1[i] != s2[i]) and (s1[i] != temp_2 or s2[i] != temp_1):
temp_1 = s1[i]
temp_2 = s2[i]
count += 1
# If we counted two or more events, then we at a contradiction with the problems data,
# so we return false.
if 2 <= count:
return False
return True
# Runtime: 37 ms, faster than 86.78% of Python3 online submissions for Check if One String Swap Can Make Strings Equal.
# Memory Usage: 13.9 MB, less than 72.10% of Python3 online submissions for Check if One String Swap Can Make Strings Equal.
# If you like my work and found it helpful, then I'll appreciate a like. Thanks! | check-if-one-string-swap-can-make-strings-equal | Python3 solution, clean code with full comments. | 375d | 0 | 16 | check if one string swap can make strings equal | 1,790 | 0.456 | Easy | 25,623 |
https://leetcode.com/problems/check-if-one-string-swap-can-make-strings-equal/discuss/2686970/python3 | class Solution:
def areAlmostEqual(self, s1: str, s2: str) -> bool:
if sorted(s1)!=sorted(s2):
return False
c=0
for i in range(len(s1)):
if s1[i]!=s2[i]:
c+=1
if c>2:
return False
return True | check-if-one-string-swap-can-make-strings-equal | python3 | gnani_dw | 0 | 4 | check if one string swap can make strings equal | 1,790 | 0.456 | Easy | 25,624 |
https://leetcode.com/problems/check-if-one-string-swap-can-make-strings-equal/discuss/2668614/Python-or-Easy-stack-solution | class Solution:
def areAlmostEqual(self, s1: str, s2: str) -> bool:
not_eq, buf1, buf2 = 0, [], []
for i in range(len(s1)):
if s1[i] != s2[i]:
not_eq += 1
if not_eq > 2:
return False
if not_eq == 1:
buf1 += [s1[i], s2[i]]
else:
buf2 += [s1[i], s2[i]]
if buf1 != buf2[::-1]:
return False
return True | check-if-one-string-swap-can-make-strings-equal | Python | Easy stack solution | LordVader1 | 0 | 13 | check if one string swap can make strings equal | 1,790 | 0.456 | Easy | 25,625 |
https://leetcode.com/problems/check-if-one-string-swap-can-make-strings-equal/discuss/2657312/Easy-Python-Solution | class Solution:
def areAlmostEqual(self, s1: str, s2: str) -> bool:
c1 = Counter(s1)
c2 = Counter(s2)
if c1 != c2: return False
count = 0
for i in range(len(s1)):
if s1[i] !=s2[i]:
count+=1
if count >2:
return False
return True | check-if-one-string-swap-can-make-strings-equal | 🐍 Easy Python Solution ✔ | kanvi26 | 0 | 4 | check if one string swap can make strings equal | 1,790 | 0.456 | Easy | 25,626 |
https://leetcode.com/problems/check-if-one-string-swap-can-make-strings-equal/discuss/2632803/Python-or-O(n)-or-simple | class Solution:
def areAlmostEqual(self, s1: str, s2: str) -> bool:
indices = []
#trace mis-matched indices - O(n)
for i in range(len(s1)):
if s1[i] != s2[i]:
indices.append(i)
#strings already equal
if len(indices) == 0:
return True
#more than two indices have different characters
#so swap isn't possible
elif len(indices) != 2:
return False
#check if the indices are swappable
else:
i, j = indices
return s1[i] == s2[j] and s1[j] == s2[i] | check-if-one-string-swap-can-make-strings-equal | Python | O(n) | simple | _drunkenmonkey | 0 | 29 | check if one string swap can make strings equal | 1,790 | 0.456 | Easy | 25,627 |
https://leetcode.com/problems/check-if-one-string-swap-can-make-strings-equal/discuss/2463038/Python-Simple-Solution | class Solution:
def areAlmostEqual(self, s1: str, s2: str) -> bool:
if s1 == s2:
return True
for value in s2:
if s1.count(value) != s2.count(value):
return False
length = len(s1)
check = 0
for i, j in zip(s1, s2):
if i != j:
check += 1
if length <= 2 and check == 0:
return True
elif length > 2 and check == 2:
return True
else:
return False | check-if-one-string-swap-can-make-strings-equal | Python Simple Solution | NRYU | 0 | 52 | check if one string swap can make strings equal | 1,790 | 0.456 | Easy | 25,628 |
https://leetcode.com/problems/check-if-one-string-swap-can-make-strings-equal/discuss/2424324/Easy-Python-Solution | class Solution:
def areAlmostEqual(self, s1: str, s2: str) -> bool:
f,s = 0,0
for i in range(0,len(s1)):
if s1[i] != s2[i]:
if f == 0:
f = i
elif s == 0:
s = i
else:
return False
return (s1[f] == s2[s]) and (s1[s] == s2[f]) | check-if-one-string-swap-can-make-strings-equal | Easy Python Solution | SouravSingh49 | 0 | 42 | check if one string swap can make strings equal | 1,790 | 0.456 | Easy | 25,629 |
https://leetcode.com/problems/check-if-one-string-swap-can-make-strings-equal/discuss/2261790/save-mappping-in-dict | class Solution:
def areAlmostEqual(self, s1: str, s2: str) -> bool:
cond = 0
dict_1 = {}
# check if two strings are same
if s1==s2:
return True
# loop over string
for i,j in zip(s1,s2):
# when mismatches
if i !=j:
# if dict is empty append the next expected mismatch
if len(dict_1) == 0:
dict_1[j] = i
else:
# mismatch is of different charecter
if i not in dict_1:
return False
else:
# charecter in s1 matches but s2 not matching
if dict_1[i] != j:
return False
# multiple such mismatches can happen so count it
cond += 1
return cond ==1 | check-if-one-string-swap-can-make-strings-equal | save mappping in dict | krishnamsgn | 0 | 14 | check if one string swap can make strings equal | 1,790 | 0.456 | Easy | 25,630 |
https://leetcode.com/problems/check-if-one-string-swap-can-make-strings-equal/discuss/2177241/Python-Simple-Python-Solution-By-Swapping-the-Index | class Solution:
def areAlmostEqual(self, s1: str, s2: str) -> bool:
if s1 == s2:
return True
index = []
for i in range(len(s1)):
if s1[i] != s2[i]:
index.append(i)
if len(index) != 2:
return False
index_one , index_second = index
s1 = list(s1)
s1[index_one], s1[index_second] = s1[index_second], s1[index_one]
s1 = ''.join(s1)
if s1 == s2:
return True
else:
return False | check-if-one-string-swap-can-make-strings-equal | [ Python ] ✅✅ Simple Python Solution By Swapping the Index 🥳✌👍 | ASHOK_KUMAR_MEGHVANSHI | 0 | 95 | check if one string swap can make strings equal | 1,790 | 0.456 | Easy | 25,631 |
https://leetcode.com/problems/check-if-one-string-swap-can-make-strings-equal/discuss/2159630/Python-Solution | class Solution:
def areAlmostEqual(self, s1: str, s2: str) -> bool:
# check if letters not equal
if sorted(s1) != sorted(s2):
return False
#to small case
s1 = s1.lower()
s2 = s2.lower()
c = 0
for i in range(len(s1)):
if s1[i] != s2[i]:
c = c + 1 #increment if not equal
return c <= 2 #return false if difference is more than 2 | check-if-one-string-swap-can-make-strings-equal | Python Solution | ahmeddossamaa184 | 0 | 47 | check if one string swap can make strings equal | 1,790 | 0.456 | Easy | 25,632 |
https://leetcode.com/problems/check-if-one-string-swap-can-make-strings-equal/discuss/2074072/Python-Easy-solution-with-complexities | class Solution:
def areAlmostEqual(self, s1: str, s2: str) -> bool:
if (len(s1) > len (s2)) or (len (s1) > len (s2)):
return False
if len(s1) == 1 :
if s1[0] == s2[0]:
return True
first = 0
second = 0
for i in range(0,len(s1)):
if s1[i] != s2[i]:
if first ==0:
first = i
elif second == 0:
second = i
else :
return False
if s1[first] == s2[second] and s1[second] == s2[first]:
return True
return False
# time O(n)
# space O(1) | check-if-one-string-swap-can-make-strings-equal | [Python] Easy solution with complexities | mananiac | 0 | 69 | check if one string swap can make strings equal | 1,790 | 0.456 | Easy | 25,633 |
https://leetcode.com/problems/check-if-one-string-swap-can-make-strings-equal/discuss/2049258/python3-List-Comprehension | class Solution:
def areAlmostEqual(self, s1: str, s2: str) -> bool:
hashmap = [i for i,l1 in enumerate(s2) if s1[i] != s2[i]]
if not hashmap:
return True
elif len(hashmap) == 2:
s2 = list(s2)
s2[hashmap[0]],s2[hashmap[1]] = s2[hashmap[1]],s2[hashmap[0]]
if ''.join(s2) == s1:
return True
else:
return False | check-if-one-string-swap-can-make-strings-equal | python3 List Comprehension | kedeman | 0 | 48 | check if one string swap can make strings equal | 1,790 | 0.456 | Easy | 25,634 |
https://leetcode.com/problems/check-if-one-string-swap-can-make-strings-equal/discuss/1978497/Python-oror-Time%3A-O(N)-oror-Space%3A-O(1) | class Solution:
def areAlmostEqual(self, s1: str, s2: str) -> bool:
# keep track of found differences
first_diff = -1
second_diff = -1
for idx in range(len(s1)):
if s1[idx] != s2[idx]:
if first_diff == -1:
first_diff = idx
elif second_diff == -1:
second_diff = idx
else:
# found more than two differences
return False
# if differences are equal in cross then strings would become equal
return s1[first_diff] == s2[second_diff] and s1[second_diff] == s2[first_diff] | check-if-one-string-swap-can-make-strings-equal | Python || Time: O(N) || Space: O(1) | user3694B | 0 | 63 | check if one string swap can make strings equal | 1,790 | 0.456 | Easy | 25,635 |
https://leetcode.com/problems/check-if-one-string-swap-can-make-strings-equal/discuss/1924533/Python-Detailed-Solution-Faster-Than-96.66-With-Explanation | class Solution:
def areAlmostEqual(self, s1: str, s2: str) -> bool:
if s1 == s2:
return True
diff, pos1, pos2, s = 0, -1, -1, ""
for i in range(len(s1)):
if s1[i] != s2[i]:
diff += 1
if diff > 2:
return 0
if pos1 == -1:
pos1 = i
else:
pos2 = i
for i in range(len(s1)):
if i == pos1:
s += s1[pos2]
elif i == pos2:
s += s1[pos1]
else:
s += s1[i]
return s == s2 | check-if-one-string-swap-can-make-strings-equal | Python Detailed Solution Faster Than 96.66% With Explanation | Hejita | 0 | 79 | check if one string swap can make strings equal | 1,790 | 0.456 | Easy | 25,636 |
https://leetcode.com/problems/check-if-one-string-swap-can-make-strings-equal/discuss/1910606/Python-Solution | class Solution:
def areAlmostEqual(self, s1: str, s2: str) -> bool:
if sorted(s1) != sorted(s2):
return False
result = 0
for x, y in zip(s1, s2):
if x != y:
result += 1
if result > 2:
return False
return True | check-if-one-string-swap-can-make-strings-equal | Python Solution | hgalytoby | 0 | 81 | check if one string swap can make strings equal | 1,790 | 0.456 | Easy | 25,637 |
https://leetcode.com/problems/check-if-one-string-swap-can-make-strings-equal/discuss/1910606/Python-Solution | class Solution:
def areAlmostEqual(self, s1: str, s2: str) -> bool:
result = []
count = 0
for x, y in zip(s1, s2):
if x != y:
result.append((x, y))
count += 1
if count > 2:
return False
if count == 0:
return True
elif count == 2:
return result[0] == result[1][::-1]
return False | check-if-one-string-swap-can-make-strings-equal | Python Solution | hgalytoby | 0 | 81 | check if one string swap can make strings equal | 1,790 | 0.456 | Easy | 25,638 |
https://leetcode.com/problems/check-if-one-string-swap-can-make-strings-equal/discuss/1872917/Clean-solution-in-Python-extracting-and-comparing-different-characters | class Solution:
def areAlmostEqual(self, s1: str, s2: str) -> bool:
if s1 == s2:
return True
d = tuple((a, b) for a, b in zip(s1, s2) if a != b)
if len(d) != 2:
return False
a1, b1, a2, b2 = *d[0], *d[1]
return a1 == b2 and b1 == a2 | check-if-one-string-swap-can-make-strings-equal | Clean solution in Python, extracting and comparing different characters | mousun224 | 0 | 57 | check if one string swap can make strings equal | 1,790 | 0.456 | Easy | 25,639 |
https://leetcode.com/problems/check-if-one-string-swap-can-make-strings-equal/discuss/1853895/Python-for-loop-solution-beats-95.56 | class Solution:
def areAlmostEqual(self, s1: str, s2: str) -> bool:
arr1, arr2 = [], []
count = 0
for i in range(len(s1)):
if s1[i] != s2[i]:
count += 1
arr1.append(s1[i])
arr2.append(s2[i])
return (count == 2 and arr1.pop() == arr2[0] and arr1.pop() == arr2[1]) or count == 0 | check-if-one-string-swap-can-make-strings-equal | Python for-loop solution beats 95.56% | yusianglin11010 | 0 | 96 | check if one string swap can make strings equal | 1,790 | 0.456 | Easy | 25,640 |
https://leetcode.com/problems/check-if-one-string-swap-can-make-strings-equal/discuss/1818164/Python-solution | class Solution:
def areAlmostEqual(self, s1: str, s2: str) -> bool:
if set(s1) != set(s2):
return False
count = 0
for i in range(len(s1)):
if s1[i] != s2[i]:
count += 1
return count == 0 or count == 2 | check-if-one-string-swap-can-make-strings-equal | Python solution | Gleb4ik | 0 | 45 | check if one string swap can make strings equal | 1,790 | 0.456 | Easy | 25,641 |
https://leetcode.com/problems/check-if-one-string-swap-can-make-strings-equal/discuss/1709348/Python3-accepted-solution | class Solution:
def areAlmostEqual(self, s1: str, s2: str) -> bool:
count = 0
if(s1==s2): return True
l1 = []; l2 = []
for i in range(len(s1)):
if(s1[i]!=s2[i]):
count+=1
l1.append(s1[i])
l2.append(s2[i])
if(count>2):
return False
if(count==2):
if(l1[0] == l2[1] and l2[0] == l1[1]):
return True
return False | check-if-one-string-swap-can-make-strings-equal | Python3 accepted solution | sreeleetcode19 | 0 | 62 | check if one string swap can make strings equal | 1,790 | 0.456 | Easy | 25,642 |
https://leetcode.com/problems/check-if-one-string-swap-can-make-strings-equal/discuss/1517541/One-pass-99.5-speed | class Solution:
def areAlmostEqual(self, s1: str, s2: str) -> bool:
if len(s1) == len(s2):
different_idx = []
for i, (a, b) in enumerate(zip(s1, s2)):
if a != b:
different_idx.append(i)
if not different_idx:
return True
elif (len(different_idx) == 2 and
s1[different_idx[0]] == s2[different_idx[1]] and
s1[different_idx[1]] == s2[different_idx[0]]):
return True
return False | check-if-one-string-swap-can-make-strings-equal | One pass, 99.5% speed | EvgenySH | 0 | 122 | check if one string swap can make strings equal | 1,790 | 0.456 | Easy | 25,643 |
https://leetcode.com/problems/check-if-one-string-swap-can-make-strings-equal/discuss/1484575/Python-O(N)-time-O(1)-space-Easy-to-Read | class Solution:
def areAlmostEqual(self, s1: str, s2: str) -> bool:
diffCount = 0
d1, d2 = -1, -1
for i in range(len(s1)):
if s1[i] != s2[i]:
diffCount += 1
if d1 == -1:
d1 = i
else:
d2 = i
if diffCount > 2:
return False
if diffCount == 0:
return True
elif diffCount == 1:
return False
return {s1[d1], s1[d2]} == {s2[d1], s2[d2]} | check-if-one-string-swap-can-make-strings-equal | Python O(N) time O(1) space, Easy to Read | CocoWine | 0 | 119 | check if one string swap can make strings equal | 1,790 | 0.456 | Easy | 25,644 |
https://leetcode.com/problems/check-if-one-string-swap-can-make-strings-equal/discuss/1179045/simple-using-count | class Solution:
def areAlmostEqual(self, s1: str, s2: str) -> bool:
if len(s1)!=len(s2):
return False
count=0
for i in range (len(s2)):
if s1[i]!=s2[i]:
count+=1
if s1[i] not in s2 or s2[i] not in s1:
return False
if count==2 or count==0:
return True
return False | check-if-one-string-swap-can-make-strings-equal | simple using count | janhaviborde23 | 0 | 113 | check if one string swap can make strings equal | 1,790 | 0.456 | Easy | 25,645 |
https://leetcode.com/problems/check-if-one-string-swap-can-make-strings-equal/discuss/1146362/Python3-Simple-solution-24-ms-runtime | class Solution:
def areAlmostEqual(self, s1: str, s2: str) -> bool:
s = 0
for i in range(0,len(s1)):
if s1[i] != s2[i]:
if s1.count(s1[i]) !=s2.count(s1[i]):
return False
s = s+1
if s>2:
return False
return True | check-if-one-string-swap-can-make-strings-equal | Python3, Simple solution, 24 ms runtime | naiem_ece | 0 | 125 | check if one string swap can make strings equal | 1,790 | 0.456 | Easy | 25,646 |
https://leetcode.com/problems/check-if-one-string-swap-can-make-strings-equal/discuss/1138782/99-speed-98-memory | class Solution:
def areAlmostEqual(self, s1: str, s2: str) -> bool:
if not set(s1) == set(s2):
return False
return sum(1 for i in range(len(s1)) if not s1[i] == s2[i]) < 3 | check-if-one-string-swap-can-make-strings-equal | 99% speed, 98% memory | JulianaYo | 0 | 169 | check if one string swap can make strings equal | 1,790 | 0.456 | Easy | 25,647 |
https://leetcode.com/problems/find-center-of-star-graph/discuss/1568945/Beginner-Friendly-solution-in-O(1)-time-with-detailed-explanation | class Solution:
def findCenter(self, edges: List[List[int]]) -> int:
""" From the Constraints: A valid STAR GRAPH is confirmed.
That means the center will be common to every edges.
Therefore we can get the center by comparing only first 2 elements"""
for i in range (1):
# Check if first element of first edge mathches with any element of second edges
if edges[i][0] == edges [i+1][0] or edges[i][0] == edges[i+1][1]:
return edges[i][0]
#Otherwise second element of first edge will be the answer
else:
return edges[i][1] | find-center-of-star-graph | Beginner Friendly solution in O(1) time with detailed explanation | stormbreaker_x | 4 | 331 | find center of star graph | 1,791 | 0.835 | Easy | 25,648 |
https://leetcode.com/problems/find-center-of-star-graph/discuss/1702278/Python3-%3A-O(n)-Solution-oror-Faster-oror-Improved-(2-line-only) | class Solution:
def findCenter(self, edges: List[List[int]]) -> int:
if edges[0][0] in edges[1]: return edges[0][0]
return edges[0][1] | find-center-of-star-graph | Python3 : O(n) Solution || Faster || Improved (2 line only) | Anilchouhan181 | 3 | 203 | find center of star graph | 1,791 | 0.835 | Easy | 25,649 |
https://leetcode.com/problems/find-center-of-star-graph/discuss/1702268/Python3-%3A-O(n)-Solution-oror-Faster | class Solution:
def findCenter(self, edges: List[List[int]]) -> int:
if edges[1][0]==edges[0][0] or edges[1][0]==edges[0][1]: return edges[1][0]
return edges[1][1] | find-center-of-star-graph | Python3 : O(n) Solution || Faster | Anilchouhan181 | 3 | 114 | find center of star graph | 1,791 | 0.835 | Easy | 25,650 |
https://leetcode.com/problems/find-center-of-star-graph/discuss/1466320/Easy-Solution-or-Simple-Understanding-Java-Python3-C%2B%2B-JavaScript | class Solution:
def findCenter(self, edges: List[List[int]]) -> int:
first = edges[0]
second = edges[1]
if first[0] == second[0] or first[0] == second[1]:
return first[0]
return first[1] | find-center-of-star-graph | Easy Solution | Simple Understanding [Java, Python3, C++, JavaScript] | iamcmk | 2 | 134 | find center of star graph | 1,791 | 0.835 | Easy | 25,651 |
https://leetcode.com/problems/find-center-of-star-graph/discuss/1108306/Python3-check-degree | class Solution:
def findCenter(self, edges: List[List[int]]) -> int:
freq = {}
for u, v in edges:
freq[u] = 1 + freq.get(u, 0)
freq[v] = 1 + freq.get(v, 0)
return next(k for k, v in freq.items() if v > 1) | find-center-of-star-graph | [Python3] check degree | ye15 | 2 | 161 | find center of star graph | 1,791 | 0.835 | Easy | 25,652 |
https://leetcode.com/problems/find-center-of-star-graph/discuss/1108306/Python3-check-degree | class Solution:
def findCenter(self, edges: List[List[int]]) -> int:
if edges[0][0] in edges[1]: return edges[0][0]
else: return edges[0][1] | find-center-of-star-graph | [Python3] check degree | ye15 | 2 | 161 | find center of star graph | 1,791 | 0.835 | Easy | 25,653 |
https://leetcode.com/problems/find-center-of-star-graph/discuss/1977978/1-Line-Python-Solution-oror-90-Faster-oror-Memory-less-than-95 | class Solution:
def findCenter(self, edges: List[List[int]]) -> int:
return edges[0][0] if edges[0][0] in edges[1] else edges[0][1] | find-center-of-star-graph | 1-Line Python Solution || 90% Faster || Memory less than 95% | Taha-C | 1 | 125 | find center of star graph | 1,791 | 0.835 | Easy | 25,654 |
https://leetcode.com/problems/find-center-of-star-graph/discuss/1977978/1-Line-Python-Solution-oror-90-Faster-oror-Memory-less-than-95 | class Solution:
def findCenter(self, edges: List[List[int]]) -> int:
return reduce(lambda x,y: set(x)&set(y), edges).pop() | find-center-of-star-graph | 1-Line Python Solution || 90% Faster || Memory less than 95% | Taha-C | 1 | 125 | find center of star graph | 1,791 | 0.835 | Easy | 25,655 |
https://leetcode.com/problems/find-center-of-star-graph/discuss/1945202/Python-Clean-and-Simple | class Solution:
def findCenter(self, edges):
counter = {}
for v1, v2 in edges:
if v1 not in counter: counter[v1] = 0
if v2 not in counter: counter[v2] = 0
counter[v1] += 1
counter[v2] += 1
return max(counter, key=counter.get) | find-center-of-star-graph | Python - Clean and Simple | domthedeveloper | 1 | 98 | find center of star graph | 1,791 | 0.835 | Easy | 25,656 |
https://leetcode.com/problems/find-center-of-star-graph/discuss/1945202/Python-Clean-and-Simple | class Solution:
def findCenter(self, e):
return mode(e[0] + e[1]) | find-center-of-star-graph | Python - Clean and Simple | domthedeveloper | 1 | 98 | find center of star graph | 1,791 | 0.835 | Easy | 25,657 |
https://leetcode.com/problems/find-center-of-star-graph/discuss/1625595/Python3-O(1)-space-O(1)-time-solution | class Solution:
def findCenter(self, edges: List[List[int]]) -> int:
return edges[0][0] if edges[0][0] == edges[1][0] or edges[0][0] == edges[1][1] else edges[0][1] | find-center-of-star-graph | [Python3] O(1) space, O(1) time solution | maosipov11 | 1 | 146 | find center of star graph | 1,791 | 0.835 | Easy | 25,658 |
https://leetcode.com/problems/find-center-of-star-graph/discuss/1188525/Easy-Python-Solution-with-Comments | class Solution:
def findCenter(self, edges: List[List[int]]) -> int:
# Counts how many connections are associated with a node
# Because the graph is undirected, we don't need to differentiate start points and end points
freq_dict = defaultdict(int)
for edge in edges:
for num in edge:
freq_dict[num] += 1
# Manually checks for a node that has n-1 connections meaning it is the center node!
for num in freq_dict:
if freq_dict[num] == len(edges):
return num
return False
# Time Complexity: O(n)
# Space Complexity: O(n) | find-center-of-star-graph | Easy Python Solution with Comments | kevinvle1997 | 1 | 256 | find center of star graph | 1,791 | 0.835 | Easy | 25,659 |
https://leetcode.com/problems/find-center-of-star-graph/discuss/1126836/Python-one-line | class Solution:
def findCenter(self, edges: List[List[int]]) -> int:
return edges[0][0] if edges[0][0] in edges[1] else edges[0][1] | find-center-of-star-graph | Python one line | airksh | 1 | 67 | find center of star graph | 1,791 | 0.835 | Easy | 25,660 |
https://leetcode.com/problems/find-center-of-star-graph/discuss/2824174/Python-solution-beats-88.99-in-memory-usage | class Solution:
def findCenter(self, edges: List[List[int]]) -> int:
if edges[0][0]==edges[1][0] or edges[0][0]==edges[1][1]:
return edges[0][0]
return edges[0][1] | find-center-of-star-graph | Python solution beats 88.99% in memory usage | Just_03 | 0 | 4 | find center of star graph | 1,791 | 0.835 | Easy | 25,661 |
https://leetcode.com/problems/find-center-of-star-graph/discuss/2796390/Python-1-line-solution-O(1)-timespace-without-if's | class Solution:
def findCenter(self, edges: List[List[int]]) -> int:
return set(edges[0]).intersection(set(edges[1])).pop() | find-center-of-star-graph | Python 1-line solution O(1) time/space - without if's | gleberof | 0 | 8 | find center of star graph | 1,791 | 0.835 | Easy | 25,662 |
https://leetcode.com/problems/find-center-of-star-graph/discuss/2759517/100-Fastest-O(1)-Python-solution-oror-Intuition-Code-Time-and-Space-Complexity-Explained | class Solution:
def findCenter(self, edges: List[List[int]]) -> int:
return list(set(edges[0])&set(edges[1]))[0] | find-center-of-star-graph | 100% Fastest O(1) Python solution || Intuition, Code, Time and Space Complexity Explained | tkdhimanshusingh | 0 | 8 | find center of star graph | 1,791 | 0.835 | Easy | 25,663 |
https://leetcode.com/problems/find-center-of-star-graph/discuss/2721597/Beats-98.73ororSimpleororPython3 | class Solution:
def findCenter(self, edges: List[List[int]]) -> int:
m=len(edges)
output=[]
for i in edges:
for j in i:
output.append(j)
for i in output:
if output.count(i)==m:
return i | find-center-of-star-graph | Beats 98.73%||Simple||Python3 | sowmika_chaluvadi | 0 | 6 | find center of star graph | 1,791 | 0.835 | Easy | 25,664 |
https://leetcode.com/problems/find-center-of-star-graph/discuss/2705235/Simple-Python-solution | class Solution:
def findCenter(self, edges: List[List[int]]) -> int:
if (edges[0][0] == edges[1][0] or edges[0][0] == edges[1][1]):
return edges[0][0]
return edges[0][1]
# 0r
# return next(iter(set(edges[0]) & set(edges[1]))) | find-center-of-star-graph | Simple Python solution | Baboolal | 0 | 5 | find center of star graph | 1,791 | 0.835 | Easy | 25,665 |
https://leetcode.com/problems/find-center-of-star-graph/discuss/2704803/Python3-O(1)-solution | class Solution:
def findCenter(self, edges: List[List[int]]) -> int:
i, j = edges[0][0], edges[0][1]
if i in edges[1]:
return i
else:
return j | find-center-of-star-graph | Python3 O(1) solution | sipi09 | 0 | 3 | find center of star graph | 1,791 | 0.835 | Easy | 25,666 |
https://leetcode.com/problems/find-center-of-star-graph/discuss/2698631/Easy-or-Python-Solution-or-HashMaps | class Solution:
def findCenter(self, edges: List[List[int]]) -> int:
maps = {}
count = len(edges)
for path in edges:
for i in path:
if i in maps:
maps[i] += 1
else:
maps[i] = 1
sorted_map = [k for k, v in sorted(maps.items(), key=lambda a:a[1], reverse=True)]
return sorted_map[0] | find-center-of-star-graph | Easy | Python Solution | HashMaps | atharva77 | 0 | 4 | find center of star graph | 1,791 | 0.835 | Easy | 25,667 |
https://leetcode.com/problems/find-center-of-star-graph/discuss/2662178/python3-one-line-of-code-faster-than-93.81 | class Solution:
def findCenter(self, edges: List[List[int]]) -> int:
return set(edges[0]).intersection(set(edges[1])).pop() | find-center-of-star-graph | python3 one line of code, faster than 93.81% | samanehghafouri | 0 | 10 | find center of star graph | 1,791 | 0.835 | Easy | 25,668 |
https://leetcode.com/problems/find-center-of-star-graph/discuss/2589772/Simple-python-solution | class Solution(object):
def findCenter(self, edges):
"""
:type edges: List[List[int]]
:rtype: int
"""
maps = [0] * (len(edges) + 2)
for edge in edges:
maps[edge[0]] += 1
maps[edge[1]] += 1
return maps.index(max(maps)) | find-center-of-star-graph | Simple python solution | Gilbert770 | 0 | 44 | find center of star graph | 1,791 | 0.835 | Easy | 25,669 |
https://leetcode.com/problems/find-center-of-star-graph/discuss/2580996/Python-solution-with-O(v%2Be) | class Solution:
def adjacencyList(self,List):
graph = {}
for e in List:
if e[0] in graph.keys():
graph[e[0]].append(e[1])
else:
graph[e[0]]=[e[1]]
if e[1] in graph.keys():
graph[e[1]].append(e[0])
else:
graph[e[1]]=[e[0]]
return graph
def findCenter(self, edges: List[List[int]]) -> int:
max_len = 0
star = 0
graph = self.adjacencyList(edges)
# find the vertex having maximum no of edges connected with it
# that vertex will be the start vertex
for item in graph:
if len(graph[item]) >= max_len:
# here counting vertex with maximum children
max_len = len(graph[item])
star = item
return star | find-center-of-star-graph | Python solution with O(v+e) | ronipaul9972 | 0 | 41 | find center of star graph | 1,791 | 0.835 | Easy | 25,670 |
https://leetcode.com/problems/find-center-of-star-graph/discuss/2519577/Python-O(n)-time-complexity-beats-90-detailed-explanation | class Solution:
def findCenter(self, edges: List[List[int]]) -> int:
'''Time complexity: O(n)'''
# the center is the common number in all the lists within the list
# take the first list in the list of lists
# iterate through the rest of list and finding if the elements in the first list exists in the each list
# since the question states that it always represents a valid star graph, we can assume that element i is center as long as element j is not present in any of the list
# we can use any function to achieve that
if not any(edges[0][0] not in item for item in edges[1:]):
return edges[0][0]
else:
return edges[0][1] | find-center-of-star-graph | [Python] O(n) time complexity, beats 90% - detailed explanation | romejj | 0 | 66 | find center of star graph | 1,791 | 0.835 | Easy | 25,671 |
https://leetcode.com/problems/find-center-of-star-graph/discuss/2337112/Python3-or-Faster-than-99.75-or-Simple-one-liner | class Solution:
def findCenter(self, edges: List[List[int]]) -> int:
return set(edges[0]).intersection(edges[1]).pop() | find-center-of-star-graph | Python3 | Faster than 99.75% | Simple one liner | prameshbajra | 0 | 107 | find center of star graph | 1,791 | 0.835 | Easy | 25,672 |
https://leetcode.com/problems/find-center-of-star-graph/discuss/2155489/Python-adjacency-list-solution | class Solution:
def findCenter(self, edges: List[List[int]]) -> int:
adj = {i:[] for i in range(1, len(edges)+2)}
for a,b in edges:
adj[a].append(b)
adj[b].append(a)
for k, v in adj.items():
if len(v) == len(edges):
return k | find-center-of-star-graph | Python adjacency list solution | maj3r | 0 | 105 | find center of star graph | 1,791 | 0.835 | Easy | 25,673 |
https://leetcode.com/problems/find-center-of-star-graph/discuss/2106011/Find-Center-of-Star-Graph | class Solution:
def findCenter(self, edges: List[List[int]]) -> int:
graph = {}
for a,b in edges:
graph[a] = b
count = {}
for key,value in graph.items():
if key in count:
count[key] +=1
else:
count[key] = 1
if value in count:
count[value] +=1
else:
count[value] = 1
maxCo = 0
for key,value in count.items():
if value > maxCo:
maxCo = key
return maxCo | find-center-of-star-graph | Find Center of Star Graph | somendrashekhar2199 | 0 | 57 | find center of star graph | 1,791 | 0.835 | Easy | 25,674 |
https://leetcode.com/problems/find-center-of-star-graph/discuss/2001796/Python-Easy-solution | class Solution:
def findCenter(self, edges: List[List[int]]) -> int:
adj = [[] for _ in range(len(edges)+2)]
for i, j in edges:
adj[i].append(j)
adj[j].append(i)
for i in range(len(adj)):
if len(adj[i]) == len(edges):
return i | find-center-of-star-graph | Python Easy solution | Ashi_garg | 0 | 128 | find center of star graph | 1,791 | 0.835 | Easy | 25,675 |
https://leetcode.com/problems/find-center-of-star-graph/discuss/1930921/python-3-oror-O(1)O(1) | class Solution:
def findCenter(self, edges: List[List[int]]) -> int:
a, b = edges[0]
c, d = edges[1]
return a if a == c or a == d else b | find-center-of-star-graph | python 3 || O(1)/O(1) | dereky4 | 0 | 89 | find center of star graph | 1,791 | 0.835 | Easy | 25,676 |
https://leetcode.com/problems/find-center-of-star-graph/discuss/1910657/Python-Solution | class Solution:
def findCenter(self, edges: List[List[int]]) -> int:
return (edges[0][1], edges[0][0])[edges[0][0] in edges[1]] | find-center-of-star-graph | Python Solution | hgalytoby | 0 | 52 | find center of star graph | 1,791 | 0.835 | Easy | 25,677 |
https://leetcode.com/problems/find-center-of-star-graph/discuss/1896680/Python3-Dynamic-List-or-faster-than-80-or-less-than-92-or-Two-Solution | class Solution:
def findCenter(self, edges: List[List[int]]) -> int:
sets = []
for k in edges[:2]:
sets = self.statis(sets, k[0])
sets = self.statis(sets, k[1])
return sets.index(max(sets))+1
def statis(self, sets, k):
gen = lambda sz:[0]*(sz-len(sets)-1)+[1]
if k > len(sets):
sets += gen(k)
else:
sets[k-1] += 1
return sets | find-center-of-star-graph | ✔Python3 Dynamic List | faster than 80% | less than 92% | Two Solution | khRay13 | 0 | 44 | find center of star graph | 1,791 | 0.835 | Easy | 25,678 |
https://leetcode.com/problems/find-center-of-star-graph/discuss/1896680/Python3-Dynamic-List-or-faster-than-80-or-less-than-92-or-Two-Solution | class Solution:
def findCenter(self, edges: List[List[int]]) -> int:
return (set(edges[0]) & set(edges[1])).pop() | find-center-of-star-graph | ✔Python3 Dynamic List | faster than 80% | less than 92% | Two Solution | khRay13 | 0 | 44 | find center of star graph | 1,791 | 0.835 | Easy | 25,679 |
https://leetcode.com/problems/find-center-of-star-graph/discuss/1866333/Python3-Easy-Solution | class Solution:
def findCenter(self, edges: List[List[int]]) -> int:
a, b = edges[0][0], edges[0][1]
i = 1
while i < len(edges[0]):
for edge in edges[1:]:
if a in edge:
r = a
elif b in edge:
r = b
i += 1
return r | find-center-of-star-graph | [Python3] Easy Solution | natscripts | 0 | 78 | find center of star graph | 1,791 | 0.835 | Easy | 25,680 |
https://leetcode.com/problems/find-center-of-star-graph/discuss/1852744/Python-One-Liner | class Solution:
def findCenter(self, edges: List[List[int]]) -> int:
return edges[0][0] if edges[0][0] in edges[1] else edges[0][1] | find-center-of-star-graph | Python One Liner | AjayKadiri | 0 | 38 | find center of star graph | 1,791 | 0.835 | Easy | 25,681 |
https://leetcode.com/problems/find-center-of-star-graph/discuss/1804958/sets-intersection | class Solution:
def findCenter(self, edges: List[List[int]]) -> int:
return set.intersection(*[set(x) for x in edges]).pop() | find-center-of-star-graph | sets intersection | denizen-ru | 0 | 26 | find center of star graph | 1,791 | 0.835 | Easy | 25,682 |
https://leetcode.com/problems/find-center-of-star-graph/discuss/1562599/Python-Solution-oror-O(1)-time | class Solution:
def findCenter(self, edges: List[List[int]]) -> int:
first, second = edges[0][0], edges[0][1]
if first == edges[1][0] or first == edges[1][1]:
return first
return second | find-center-of-star-graph | Python Solution || O(1) time | s_m_d_29 | 0 | 63 | find center of star graph | 1,791 | 0.835 | Easy | 25,683 |
https://leetcode.com/problems/find-center-of-star-graph/discuss/1531366/One-line-no-extra-variables-98-speed | class Solution:
def findCenter(self, edges: List[List[int]]) -> int:
return (set(edges[0]) & set(edges[1])).pop() | find-center-of-star-graph | One line, no extra variables, 98% speed | EvgenySH | 0 | 77 | find center of star graph | 1,791 | 0.835 | Easy | 25,684 |
https://leetcode.com/problems/find-center-of-star-graph/discuss/1395368/Find-Center-of-Star-Graph-(THE-OG-SOLUTION-OF-DECADE) | class Solution:
def findCenter(self, edges: List[List[int]]) -> int:
a_set = set(edges[0])
b_set = set(edges[1])
if a_set and b_set:
c=a_set and b_set
d = list(c)
return(d[0]) | find-center-of-star-graph | Find Center of Star Graph (THE OG SOLUTION OF DECADE) | _rakshitkapoor_ | 0 | 149 | find center of star graph | 1,791 | 0.835 | Easy | 25,685 |
https://leetcode.com/problems/find-center-of-star-graph/discuss/1343048/Easy-Python-Solution(96.66) | class Solution:
def findCenter(self, edges: List[List[int]]) -> int:
f=edges[0][0]
s=edges[0][1]
if(f in edges[1]):
return f
else:
return s | find-center-of-star-graph | Easy Python Solution(96.66%) | Sneh17029 | 0 | 472 | find center of star graph | 1,791 | 0.835 | Easy | 25,686 |
https://leetcode.com/problems/find-center-of-star-graph/discuss/1341119/Python-graph-solution-without-using-any-built-in-library | class Solution:
def __init__(self):
self.no_of_nodes = 0
self.adjacency_list = {}
def findCenter(self, edges: List[List[int]]) -> int:
for node in edges:
if node[0] not in self.adjacency_list: self.adjacency_list[node[0]] = []
if node[1] not in self.adjacency_list: self.adjacency_list[node[1]] = []
if node[1] not in self.adjacency_list[node[0]]:
self.adjacency_list[node[0]].append(node[1])
self.adjacency_list[node[1]].append(node[0])
if len(self.adjacency_list[node[0]])>1: return node[0]
if len(self.adjacency_list[node[1]])>1: return node[1] | find-center-of-star-graph | Python graph solution without using any built in library | prajwal_vs | 0 | 189 | find center of star graph | 1,791 | 0.835 | Easy | 25,687 |
https://leetcode.com/problems/find-center-of-star-graph/discuss/1275708/Python3-simple-%22one-liner%22-solution | class Solution:
def findCenter(self, edges: List[List[int]]) -> int:
return edges[0][0] if edges[0][0] in edges[1] else edges[0][1] | find-center-of-star-graph | Python3 simple "one-liner" solution | EklavyaJoshi | 0 | 115 | find center of star graph | 1,791 | 0.835 | Easy | 25,688 |
https://leetcode.com/problems/find-center-of-star-graph/discuss/1261871/assign-scores-to-each-node | class Solution:
def findCenter(self, edges: List[List[int]]) -> int:
n = len(edges)
scores = [0] * ((n+1)+1)
for a,b in edges:
scores[a] += 1
scores[b] += 1
for i, score in enumerate(scores):
if score == n:
return i | find-center-of-star-graph | assign scores to each node | uzumaki01 | 0 | 70 | find center of star graph | 1,791 | 0.835 | Easy | 25,689 |
https://leetcode.com/problems/find-center-of-star-graph/discuss/1161397/Python-Easy-Hash-Question | class Solution:
def findCenter(self, edges: List[List[int]]) -> int:
#Complexity - O(N)*O(1) O(N)
d={}
for i in edges:
if i[0] not in d:
d[i[0]]=1
elif i[0] in d:
d[i[0]]+=1
if i[1] not in d:
d[i[1]]=1
elif i[1] in d:
d[i[1]]+=1
n=len(d)
for i in d:
if d[i]==n-1:
return i
return n | find-center-of-star-graph | Python, Easy Hash Question | iamkshitij77 | 0 | 143 | find center of star graph | 1,791 | 0.835 | Easy | 25,690 |
https://leetcode.com/problems/find-center-of-star-graph/discuss/1131449/Python-3-O(1)-Time-and-Space | class Solution:
def findCenter(self, edges: List[List[int]]) -> int:
u,v = edges[0]
return u if u in edges[1] else v | find-center-of-star-graph | Python 3 O(1) Time & Space | leeteatsleep | 0 | 200 | find center of star graph | 1,791 | 0.835 | Easy | 25,691 |
https://leetcode.com/problems/find-center-of-star-graph/discuss/1121104/Python3-solution-with-explanation-(Better-than-100-in-time-and-space)-(O(n)) | class Solution:
def findCenter(self, edges: List[List[int]]) -> int:
dic = {}
for i in edges:
dic[i[0]] = dic.get(i[0],0) + 1
dic[i[1]] = dic.get(i[1],0) + 1
n = len(dic.keys())
for i in dic.keys():
if dic[i] == n-1:
return i | find-center-of-star-graph | Python3 solution with explanation (Better than 100% in time and space) (O(n)) | kevin_bony | 0 | 91 | find center of star graph | 1,791 | 0.835 | Easy | 25,692 |
https://leetcode.com/problems/find-center-of-star-graph/discuss/1114742/Python-two-one-liners | class Solution:
def findCenter(self, edges: List[List[int]]) -> int:
return (set(edges[0]) & set(edges[1])).pop() | find-center-of-star-graph | Python, two one liners | blue_sky5 | 0 | 93 | find center of star graph | 1,791 | 0.835 | Easy | 25,693 |
https://leetcode.com/problems/find-center-of-star-graph/discuss/1112160/python-3-solution-faster-than-the-100-solution-in-O(1)-time-complexity-one-liner | class Solution:
def findCenter(self, edges: List[List[int]]) -> int:
y=list(set(edges[0]).intersection(set(edges[1])))
return y[0] | find-center-of-star-graph | python 3 solution faster than the 100% solution in O(1) time complexity one liner | Underdog2000 | 0 | 147 | find center of star graph | 1,791 | 0.835 | Easy | 25,694 |
https://leetcode.com/problems/find-center-of-star-graph/discuss/1108719/Python-solution | class Solution:
def findCenter(self, edges: List[List[int]]) -> int:
center_set = set(edges[0])
for edge in edges[1:]:
center_set &= set(edge)
return center_set.pop() | find-center-of-star-graph | Python solution | zonda_yang | 0 | 51 | find center of star graph | 1,791 | 0.835 | Easy | 25,695 |
https://leetcode.com/problems/find-center-of-star-graph/discuss/1108661/Python-simple-solution | class Solution:
def findCenter(self, edge: List[List[int]]) -> int:
if edge[0][0] in edge[1]:
return edge[0][0]
else:
return edge[0][1] | find-center-of-star-graph | Python simple solution | abhisek_ | 0 | 48 | find center of star graph | 1,791 | 0.835 | Easy | 25,696 |
https://leetcode.com/problems/maximum-average-pass-ratio/discuss/1108491/Python-100-Efficient-solution-easy-to-understand-with-comments-and-explanation | class Solution:
def maxAverageRatio(self, classes: List[List[int]], extraStudents: int) -> float:
n = len(classes)
impacts = [0]*n
minRatioIndex = 0
# calculate and store impacts for each class in form of tuples -> (-impactValue, passCount, totalCount)
for i in range(n):
passCount = classes[i][0]
totalCount = classes[i][1]
# calculate the impact for class i
currentRatio = passCount/totalCount
expectedRatioAfterUpdate = (passCount+1)/(totalCount+1)
impact = expectedRatioAfterUpdate - currentRatio
impacts[i] = (-impact, passCount, totalCount) # note the - sign for impact
heapq.heapify(impacts)
while(extraStudents > 0):
# pick the next class with greatest impact
_, passCount, totalCount = heapq.heappop(impacts)
# assign a student to the class
passCount+=1
totalCount+=1
# calculate the updated impact for current class
currentRatio = passCount/totalCount
expectedRatioAfterUpdate = (passCount+1)/(totalCount+1)
impact = expectedRatioAfterUpdate - currentRatio
# insert updated impact back into the heap
heapq.heappush(impacts, (-impact, passCount, totalCount))
extraStudents -= 1
result = 0
# for all the updated classes calculate the total passRatio
for _, passCount, totalCount in impacts:
result += passCount/totalCount
# return the average pass ratio
return result/n | maximum-average-pass-ratio | [Python] 100% Efficient solution, easy to understand with comments and explanation | CaptainX | 14 | 1,000 | maximum average pass ratio | 1,792 | 0.521 | Medium | 25,697 |
https://leetcode.com/problems/maximum-average-pass-ratio/discuss/1280681/python-heap-solution | class Solution:
def maxAverageRatio(self, classes: List[List[int]], e: int) -> float:
heap=[]
for i,j in classes:
diff=(i+1)/(j+1)-(i/j)
heapq.heappush(heap,(-diff,i,j))
while(e>0):
diff,i,j=heapq.heappop(heap)
i+=1
j+=1
diff=(i+1)/(j+1)-(i/j)
heapq.heappush(heap,(-diff,i,j))
e-=1
ans=0
for diff,i,j in heap:
ans+=(i/j)
return ans/len(classes) | maximum-average-pass-ratio | python heap solution | heisenbarg | 2 | 131 | maximum average pass ratio | 1,792 | 0.521 | Medium | 25,698 |
https://leetcode.com/problems/maximum-average-pass-ratio/discuss/1998238/Simple-python-solution-using-heap | class Solution:
def maxAverageRatio(self, classes: List[List[int]], extraStudents: int) -> float:
H=[]
for i in range(len(classes)):
p,t=classes[i]
heapq.heappush(H,(((p/t)-((p+1)/(t+1))),p,t))
while extraStudents>0:
x,y,z=heapq.heappop(H)
y+=1
z+=1
heapq.heappush(H,(((y/z)-((y+1)/(z+1))),y,z))
extraStudents-=1
sm=0
for x,y,z in H:
sm+=(y/z)
return sm/len(classes) | maximum-average-pass-ratio | Simple python solution using heap | pbhuvaneshwar | 1 | 129 | maximum average pass ratio | 1,792 | 0.521 | Medium | 25,699 |
Subsets and Splits
Top 2 Solutions by Upvotes
Identifies the top 2 highest upvoted Python solutions for each problem, providing insight into popular approaches.