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/reverse-substrings-between-each-pair-of-parentheses/discuss/2290806/PYTHON-SOL-or-RECURSION-AND-STACK-SOL-or-DETAILED-EXPLANATION-WITH-PICTRUE-or
class Solution: def reverseParentheses(self, s: str) -> str: def solve(string): n = len(string) word = "" i = 0 while i <n: if string[i] == '(': new = "" count = 0 while True: count += 1 if string[i] == '(' else -1 if string[i] == ')' else 0 if count == 0: break new += string[i] i += 1 i += 1 word += solve(new[1:]) else: word += string[i] i += 1 return word[::-1] return solve(s)[::-1]
reverse-substrings-between-each-pair-of-parentheses
PYTHON SOL | RECURSION AND STACK SOL | DETAILED EXPLANATION WITH PICTRUE |
reaper_27
4
123
reverse substrings between each pair of parentheses
1,190
0.658
Medium
18,100
https://leetcode.com/problems/reverse-substrings-between-each-pair-of-parentheses/discuss/2290806/PYTHON-SOL-or-RECURSION-AND-STACK-SOL-or-DETAILED-EXPLANATION-WITH-PICTRUE-or
class Solution: def reverseParentheses(self, s: str) -> str: stack = [] for i in s: if i == ')': tmp = "" while stack[-1] != '(': tmp += stack.pop() stack.pop() for j in tmp: stack.append(j) else: stack.append(i) return "".join(stack)
reverse-substrings-between-each-pair-of-parentheses
PYTHON SOL | RECURSION AND STACK SOL | DETAILED EXPLANATION WITH PICTRUE |
reaper_27
4
123
reverse substrings between each pair of parentheses
1,190
0.658
Medium
18,101
https://leetcode.com/problems/reverse-substrings-between-each-pair-of-parentheses/discuss/382379/Python3-regex-find
class Solution: def reverseParentheses(self, s: str) -> str: while '(' in s: posopen=s.rfind('(') posclose=s.find(')',posopen+1) s=s[:posopen]+s[posopen+1:posclose][::-1]+s[posclose+1:] return s
reverse-substrings-between-each-pair-of-parentheses
Python3 regex find
aj_to_rescue
3
120
reverse substrings between each pair of parentheses
1,190
0.658
Medium
18,102
https://leetcode.com/problems/reverse-substrings-between-each-pair-of-parentheses/discuss/1079296/Python-FASTER-THAN-98-SUBMISSION-Using-Stack-and-Array
class Solution: def reverseParentheses(self, s: str) -> str: stk,arr=[],[] for i in s: if i!=')': stk.append(i) else: popele=stk.pop() while popele!='(': arr.append(popele) popele=stk.pop() for j in arr: stk.append(j) arr=[] ans='' for k in stk: ans+=k return ans ```
reverse-substrings-between-each-pair-of-parentheses
[Python] FASTER THAN 98% SUBMISSION, Using Stack and Array
jayrathore070
1
181
reverse substrings between each pair of parentheses
1,190
0.658
Medium
18,103
https://leetcode.com/problems/reverse-substrings-between-each-pair-of-parentheses/discuss/2695464/Python-O(N)-O(N)
class Solution: def reverseParentheses(self, s: str) -> str: stack = [] for char in s: if char != ")": stack.append(char) continue current = [] while stack[-1] != "(": current.append(stack.pop()) stack.pop() stack += current return "".join(stack)
reverse-substrings-between-each-pair-of-parentheses
Python - O(N), O(N)
Teecha13
0
9
reverse substrings between each pair of parentheses
1,190
0.658
Medium
18,104
https://leetcode.com/problems/reverse-substrings-between-each-pair-of-parentheses/discuss/2587019/python-stack-solution-with-explanation
class Solution: def reverseParentheses(self, s: str) -> str: stack = deque() for i in s: if i == ')': c = "" while stack[-1] != '(': c += stack.pop() stack.pop() for j in c: stack.append(j) else: stack.append(i) return "".join(stack)
reverse-substrings-between-each-pair-of-parentheses
python stack solution with explanation
pandish
0
30
reverse substrings between each pair of parentheses
1,190
0.658
Medium
18,105
https://leetcode.com/problems/reverse-substrings-between-each-pair-of-parentheses/discuss/2206705/97-faster-solution-or-python-or-easy-implementation-using-stack
class Solution: def reverseParentheses(self, s: str) -> str: stack=[] left=0 right=len(s) while left<right: if s[left]!=")": stack.append(s[left]) left+=1 else: st="" while stack and stack[-1]!="(": st+=stack.pop() if stack: stack.pop() if st: for i in st: stack.append(i) left+=1 return "".join(stack)
reverse-substrings-between-each-pair-of-parentheses
97% faster solution | python | easy implementation using stack
glimloop
0
95
reverse substrings between each pair of parentheses
1,190
0.658
Medium
18,106
https://leetcode.com/problems/reverse-substrings-between-each-pair-of-parentheses/discuss/2178205/Easy-to-understand-oror-python
class Solution: def reverseParentheses(self, s: str) -> str: stack = [] for i in range(0,len(s)): if(s[i] == "("): stack.append(s[i]) elif(s[i] >= "a" and s[i] <= "z"): stack.append(s[i]) else: s1 = "" while len(stack) > 0 : a = stack.pop() if(a == "("): break s1 = a + s1 s1 = s1[::-1] for i in s1: stack.append(i) s1 = "" for i in stack: s1 = s1 + i return s1
reverse-substrings-between-each-pair-of-parentheses
Easy to understand || python
MB16biwas
0
55
reverse substrings between each pair of parentheses
1,190
0.658
Medium
18,107
https://leetcode.com/problems/reverse-substrings-between-each-pair-of-parentheses/discuss/1912870/Python-easy-to-read-and-understand-or-stack
class Solution: def reverseParentheses(self, s: str) -> str: stack = [] for i in range(len(s)): if s[i] == ")": temp = "" while stack and stack[-1] != "(": temp += stack.pop() stack.pop() for ch in temp: stack.append(ch) else: stack.append(s[i]) res = "" for word in stack: res += word return res
reverse-substrings-between-each-pair-of-parentheses
Python easy to read and understand | stack
sanial2001
0
98
reverse substrings between each pair of parentheses
1,190
0.658
Medium
18,108
https://leetcode.com/problems/reverse-substrings-between-each-pair-of-parentheses/discuss/1867932/Python-or-Recursion
class Solution: def reverseParentheses(self, s: str) -> str: def dfs(i): curr='' while i<len(s): if s[i]=='(': ans,i=dfs(i+1) curr+=ans elif s[i]==')': return curr[::-1],i else: curr+=s[i] i+=1 return curr return dfs(0)
reverse-substrings-between-each-pair-of-parentheses
Python | Recursion
heckt27
0
53
reverse substrings between each pair of parentheses
1,190
0.658
Medium
18,109
https://leetcode.com/problems/reverse-substrings-between-each-pair-of-parentheses/discuss/1576385/Python3-Solution-with-using-stack
class Solution: def reverseParentheses(self, s: str) -> str: stack = [[]] for c in s: if c == '(': stack.append([]) elif c == ')': last_chain = stack.pop() stack[-1] += last_chain[::-1] else: stack[-1].append(c) return ''.join(stack[-1])
reverse-substrings-between-each-pair-of-parentheses
[Python3] Solution with using stack
maosipov11
0
72
reverse substrings between each pair of parentheses
1,190
0.658
Medium
18,110
https://leetcode.com/problems/reverse-substrings-between-each-pair-of-parentheses/discuss/1387821/Python-Stack
class Solution: def reverseParentheses(self, s: str) -> str: result, stack = "", [] for c in s: if c == "(": stack += [""] elif c == ")": temp = "".join(stack.pop())[::-1] if stack: stack[-1] += temp else: result += temp elif stack: stack[-1] += c else: result += c return result
reverse-substrings-between-each-pair-of-parentheses
[Python] Stack
dev-josh
0
127
reverse substrings between each pair of parentheses
1,190
0.658
Medium
18,111
https://leetcode.com/problems/reverse-substrings-between-each-pair-of-parentheses/discuss/1363086/Python3-solution-using-stack
class Solution: def reverseParentheses(self, s: str) -> str: st = [] for i in s: if i == ')': l = [] while st[-1] != '(': l.append(st.pop()) st.pop() st.extend(l) else: st.append(i) return ''.join(st)
reverse-substrings-between-each-pair-of-parentheses
Python3 solution using stack
EklavyaJoshi
0
51
reverse substrings between each pair of parentheses
1,190
0.658
Medium
18,112
https://leetcode.com/problems/reverse-substrings-between-each-pair-of-parentheses/discuss/1325923/Python3-Stack-approach
class Solution: def reverseParentheses(self, s: str) -> str: stack = [] ln = len(s) for i in range(ln): if s[i] != ')': stack.append(s[i]) else: reverse = [] while stack and stack[-1] != '(': reverse.append(stack.pop()) if stack and stack[-1] == '(': stack.pop() for k in reverse: stack.append(k) return ''.join(stack)
reverse-substrings-between-each-pair-of-parentheses
[Python3] Stack approach
sann2011
0
39
reverse substrings between each pair of parentheses
1,190
0.658
Medium
18,113
https://leetcode.com/problems/reverse-substrings-between-each-pair-of-parentheses/discuss/1267913/python-beats-95-or
class Solution: def reverseParentheses(self, s: str) -> str: s=list(s) u=[] while s: a=s.pop(0) if a!=')': u.append(a) else: p=[] while True: x=u.pop() if x=='(': u+=p break else: p.append(x) return ''.join(u)
reverse-substrings-between-each-pair-of-parentheses
python beats 95% |
chikushen99
0
103
reverse substrings between each pair of parentheses
1,190
0.658
Medium
18,114
https://leetcode.com/problems/reverse-substrings-between-each-pair-of-parentheses/discuss/1232204/Python-Simple-Straightforward-Easy-Understand-Stack-Solution
class Solution: def reverseParentheses(self, s: str) -> str: stack = [] for ele in s: if ele.isalpha() or ele == '(': stack.append(ele) else: temp = [] while stack[-1] and stack[-1] != '(': temp.append(stack.pop()) if stack[-1] == '(': stack.pop() stack.extend(temp) return "".join(stack)
reverse-substrings-between-each-pair-of-parentheses
[Python] Simple, Straightforward, Easy Understand, Stack Solution
Ruifeng_Wang
0
129
reverse substrings between each pair of parentheses
1,190
0.658
Medium
18,115
https://leetcode.com/problems/reverse-substrings-between-each-pair-of-parentheses/discuss/1155426/Python3-stack
class Solution: def reverseParentheses(self, s: str) -> str: stack = [""] for c in s: if c == "(": stack.append("") elif c == ")": val = stack.pop()[::-1] stack[-1] += val else: stack[-1] += c return stack.pop()
reverse-substrings-between-each-pair-of-parentheses
[Python3] stack
ye15
0
67
reverse substrings between each pair of parentheses
1,190
0.658
Medium
18,116
https://leetcode.com/problems/reverse-substrings-between-each-pair-of-parentheses/discuss/1155426/Python3-stack
class Solution: def reverseParentheses(self, s: str) -> str: stack = [] mp = {} for i, c in enumerate(s): if c == "(": stack.append(i) elif c == ")": k = stack.pop() mp[i], mp[k] = k, i ans = [] i, ii = 0, 1 while i < len(s): if s[i] in "()": i = mp[i] ii *= -1 else: ans.append(s[i]) i += ii return "".join(ans)
reverse-substrings-between-each-pair-of-parentheses
[Python3] stack
ye15
0
67
reverse substrings between each pair of parentheses
1,190
0.658
Medium
18,117
https://leetcode.com/problems/reverse-substrings-between-each-pair-of-parentheses/discuss/414098/Python-100-memory-with-Comments%3A-Easy-Understand
class Solution: def reverseParentheses(self, s: str) -> str: #Take an empty stack for iteration stack = [] for i in range(0, len(s)): # If the current charector is anything other than closing bracket append it if s[i] != ')': stack.append(s[i]) else: k = [] #pop the elements from the stack and reverse place it back to the stack until the opening brace is found while len(stack)!=0 and stack[-1]!='(': k.append(stack.pop()) #Pop the ')' opening brace stack.pop() k = k[::-1] while len(k)!=0: stack.append(k.pop()) #return Stack return "".join(stack)
reverse-substrings-between-each-pair-of-parentheses
Python 100% memory with Comments: Easy Understand
kottapallicharan
0
178
reverse substrings between each pair of parentheses
1,190
0.658
Medium
18,118
https://leetcode.com/problems/reverse-substrings-between-each-pair-of-parentheses/discuss/382563/Two-Solutions-in-Python-3-(beats-100.0-)-(three-lines)
class Solution: def reverseParentheses(self, s: str) -> str: L = [i for i,j in enumerate(s) if j == '('] while L: s = (lambda x,y: s[0:x]+s[x+1:y][::-1]+s[y+1:])(L[-1],s.index(')',L.pop()+1)) return s
reverse-substrings-between-each-pair-of-parentheses
Two Solutions in Python 3 (beats 100.0 %) (three lines)
junaidmansuri
-1
207
reverse substrings between each pair of parentheses
1,190
0.658
Medium
18,119
https://leetcode.com/problems/reverse-substrings-between-each-pair-of-parentheses/discuss/382563/Two-Solutions-in-Python-3-(beats-100.0-)-(three-lines)
class Solution: def reverseParentheses(self, s: str) -> str: j, s, S = 0, list(s)+[''], [] while s[j]: if s[j] == '(': S.append(j) elif s[j] == ')': i = S.pop() s, j = s[0:i]+s[i+1:j][::-1]+s[j+1:], i-1 j += 1 return "".join(s) - Junaid Mansuri (LeetCode ID)@hotmail.com
reverse-substrings-between-each-pair-of-parentheses
Two Solutions in Python 3 (beats 100.0 %) (three lines)
junaidmansuri
-1
207
reverse substrings between each pair of parentheses
1,190
0.658
Medium
18,120
https://leetcode.com/problems/reverse-substrings-between-each-pair-of-parentheses/discuss/1145106/Python-Stack-Solution-or-O(n)-time-O(n)-space
class Solution: def reverseParentheses(self, s: str) -> str: stack = [] i = 0 while i < len(s): while i < len(s) and s[i] != ")": stack.append(s[i]) i += 1 temp = "" if i < len(s) and s[i] == ")": while stack[-1] != "(": temp += stack.pop() i += 1 stack.pop() if temp != "": for letter in temp: stack.append(letter) return "".join(stack)
reverse-substrings-between-each-pair-of-parentheses
Python Stack Solution | O(n) time O(n) space
vanigupta20024
-3
108
reverse substrings between each pair of parentheses
1,190
0.658
Medium
18,121
https://leetcode.com/problems/k-concatenation-maximum-sum/discuss/2201976/Python-easy-to-read-and-understand-or-kadane
class Solution: def kadane(self, nums): for i in range(1, len(nums)): if nums[i-1] > 0: nums[i] += nums[i-1] return max(max(nums), 0) def kConcatenationMaxSum(self, arr: List[int], k: int) -> int: sums = sum(arr) mod = 10**9 + 7 if k == 1: return self.kadane(arr) % (mod) if sums > 0: return (self.kadane(arr+arr) + (k-2)*sums) % (mod) else: return self.kadane(arr+arr) % (mod)
k-concatenation-maximum-sum
Python easy to read and understand | kadane
sanial2001
2
147
k concatenation maximum sum
1,191
0.239
Medium
18,122
https://leetcode.com/problems/k-concatenation-maximum-sum/discuss/1155407/Python3-Kadane's-algo
class Solution: def kConcatenationMaxSum(self, arr: List[int], k: int) -> int: rsm = val = 0 sm = sum(arr) if k > 1: arr *= 2 for x in arr: val = max(0, val + x) rsm = max(rsm, val) return max(rsm, rsm + max(0, k-2)*sm) % 1_000_000_007
k-concatenation-maximum-sum
[Python3] Kadane's algo
ye15
1
157
k concatenation maximum sum
1,191
0.239
Medium
18,123
https://leetcode.com/problems/k-concatenation-maximum-sum/discuss/2810564/Python-(Simple-Dynamic-Programming)
class Solution: def kadane(self,ans): max_sum_so_far, max_ending_here = ans[0], ans[0] for i in ans[1:]: max_ending_here = max(max_ending_here+i,i) max_sum_so_far = max(max_sum_so_far,max_ending_here) return max_sum_so_far def kConcatenationMaxSum(self, arr, k): if k == 1: return self.kadane(arr)%(10**9+7) else: return ((k-2)*max(sum(arr),0) + max(self.kadane(arr*2),0))%(10**9+7)
k-concatenation-maximum-sum
Python (Simple Dynamic Programming)
rnotappl
0
1
k concatenation maximum sum
1,191
0.239
Medium
18,124
https://leetcode.com/problems/k-concatenation-maximum-sum/discuss/2295009/PYTHON-or-KADANE-ALGO-or-DETAILED-EXPLANATION-WITH-PICTURE-or-INTUITIVE-or
class Solution: def kConcatenationMaxSum(self, arr: List[int], k: int) -> int: n = len(arr) if n == 0: return 0 summ,gmax,cmax,gmin,cmin = arr[0],arr[0],arr[0],arr[0],arr[0] for i in range(1,n): summ += arr[i] cmax = max(arr[i],cmax+arr[i]) gmax = max(cmax,gmax) cmin = min(arr[i],cmin+arr[i]) gmin = min(cmin,gmin) if k == 1: return gmax opt1 = gmax + max(0,summ*(k-1)) opt2 = summ - gmin + max(0,summ*(k-2)) return max(opt1,opt2) % 1000000007
k-concatenation-maximum-sum
PYTHON | KADANE ALGO | DETAILED EXPLANATION WITH PICTURE | INTUITIVE |
reaper_27
0
108
k concatenation maximum sum
1,191
0.239
Medium
18,125
https://leetcode.com/problems/k-concatenation-maximum-sum/discuss/2100728/python-3-oror-Kadane's-Algorithim-oror-O(n)O(1)
class Solution: def kConcatenationMaxSum(self, nums: List[int], k: int) -> int: def maxSum(k): res = cur = 0 for _ in range(k): for num in nums: cur = max(cur + num, num) res = max(res, cur) return res return (max(0, k - 2) * max(0, sum(nums)) + maxSum(min(2, k))) % (10 ** 9 + 7)
k-concatenation-maximum-sum
python 3 || Kadane's Algorithim || O(n)/O(1)
dereky4
0
146
k concatenation maximum sum
1,191
0.239
Medium
18,126
https://leetcode.com/problems/k-concatenation-maximum-sum/discuss/1223296/Python-wo-any-algo(Pure-Case-based-easy-Soln)
class Solution: def kConcatenationMaxSum(self, a: List[int], k: int) -> int: b = [] if k>1: for i in a: b.append(i) b.extend(a) def maxSubArray(nums): meh=0 msf=min(nums) temp = [] for i in nums: meh=meh+i temp.append(i) if meh<i: meh=i temp.pop() if msf < meh: msf=meh return msf comp1 = maxSubArray(a) comp2 = 0 comp3 = 0 comp4 = 0 if sum(a)>0: comp2 = sum(a)*k x = 0 stack = [] maxi = 0 for i in range(len(a)-1,-1,-1): x+=a[i] if x>0: if not stack: stack.append(x) elif x>stack[-1]: stack.append(x) x = 0 stack1 = [] maxi = 0 for i in range(len(a)): x+=a[i] if x>0: if not stack1: stack1.append(x) elif x>stack1[-1]: stack1.append(x) q = sum(a) if stack1: if stack1[-1]>q: q = stack1[-1] if stack: temp = stack[-1] temp2 = temp + sum(a)*(k-2) + q if temp2>0 and k>2: comp3 = temp2 if k>1: g = maxSubArray(b) if g>0: comp4 = g return max(comp1,comp2,comp3,comp4)%(10**9+7)
k-concatenation-maximum-sum
Python w/o any algo(Pure Case based easy Soln)
iamkshitij77
0
141
k concatenation maximum sum
1,191
0.239
Medium
18,127
https://leetcode.com/problems/k-concatenation-maximum-sum/discuss/382382/python3-Extension-to-kadane's-algo
class Solution: def kConcatenationMaxSum(self, arr: List[int], k: int) -> int: def kadane(a): n = len(a) max_so_far = a[0] max_ending_here = a[0] for i in range(1, n): max_ending_here = max(a[i],max_ending_here + a[i]) max_so_far = max(max_so_far, max_ending_here) return max_so_far def maxCircularSum(a, k): n = len(a) a_kadane = kadane(a) sum = 0 for i in range(0,n): sum += a[i] a[i] = -a[i] a_rest = sum - a_kadane b_kadane = sum + kadane(a) b_rest = sum - b_kadane if k == 1: return a_kadane if a_kadane <=0: return max(a_kadane, a_kadane + ((a_kadane + a_rest)*(k-1))) result1 = max(a_kadane, a_kadane + ((a_kadane + a_rest)*(k-1))) result2 = max(b_kadane , b_kadane + ((b_kadane + b_rest)*(k-2))) return max(result1, result2) return max(maxCircularSum(arr, k), 0)%(1000000007)
k-concatenation-maximum-sum
python3 Extension to kadane's algo
aj_to_rescue
0
84
k concatenation maximum sum
1,191
0.239
Medium
18,128
https://leetcode.com/problems/k-concatenation-maximum-sum/discuss/382490/Solution-in-Python-3-(beats-100.0)-(ten-lines)
class Solution: def kConcatenationMaxSum(self, a: List[int], k: int) -> int: L, M, j, m = len(a), 10**9 + 7, 0, 0 if min(a) >= 0: return sum(a)*k % M if max(a) <= 0: return 0 while j < 2*L: n, i = 0, j for j in range(i,2*L): n, j = n + a[j%L], j + 1 if n < 0: break if n > m: m = n return max(m,sum(a)*(k-2)+m) % M - Junaid Mansuri (LeetCode ID)@hotmail.com
k-concatenation-maximum-sum
Solution in Python 3 (beats 100.0%) (ten lines)
junaidmansuri
-1
250
k concatenation maximum sum
1,191
0.239
Medium
18,129
https://leetcode.com/problems/critical-connections-in-a-network/discuss/382440/Python-DFS-Tree-Solution-(O(V%2BE)-complexity)
class Solution: def criticalConnections(self, n: int, connections: List[List[int]]) -> List[List[int]]: dic = collections.defaultdict(list) for c in connections: u, v = c dic[u].append(v) dic[v].append(u) timer = 0 depth, lowest, parent, visited = [float("inf")]*n, [float("inf")]*n, [float("inf")]*n, [False]*n res = [] def find(u): nonlocal timer visited[u] = True depth[u], lowest[u] = timer, timer timer += 1 for v in dic[u]: if not visited[v]: parent[v] = u find(v) if lowest[v]>depth[u]: res.append([u,v]) if parent[u]!=v: lowest[u] = min(lowest[u], lowest[v]) find(0) return res
critical-connections-in-a-network
Python DFS-Tree Solution (O(V+E) complexity)
ywen1995
16
5,500
critical connections in a network
1,192
0.545
Hard
18,130
https://leetcode.com/problems/critical-connections-in-a-network/discuss/990791/Tarjan-Algo-Critical-Connections-Python-Solution-explained
class Solution: def criticalConnections(self, n: int, connections: List[List[int]]) -> List[List[int]]: ''' disc = discovery time of each node in the graph _____________________ |The concept of 'LOW'| low values means to which scc this node belongs to and that if this node is reachable to its ancestor (basically is there any way , if yes then we assign the low value of this node to the low value of its ancestor which will signify that this node belongs to the SCC and that the edge from this node to the ancestor node is the back edge when this node will backtrack to its parent node then it will say that look the connection between you(Parent) and me(child) is not a critical connection because I can be dicovered without your help(Parent) and we all belong to one SCC hence we update the parents low value to the min of low[parent],low[child]) Next imp thing : _____________________________________________ |Condition to check if this edge is a bridge | eg : SCC1 -----> SCC2 disc=0 disc =1 low=0 low=1 SCC1 = 1->2->3->1 SCC2= 4->5->4 disc 0 1 2 0 disc 3 4 3 low 0 0 0 0 low 3 3 3 suppose there s an edge from 1 to 4 and we start our dfs from node 1 then we know that the discovery of node 1 is done before the discovery of node 4 now we cant simply compare the dicovery time of the nodes(thats not correct) hence we use the low value of the chid to check ___________________________________ | if dicovery[parent] < low[child] | MEANS , That the dicovery ofthe parent was done before that of child hence its value is small if the edge is critical edge else if this edge is not a critical edge then the low value of the child is lesser than or equal to parent ''' disc = [-1]*n low = [-1]*n self.time = 0 graph = defaultdict(list) bridges = [] for u,v in connections: graph[u].append(v) graph[v].append(u) def dfs(node,parent): #print(parent) if disc[node] != -1: return disc[node] = self.time low[node] = self.time self.time += 1 for neighbor in graph[node]: if neighbor == parent: continue dfs(neighbor,node) low[node] = min(low[neighbor],low[node]) if disc[node] < low[neighbor] : bridges.append([node,neighbor]) dfs(0,-1) #print(low) return bridges
critical-connections-in-a-network
Tarjan Algo Critical Connections Python Solution explained
SaSha59
6
838
critical connections in a network
1,192
0.545
Hard
18,131
https://leetcode.com/problems/critical-connections-in-a-network/discuss/1339096/Elegant-Python-DFS-or-98.66-82.23
class Solution: def criticalConnections(self, n: int, connections: List[List[int]]) -> List[List[int]]: graph = defaultdict(list) for node1, node2 in connections: graph[node1].append(node2), graph[node2].append(node1) arrival_time = [None]*n critical_connections = [] def dfs(node = 0, parent = -1, time = 1): if arrival_time[node]: return arrival_time[node] = time for neighbour in graph[node]: if neighbour == parent: continue dfs(neighbour, node, time + 1) if arrival_time[neighbour] == time + 1: critical_connections.append((node, neighbour)) else: arrival_time[node] = min(arrival_time[node], arrival_time[neighbour]) return critical_connections return dfs()
critical-connections-in-a-network
Elegant Python DFS | 98.66%, 82.23%
soma28
5
656
critical connections in a network
1,192
0.545
Hard
18,132
https://leetcode.com/problems/critical-connections-in-a-network/discuss/1155457/Python3-Tarjan's-algo
class Solution: def criticalConnections(self, n: int, connections: List[List[int]]) -> List[List[int]]: graph = {} # graph as adjacency list for u, v in connections: graph.setdefault(u, []).append(v) graph.setdefault(v, []).append(u) def dfs(x, p, step): """Traverse the graph and collect bridges using Tarjan's algo.""" disc[x] = low[x] = step for xx in graph.get(x, []): if disc[xx] == inf: step += 1 dfs(xx, x, step) low[x] = min(low[x], low[xx]) if low[xx] > disc[x]: ans.append([x, xx]) # bridge elif xx != p: low[x] = min(low[x], disc[xx]) ans = [] low = [inf]*n disc = [inf]*n dfs(0, -1, 0) return ans
critical-connections-in-a-network
[Python3] Tarjan's algo
ye15
4
356
critical connections in a network
1,192
0.545
Hard
18,133
https://leetcode.com/problems/critical-connections-in-a-network/discuss/865386/DFS-Tarjans-Algorithm-Python3-Clean-and-Intuitive
class Solution: def criticalConnections(self, n: int, connections: List[List[int]]) -> List[List[int]]: if not connections: return [] def create_graph(edges): graph = defaultdict(list) for u, v in edges: graph[u].append(v) graph[v].append(u) return graph graph = create_graph(connections) visited = [False for _ in range(n)] counter = 0 id_low = defaultdict(dict) critical_connections = [] def dfs(node, parent): nonlocal graph, visited, counter, id_low, critical_connections if visited[node]: return visited[node] = True id_low[node]['id'] = counter id_low[node]['low'] = counter counter += 1 for node2 in graph[node]: if node2 == parent: continue dfs(node2, node) if id_low[node]['id'] < id_low[node2]['low']: critical_connections.append([node, node2]) id_low[node]['low'] = min(id_low[node]['low'], id_low[node2]['low']) dfs(0, -1) return critical_connections
critical-connections-in-a-network
DFS Tarjans Algorithm Python3 Clean & Intuitive
nyc_coder
4
817
critical connections in a network
1,192
0.545
Hard
18,134
https://leetcode.com/problems/critical-connections-in-a-network/discuss/1810111/Python-DFS-brute-force-solution
class Solution: def criticalConnections(self, n: int, connections: List[List[int]]) -> List[List[int]]: critConns = [] def buildGraph(exclude, conns): graph = defaultdict(list) for conn in conns: if conn == exclude: continue graph[conn[0]].append(conn[1]) graph[conn[1]].append(conn[0]) return graph def dfs(graph, visited, curNode): visited.add(curNode) for neighbor in graph[curNode]: if neighbor in visited: continue dfs(graph, visited, neighbor) for conn in connections: graph = buildGraph(conn, connections) visited = set() dfs(graph, visited, 0) if n != len(visited): critConns.append(conn) return critConns
critical-connections-in-a-network
Python DFS brute force solution
FluffBlankie
2
198
critical connections in a network
1,192
0.545
Hard
18,135
https://leetcode.com/problems/critical-connections-in-a-network/discuss/1651832/DFS-with-only-one-main-condition-or-O(V%2BE)-time-complexity
class Solution: def criticalConnections(self, n: int, connections: List[List[int]]) -> List[List[int]]: graph=collections.defaultdict(list) for i,j in connections: graph[i].append(j) graph[j].append(i) low=[0]*n visited=set() res=[] def dfs(node,parent,timer): nonlocal low,graph,res,visited low[node]=timer visited.add(node) for child in graph[node]: if child==parent:continue if child not in visited: dfs(child,node,timer+1) low[node]=min(low[node],low[child]) #important condition # this will check all the node which are reachable from the this node having time greater than the parent if less then it will be access from somewhere else # in teh minimum time if timer<low[child]: res.append([node,child]) dfs(0,-1,0) return res
critical-connections-in-a-network
DFS with only one main condition | O(V+E) time complexity
DaRk_hEaRt
2
242
critical connections in a network
1,192
0.545
Hard
18,136
https://leetcode.com/problems/critical-connections-in-a-network/discuss/2052958/Python3-Solution-with-using-dfs
class Solution: def build_graph(self, connections): g = collections.defaultdict(list) for src, dst in connections: g[src].append(dst) g[dst].append(src) return g def traversal(self, g, cur_v, prev_v, cur_rank, lowest_rank, visited, res): visited.add(cur_v) # mark if v is visited lowest_rank[cur_v] = cur_rank # mark cur rank for this v for neigb in g[cur_v]: if neigb == prev_v: # exclude repeated bridges continue # dfs traversal if neigb not in visited: self.traversal(g, neigb, cur_v, cur_rank + 1, lowest_rank, visited, res) # If there are several neighbors, paths to the current vertex from the initial vertex, then the rank will decrease lowest_rank[cur_v] = min(lowest_rank[cur_v], lowest_rank[neigb]) # in rank of neigb >= cur + 1 => we won't be able to get to the neigb any other way if lowest_rank[neigb] >= cur_rank + 1: res.append([cur_v, neigb]) def criticalConnections(self, n: int, connections: List[List[int]]) -> List[List[int]]: g = self.build_graph(connections) # build graph lowest_rank = [i for i in range(n)] # the order of the relative starting vertex res = [] # results bridges self.traversal(g, 0, -1, 0, lowest_rank, set(), res) return res
critical-connections-in-a-network
[Python3] Solution with using dfs
maosipov11
1
40
critical connections in a network
1,192
0.545
Hard
18,137
https://leetcode.com/problems/critical-connections-in-a-network/discuss/2435830/Python-DFS-bridge-finder
class Solution(object): def criticalConnections(self, n, nodes): graph = defaultdict(list) for u,v in nodes: graph[u].append(v) graph[v].append(u) intime = {} lowtime = {} visited = set() timer = 1 ans = [] def dfs(graph, node, visited, intime, lowtime, parent,timer): intime[node] = timer lowtime[node] = timer timer+=1 visited.add(node) for child in graph[node]: if not child in visited: dfs(graph, child, visited, intime, lowtime, node,timer) ## checking for bridge during backtracking if intime[node] < lowtime[child]: ans.append([node,child]) lowtime[node] = min(lowtime[child], lowtime[node]) else: # update the low time if child!= parent: lowtime[node] = min(intime[child], lowtime[node]) dfs(graph, list(graph.keys())[0], visited, intime, lowtime, -1,timer) return ans
critical-connections-in-a-network
Python DFS bridge finder
Abhi_009
0
119
critical connections in a network
1,192
0.545
Hard
18,138
https://leetcode.com/problems/critical-connections-in-a-network/discuss/972519/Need-help-DFS
class Solution: def criticalConnections(self, n: int, connections: List[List[int]]) -> List[List[int]]: connect = collections.defaultdict(set) for c in connections: connect[c[0]].add(c[1]) connect[c[1]].add(c[0]) step = [-1] * n res = [] ''' cur: current node index par: called dfs from parent, first call with None curStep: The step the current node should be return: the smallest step of all cur node's children ''' def dfs(cur, par, curStep, step, res, connect): # if cur node is visited if step[cur] >= 0: return step[cur] # if cur node is not visited step[cur] = curStep for child in connect[cur]: # if child is parent if child == par: continue # if not parent childRes = dfs(child, cur, step[cur] + 1, step, res, connect) step[cur] = min(step[cur], childRes) if par is not None: if step[cur] > step[par]: res.append([par, cur]) return step[cur] dfs(0, None, 0, step, res, connect) return res
critical-connections-in-a-network
Need help DFS
HaixuSong
0
173
critical connections in a network
1,192
0.545
Hard
18,139
https://leetcode.com/problems/critical-connections-in-a-network/discuss/415497/Can-anyone-explain-this-solution-to-me
class Solution: def criticalConnections(self, n: int, connections: List[List[int]]) -> List[List[int]]: graph = [[] for _ in range(n)] group = [None] * n for n1, n2 in connections: graph[n1].append(n2) graph[n2].append(n1) def dfs(node, parent): group[node] = node for neighbor in graph[node]: if neighbor == parent: continue elif group[neighbor] is None: dfs(neighbor, node) if group[neighbor] != neighbor: group[node] = group[neighbor] else: if group[neighbor] < group[node]: group[group[node]] = group[neighbor] else: group[group[neighbor]] = group[node] def get_root_parent(node): if group[node] == node: return node group[node] = get_root_parent(group[node]) return group[node] dfs(0, 0) for i in range(n): group[i] = get_root_parent(i) return [conn for conn in connections if group[conn[0]] != group[conn[1]]]
critical-connections-in-a-network
Can anyone explain this solution to me?
SkookumChoocher
0
410
critical connections in a network
1,192
0.545
Hard
18,140
https://leetcode.com/problems/minimum-absolute-difference/discuss/569795/Easy-to-Understand-or-Faster-or-Simple-or-Python-Solution
class Solution: def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]: arr.sort() m = float('inf') out = [] for i in range(1, len(arr)): prev = arr[i - 1] curr = abs(prev - arr[i]) if curr < m: out = [[prev, arr[i]]] m = curr elif curr == m: out.append([prev, arr[i]]) return out
minimum-absolute-difference
Easy to Understand | Faster | Simple | Python Solution
Mrmagician
16
1,300
minimum absolute difference
1,200
0.697
Easy
18,141
https://leetcode.com/problems/minimum-absolute-difference/discuss/1636910/Python3-SINGLE-PASS-(~)~-Explained
class Solution: def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]: arr.sort() mini, res = abs(arr[1] - arr[0]), [arr[0:2]] for i in range(2, len(arr)): diff = abs(arr[i] - arr[i - 1]) if diff > mini: continue if diff < mini: mini, res = diff, list() res.append([arr[i - 1], arr[i]]) return res
minimum-absolute-difference
✔️ [Python3] SINGLE PASS (~˘▾˘)~, Explained
artod
5
411
minimum absolute difference
1,200
0.697
Easy
18,142
https://leetcode.com/problems/minimum-absolute-difference/discuss/1636754/Beats-100-(292ms)-sort-%2B-single-scan-in-Python
class Solution: def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]: arr.sort() res = [] min_diff_so_far = float('inf') for val0, val1 in zip(arr, arr[1:]): diff = val1 - val0 if diff < min_diff_so_far: min_diff_so_far = diff res = [(val0, val1)] elif diff == min_diff_so_far: res.append((val0, val1)) return res
minimum-absolute-difference
Beats 100% (292ms), sort + single scan in Python
kryuki
4
355
minimum absolute difference
1,200
0.697
Easy
18,143
https://leetcode.com/problems/minimum-absolute-difference/discuss/1264206/Python3-Brute-Force-Solution-with-defaultdict
class Solution: def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]: arr.sort() diffs = defaultdict(list) for i in range(len(arr) - 1): diff = abs(arr[i] - arr[i + 1]) diffs[diff].append([arr[i] , arr[i + 1]]) return(diffs[min(diffs.keys())])
minimum-absolute-difference
[Python3] Brute Force Solution with defaultdict
VoidCupboard
3
87
minimum absolute difference
1,200
0.697
Easy
18,144
https://leetcode.com/problems/minimum-absolute-difference/discuss/1636776/Python3-O(nlogn)-Time-(beats-98)-or-Simple-%2B-Clean-%2B-Explanation-or-No-hashmap-or-1-Traversal-Only
class Solution: def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]: minDif = float('+inf') res = [] arr.sort() for i in range(1, len(arr)): d = arr[i] - arr[i - 1] if d == minDif: res.append([arr[i - 1], arr[i]]) elif d < minDif: res = [[arr[i- 1], arr[i]]] minDif = d return res
minimum-absolute-difference
[Python3] O(nlogn) Time (beats 98%) | Simple + Clean + Explanation | No hashmap | 1 Traversal Only
PatrickOweijane
2
197
minimum absolute difference
1,200
0.697
Easy
18,145
https://leetcode.com/problems/minimum-absolute-difference/discuss/1149275/Python3-1-pass
class Solution: def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]: arr.sort() ans = [] diff = inf for i in range(1, len(arr)): if arr[i] - arr[i-1] <= diff: if arr[i] - arr[i-1] < diff: ans = [] diff = arr[i] - arr[i-1] ans.append([arr[i-1], arr[i]]) return ans
minimum-absolute-difference
[Python3] 1-pass
ye15
2
119
minimum absolute difference
1,200
0.697
Easy
18,146
https://leetcode.com/problems/minimum-absolute-difference/discuss/1362155/Easy-Fast-Python-Solution-(faster-than-94)
class Solution: def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]: temp = sorted(arr) min_ = 9999999 ret = [] for i in range(len(temp)-1): diff = abs(temp[i+1] - temp[i]) if diff < min_: ret = [] min_ = diff ret.append([temp[i], temp[i+1]]) elif diff == min_: ret.append([temp[i], temp[i+1]]) return ret
minimum-absolute-difference
Easy, Fast, Python Solution (faster than 94%)
the_sky_high
1
249
minimum absolute difference
1,200
0.697
Easy
18,147
https://leetcode.com/problems/minimum-absolute-difference/discuss/1204035/Python3-Easy-Solution
class Solution: def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]: x = sorted(arr) s = [] count = 0 for i in range(len(x)-1): s.append((abs(x[i]-x[i+1]))) minv = min(s) s = [] for i in range(len(x)-1): if minv == abs(x[i]-x[i+1]): temp = [x[i], x[i+1]] s.append(temp) return s
minimum-absolute-difference
Python3 Easy Solution
Sanyamx1x
1
155
minimum absolute difference
1,200
0.697
Easy
18,148
https://leetcode.com/problems/minimum-absolute-difference/discuss/1047926/Python3-simple-solution-using-two-different-approaches
class Solution: def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]: arr.sort() min_diff = 100 for i in range(len(arr)-1): if arr[i+1] - arr[i] < min_diff: min_diff = arr[i+1] - arr[i] l = [] for i in range(len(arr)-1): if (arr[i+1] - arr[i]) == min_diff: l.append([arr[i],arr[i+1]]) return l
minimum-absolute-difference
Python3 simple solution using two different approaches
EklavyaJoshi
1
91
minimum absolute difference
1,200
0.697
Easy
18,149
https://leetcode.com/problems/minimum-absolute-difference/discuss/1047926/Python3-simple-solution-using-two-different-approaches
class Solution: def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]: arr.sort() min_diff = 100 d = {} for i in range(len(arr)-1): if min_diff > (arr[i+1] - arr[i]): min_diff = (arr[i+1] - arr[i]) if arr[i+1]- arr[i] in d: (d[arr[i+1]- arr[i]]).append([arr[i],arr[i+1]]) else: d[arr[i+1]- arr[i]] = [[arr[i],arr[i+1]]] return d[min_diff]
minimum-absolute-difference
Python3 simple solution using two different approaches
EklavyaJoshi
1
91
minimum absolute difference
1,200
0.697
Easy
18,150
https://leetcode.com/problems/minimum-absolute-difference/discuss/387763/Two-Solutions-in-Python-3-(beats-100)-(three-lines)
class Solution: def minimumAbsDifference(self, A: List[int]) -> List[List[int]]: L, D, m, _ = len(A), [], float('inf'), A.sort() for i in range(L-1): d = A[i+1] - A[i] if d == m: D.append([A[i],A[i+1]]) elif d < m: D, m = [[A[i],A[i+1]]], d return D
minimum-absolute-difference
Two Solutions in Python 3 (beats 100%) (three lines)
junaidmansuri
1
565
minimum absolute difference
1,200
0.697
Easy
18,151
https://leetcode.com/problems/minimum-absolute-difference/discuss/387763/Two-Solutions-in-Python-3-(beats-100)-(three-lines)
class Solution: def minimumAbsDifference(self, A: List[int]) -> List[List[int]]: L, D, _ = len(A), collections.defaultdict(list), A.sort() for i in range(L-1): D[A[i+1] - A[i]].append([A[i],A[i+1]]) return D[min(D.keys())] - Junaid Mansuri (LeetCode ID)@hotmail.com
minimum-absolute-difference
Two Solutions in Python 3 (beats 100%) (three lines)
junaidmansuri
1
565
minimum absolute difference
1,200
0.697
Easy
18,152
https://leetcode.com/problems/minimum-absolute-difference/discuss/2820144/Simple-dictonary-solution
class Solution: def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]: arr.sort() dic = defaultdict(list) for i in range(1,len(arr)): diff = abs(arr[i-1]-arr[i]) dic[diff].append([arr[i-1],arr[i]]) min_diff = min(dic) return dic[min_diff]
minimum-absolute-difference
Simple dictonary solution
aruj900
0
4
minimum absolute difference
1,200
0.697
Easy
18,153
https://leetcode.com/problems/minimum-absolute-difference/discuss/2807242/Python-3-lines-or-91-or-Short-easy-with-sort-%2B-zip
class Solution: def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]: arr.sort() min_diff = min(abs(prev - curr) for prev, curr in zip(arr[:-1], arr[1:])) return [[prev, curr] for prev, curr in zip(arr[:-1], arr[1:]) if abs(curr - prev) == min_diff]
minimum-absolute-difference
[Python] 3 lines | 91% | Short, easy with sort + zip
Nezuko-NoBamboo
0
5
minimum absolute difference
1,200
0.697
Easy
18,154
https://leetcode.com/problems/minimum-absolute-difference/discuss/2781449/Minimum-Absolute-Difference
class Solution: def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]: d={} arr.sort() for i in range(len(arr)-1): d[arr[i],arr[i+1]]=arr[i+1]-arr[i] min_difference=min(d.values()) result=[] for i in d.keys(): if d[i]==min_difference: result.append(i) return result
minimum-absolute-difference
Minimum Absolute Difference
Harsh_Gautam45
0
9
minimum absolute difference
1,200
0.697
Easy
18,155
https://leetcode.com/problems/minimum-absolute-difference/discuss/2740264/Python-HashMap-Solution-with-sorting
class Solution: def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]: d = {} arr.sort() for i in range(len(arr)-1): if arr[i+1] - arr[i] not in d: d[arr[i+1] - arr[i]] = [[arr[i], arr[i+1]]] else: d[arr[i+1] - arr[i]].append([arr[i], arr[i+1]]) m = min(d.keys()) return d.get(m)
minimum-absolute-difference
Python HashMap Solution with sorting
theReal007
0
11
minimum absolute difference
1,200
0.697
Easy
18,156
https://leetcode.com/problems/minimum-absolute-difference/discuss/2712832/faster-than-96-of-python
class Solution: def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]: arr.sort() a = abs(arr[0] - arr[1]) for i in range(1, len(arr)): if abs(arr[i] - arr[i - 1]) < a: a = abs(arr[i] - arr[i - 1]) lst = [] for i in range(1, len(arr)): if abs(arr[i] - arr[i - 1]) == a: lst.append([arr[i - 1], arr[i]]) return lst
minimum-absolute-difference
faster than 96% of python
dastankg
0
14
minimum absolute difference
1,200
0.697
Easy
18,157
https://leetcode.com/problems/minimum-absolute-difference/discuss/2712826/faster-than-96-of-python
class Solution: def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]: arr.sort() a = abs(arr[0] - arr[1]) for i in range(1, len(arr)): if abs(arr[i] - arr[i - 1]) < a: a = abs(arr[i] - arr[i - 1]) lst = [] for i in range(1, len(arr)): if abs(arr[i] - arr[i - 1]) == a: lst.append([arr[i - 1], arr[i]]) return lst
minimum-absolute-difference
faster than 96% of python
dastankg
0
7
minimum absolute difference
1,200
0.697
Easy
18,158
https://leetcode.com/problems/minimum-absolute-difference/discuss/2685042/Python3-One-pass-easy-solution
class Solution: def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]: # sort the list arr.sort() print(arr) # find the minimum difference current_min = 10**14 result = [] for idx, num in enumerate(arr[:-1]): # check whether we are at current minimum if arr[idx+1] - num == current_min: result.append([num, arr[idx+1]]) # check if we are smaller elif arr[idx+1] - num < current_min: result = [[num, arr[idx+1]]] current_min = arr[idx+1] - num return result
minimum-absolute-difference
[Python3] - One pass, easy solution
Lucew
0
9
minimum absolute difference
1,200
0.697
Easy
18,159
https://leetcode.com/problems/minimum-absolute-difference/discuss/2669511/Python%2BNumpy
class Solution: def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]: import numpy as np arr.sort() arr=np.array(arr) diff=np.diff(arr) Min=np.min(diff) Ind=np.where(diff==Min)[0] return [[arr[Ind[i]],arr[Ind[i]+1]] for i in range(len(Ind))]
minimum-absolute-difference
Python+Numpy
Leox2022
0
3
minimum absolute difference
1,200
0.697
Easy
18,160
https://leetcode.com/problems/minimum-absolute-difference/discuss/2669084/USING-BRUTE-FORCE-oror-PYTHON
class Solution: def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]: output=[] arr.sort() minn=[] for i in range(len(arr)-1): minn.append(arr[i+1]-arr[i]) min_arr=min(minn) for j in range(len(arr)-1): if (arr[j+1]-arr[j])==min_arr: output.append([arr[j],arr[j+1]]) return output
minimum-absolute-difference
USING BRUTE FORCE || PYTHON
pratiyushray2152
0
3
minimum absolute difference
1,200
0.697
Easy
18,161
https://leetcode.com/problems/minimum-absolute-difference/discuss/2573119/Python-solution-using-sort-abs()-min-and-dictionary!O(nlogn)
class Solution: def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]: result = [] dict_diff_nums = {} arr.sort() for i in range(len(arr) - 1): diff = abs(arr[i] - arr[i+1]) dict_diff_nums[arr[i], arr[i+1]] = diff minimum_diff = min(dict_diff_nums.values()) for key, val in dict_diff_nums.items(): if val == minimum_diff: result.append(list(key)) return result
minimum-absolute-difference
Python solution using sort, abs(), min, and dictionary!O(nlogn)
samanehghafouri
0
53
minimum absolute difference
1,200
0.697
Easy
18,162
https://leetcode.com/problems/minimum-absolute-difference/discuss/2463189/PYTHON-3-Simple-Solution-(Feedbacks-appreciated)
class Solution: def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]: # I created a sorted copy of the array to not modify arr in-place. In case this needs to be implemented in further code. ref_arr = sorted(arr) min_diff = ref_arr[-1] - ref_arr[0] # Initialize array for results diff_pairs = [] # Iterate through arr for i, number in enumerate(ref_arr[:-1], 1): # Skip if the difference is bigger if ref_arr[i] - number > min_diff: continue # If the new difference is smaller, we empty the results array elif ref_arr[i] - number < min_diff: min_diff = ref_arr[i] - number diff_pairs.clear() diff_pairs.append([number, ref_arr[i]]) # END FOR loop return diff_pairs
minimum-absolute-difference
[PYTHON 3] Simple Solution (Feedbacks appreciated)
Eli47
0
104
minimum absolute difference
1,200
0.697
Easy
18,163
https://leetcode.com/problems/minimum-absolute-difference/discuss/2299216/Easy-Python-solution-for-beginners....-o(n-log-n)
class Solution: def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]: arr.sort() diff=float(inf) for i in range(0,len(arr)-1): if arr[i+1]-arr[i]<diff: diff=arr[i+1]-arr[i] lst=[] for i in range(0,len(arr)-1): if arr[i+1]-arr[i]==diff: lst.append([arr[i],arr[i+1]]) return lst
minimum-absolute-difference
Easy Python solution for beginners.... o(n log n)
guneet100
0
116
minimum absolute difference
1,200
0.697
Easy
18,164
https://leetcode.com/problems/minimum-absolute-difference/discuss/2095919/PYTHON-or-Super-Simple-Python-Solution
class Solution: def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]: arr = sorted(arr) pairMap = {} min_diff = abs(arr[0] - arr[1]) for i in range(len(arr)-1): min_diff = min(min_diff, abs(arr[i] - arr[i+1])) pairMap[abs(arr[i] - arr[i+1])] = pairMap.get(abs(arr[i] - arr[i+1]), []) + [[arr[i],arr[i+1]]] return pairMap[min_diff]
minimum-absolute-difference
PYTHON | Super Simple Python Solution
shreeruparel
0
154
minimum absolute difference
1,200
0.697
Easy
18,165
https://leetcode.com/problems/minimum-absolute-difference/discuss/1986021/Python-Simple-and-Straight-Forward
class Solution: def minimumAbsDifference(self, arr): minAbsDiff, res = inf, [] for a,b in pairwise(sorted(arr)): diff = b-a if diff < minAbsDiff: res.clear() minAbsDiff = diff if diff == minAbsDiff: res.append([a, b]) return res
minimum-absolute-difference
Python - Simple and Straight Forward
domthedeveloper
0
131
minimum absolute difference
1,200
0.697
Easy
18,166
https://leetcode.com/problems/minimum-absolute-difference/discuss/1959163/easy-python-code
class Solution: def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]: mini = None pairs = [] arr.sort() for i in range(len(arr)-1): if mini == None: mini = abs(arr[i]-arr[i+1]) pairs.append([arr[i],arr[i+1]]) elif mini > abs(arr[i]-arr[i+1]): mini = abs(arr[i]-arr[i+1]) pairs = [] pairs.append([arr[i],arr[i+1]]) elif mini == abs(arr[i]-arr[i+1]): pairs.append([arr[i],arr[i+1]]) return pairs
minimum-absolute-difference
easy python code
dakash682
0
101
minimum absolute difference
1,200
0.697
Easy
18,167
https://leetcode.com/problems/minimum-absolute-difference/discuss/1918895/Python-solution-faster-than-88
class Solution: def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]: arr.sort() min_diff = min([arr[x+1] - arr[x] for x in range(len(arr)-1)]) res = [] for i in range(len(arr)-1): if arr[i+1] - arr[i] == min_diff: res.append([arr[i], arr[i+1]]) return res
minimum-absolute-difference
Python solution faster than 88%
alishak1999
0
128
minimum absolute difference
1,200
0.697
Easy
18,168
https://leetcode.com/problems/minimum-absolute-difference/discuss/1794699/4-Lines-Python-Solution-oror-75-Faster-oror-Memory-less-than-70
class Solution: def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]: arr, mn = sorted(arr), 1000000 for i in range(len(arr)-1): if arr[i+1]-arr[i] < mn: mn = arr[i+1]-arr[i] return [[arr[i],arr[i+1]] for i in range(len(arr)-1) if arr[i+1]-arr[i]==mn]
minimum-absolute-difference
4-Lines Python Solution || 75% Faster || Memory less than 70%
Taha-C
0
138
minimum absolute difference
1,200
0.697
Easy
18,169
https://leetcode.com/problems/minimum-absolute-difference/discuss/1725880/Easy-solution-using-python3
class Solution: def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]: arr.sort() li = [] for i in range(len(arr) - 1) : dif = abs(arr[i+1] - arr[i]) li.append(dif) minDiff = min(li) ans = [] for i in range(len(arr) - 1): diff = abs(arr[i+1] - arr[i]) if diff == minDiff : ans.append([arr[i], arr[i+1]]) return ans
minimum-absolute-difference
Easy solution using python3
shakilbabu
0
141
minimum absolute difference
1,200
0.697
Easy
18,170
https://leetcode.com/problems/minimum-absolute-difference/discuss/1637761/python-sorting-solution-or-constant-space
class Solution: def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]: arr.sort() minDiff = float('inf') res = [] for i in range(1, len(arr)): prev = arr[i - 1] curr_diff = abs(prev - arr[i]) if curr_diff < minDiff: res = [[prev, arr[i]]] minDiff = curr_diff elif curr_diff == minDiff: res.append([prev, arr[i]]) return res
minimum-absolute-difference
python sorting solution | constant space
abkc1221
0
39
minimum absolute difference
1,200
0.697
Easy
18,171
https://leetcode.com/problems/minimum-absolute-difference/discuss/1637240/python3-or-sort()-or-time-O(n-log-n)-or-space-O(n)
class Solution: def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]: if len(arr)==1: return [] arr.sort() # sort the array n=len(arr) min_diff=10**9 # calculate the min diff by iterrating through array for i in range(1,n): min_diff=min(min_diff,arr[i]-arr[i-1]) l=[] # iterrate through array and find the pair with min_diff for i in range(1,n): if arr[i]-arr[i-1]==min_diff: l.append([arr[i-1],arr[i]]) return l
minimum-absolute-difference
python3 | sort() | time- O(n log n) | space -O(n)
Rohit_Patil
0
31
minimum absolute difference
1,200
0.697
Easy
18,172
https://leetcode.com/problems/minimum-absolute-difference/discuss/1637216/Python3-Using-zip-saves-your-life-linear-one-pass
class Solution: def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]: arr.sort() mindiff = arr[-1]-arr[0] res = [] for x,y in zip(arr[:-1],arr[1:]): if y-x < mindiff: res = [] mindiff = y-x if y-x == mindiff: res.append([x,y]) return res
minimum-absolute-difference
[Python3] Using zip saves your life - linear one pass
Rainyforest
0
23
minimum absolute difference
1,200
0.697
Easy
18,173
https://leetcode.com/problems/minimum-absolute-difference/discuss/1637149/Using-zip()-and-sort()-to-solve-it-in-python3
class Solution: def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]: arr.sort() arr2 = [abs(x-y) for x, y in zip(arr, arr[1:])] m = min(arr2) return [[arr[i], arr[i+1]] for i in range(len(arr2)) if arr2[i]==m]
minimum-absolute-difference
Using zip() and sort() to solve it in python3
etu7912a482
0
20
minimum absolute difference
1,200
0.697
Easy
18,174
https://leetcode.com/problems/minimum-absolute-difference/discuss/1636935/Two-Liner-Solution-or-Iterative-Solution
class Solution: def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]: arr.sort() return[[arr[i],arr[i+1]] for i,j in enumerate([arr[i+1]-arr[i] for i in range(len(arr)-1)]) if j == min([arr[i+1]-arr[i] for i in range(len(arr)-1)])]
minimum-absolute-difference
Two Liner Solution | Iterative Solution
radar21
0
37
minimum absolute difference
1,200
0.697
Easy
18,175
https://leetcode.com/problems/minimum-absolute-difference/discuss/1636935/Two-Liner-Solution-or-Iterative-Solution
class Solution: def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]: n = len(arr) arr.sort() diff = [arr[i+1]-arr[i] for i in range(n-1)] final = min(diff) return[[arr[i],arr[i+1]] for i,j in enumerate(diff) if j == final]
minimum-absolute-difference
Two Liner Solution | Iterative Solution
radar21
0
37
minimum absolute difference
1,200
0.697
Easy
18,176
https://leetcode.com/problems/minimum-absolute-difference/discuss/1636895/WEEB-DOES-PYTHON
class Solution: def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]: arr.sort() result = [] curMin = float("inf") for i in range(len(arr)-1): minDiff = abs(arr[i+1] - arr[i]) if minDiff < curMin: result.clear() curMin = minDiff result.append([arr[i],arr[i+1]]) elif minDiff == curMin: result.append([arr[i],arr[i+1]]) return result
minimum-absolute-difference
WEEB DOES PYTHON
Skywalker5423
0
51
minimum absolute difference
1,200
0.697
Easy
18,177
https://leetcode.com/problems/minimum-absolute-difference/discuss/1569788/Python3-Solution-with-using-sorting
class Solution: def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]: arr.sort() res = [] _min = float('inf') for i in range(len(arr) - 1): _abs = abs(arr[i + 1] - arr[i]) if _abs < _min: _min = _abs res = [] if _abs == _min: res.append([arr[i], arr[i + 1]]) return res
minimum-absolute-difference
[Python3] Solution with using sorting
maosipov11
0
193
minimum absolute difference
1,200
0.697
Easy
18,178
https://leetcode.com/problems/minimum-absolute-difference/discuss/1552961/python-easy-solution-with-stack
class Solution: def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]: arr.sort() ans = [] for i in range(1, len(arr)): temp = abs(arr[i] - arr[i-1]) if ans == []: ans.append([arr[i-1],arr[i]]) elif abs(ans[-1][0] - ans[-1][1]) > temp: while ans and abs(ans[-1][0] - ans[-1][1]) > temp: ans.pop() ans.append([arr[i-1],arr[i]]) elif abs(ans[-1][0] - ans[-1][1]) == temp: ans.append([arr[i-1],arr[i]]) return ans
minimum-absolute-difference
python easy solution with stack
equus3144
0
75
minimum absolute difference
1,200
0.697
Easy
18,179
https://leetcode.com/problems/minimum-absolute-difference/discuss/1154315/Python-faster-than-99-O(nlogn)
class Solution: def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]: arr.sort() # O(nlogn) history, min_diff = {}, float("inf") for i in range(len(arr)-1): # O(n) if min_diff >= abs(arr[i] - arr[i+1]): min_diff = abs(arr[i] - arr[i+1]) the_history = history.get(min_diff, []) the_history.append([arr[i], arr[i+1]]) history[min_diff] = the_history return history[min_diff]
minimum-absolute-difference
Python faster than 99%, O(nlogn)
anylee2142
0
109
minimum absolute difference
1,200
0.697
Easy
18,180
https://leetcode.com/problems/minimum-absolute-difference/discuss/881143/Python-simple-solution-with-sorting-%2B-1-%22for%22-loop
class Solution: def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]: res, d = [], float('Inf') arr.sort() for i, k in zip(arr[:-1], arr[1:]): d_curr = k - i if d_curr <= d: if d_curr != d: res, d = [], d_curr res.append([i, k]) return res
minimum-absolute-difference
Python simple solution with sorting + 1 "for" loop
stom1407
0
92
minimum absolute difference
1,200
0.697
Easy
18,181
https://leetcode.com/problems/minimum-absolute-difference/discuss/416772/Python3-5-lines-clear-code-beat-100-in-O(n)
class Solution: def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]: arr.sort() temp = arr[1] - arr[0] for i in range(len(arr) - 1): temp = min(temp ,arr[i+1] - arr[i] ) res = [[arr[i] , arr[i+1]] for i in range(len(arr)-1) if arr[i+1] - arr[i] == temp] return res
minimum-absolute-difference
Python3 5 lines clear code beat 100% in O(n)
macqueen
-2
185
minimum absolute difference
1,200
0.697
Easy
18,182
https://leetcode.com/problems/ugly-number-iii/discuss/723589/Python3-inconsistent-definition-of-%22ugly-numbers%22
class Solution: def nthUglyNumber(self, n: int, a: int, b: int, c: int) -> int: # inclusion-exclusion principle ab = a*b//gcd(a, b) bc = b*c//gcd(b, c) ca = c*a//gcd(c, a) abc = ab*c//gcd(ab, c) lo, hi = 1, n*min(a, b, c) while lo < hi: mid = lo + hi >> 1 if mid//a + mid//b + mid//c - mid//ab - mid//bc - mid//ca + mid//abc < n: lo = mid + 1 else: hi = mid return lo
ugly-number-iii
[Python3] inconsistent definition of "ugly numbers"
ye15
33
1,000
ugly number iii
1,201
0.285
Medium
18,183
https://leetcode.com/problems/ugly-number-iii/discuss/2299901/PYTHON-or-BRUTE-FORCE-TO-OPTIMZIED-SOL-or-FULL-DETAILED-EXPLANATIONor
class Solution: def nthUglyNumber(self, n: int, a: int, b: int, c: int) -> int: times = [1,1,1] smallest = inf while n != 0: smallest = min ( times[0]*a,times[1]*b,times[2]*c) if times[0]*a == smallest: times[0] += 1 if times[1]*b == smallest: times[1] += 1 if times[2]*c == smallest: times[2] += 1 n -= 1 return smallest
ugly-number-iii
PYTHON | BRUTE FORCE TO OPTIMZIED SOL | FULL DETAILED EXPLANATION|
reaper_27
3
132
ugly number iii
1,201
0.285
Medium
18,184
https://leetcode.com/problems/ugly-number-iii/discuss/2299901/PYTHON-or-BRUTE-FORCE-TO-OPTIMZIED-SOL-or-FULL-DETAILED-EXPLANATIONor
class Solution: def nthUglyNumber(self, n: int, a: int, b: int, c: int) -> int: a,b,c = sorted((a,b,c)) ans = inf def hcf(a,b): if a %b == 0: return b return hcf(b , a % b) p,q,r= hcf(a,b),hcf(b,c),hcf(a,c) s = hcf(r,b) x1 = (a*b) // p x2 = (b*c) // q x3 = (a*c) // r x4 = (a * b * c * s)// (p * q * r ) low,high = a , a *n while low <= high: mid = (low + high)//2 times = mid//a + mid//b + mid//c - mid//x1 - mid//x2 - mid//x3 + mid//x4 if times < n : low = mid + 1 elif times == n: ans = min(ans,mid) high = mid - 1 else: high = mid - 1 return ans
ugly-number-iii
PYTHON | BRUTE FORCE TO OPTIMZIED SOL | FULL DETAILED EXPLANATION|
reaper_27
3
132
ugly number iii
1,201
0.285
Medium
18,185
https://leetcode.com/problems/ugly-number-iii/discuss/1457965/Simple-Binary-Search-Python3
class Solution: def nthUglyNumber(self, n: int, a: int, b: int, c: int) -> int: ab = a*b//math.gcd(a,b) ac = a*c//math.gcd(a,c) bc = b*c//math.gcd(b,c) abc = a*bc//math.gcd(a,bc) def enough(m): tot = m//a + m//b + m//c - m//ab - m//bc -m//ac +m//abc return tot>=n l,r = 1,10**10 while l<r: m=(l+r)//2 if enough(m): r=m else: l=m+1 return l
ugly-number-iii
Simple Binary Search [Python3]
rudr
0
285
ugly number iii
1,201
0.285
Medium
18,186
https://leetcode.com/problems/ugly-number-iii/discuss/387749/Solution-in-Python-3-(beats-100.00-)-(Binary-Search)-(ten-lines)
class Solution: def nthUglyNumber(self, n: int, a: int, b: int, c: int) -> int: [a,b,c] = sorted([a,b,c]) if a == 1: return n def lcm(x,y): return x*y//math.gcd(x,y) AB, BC, AC, ABC, r, s = lcm(a,b), lcm(b,c), lcm(a,c), lcm(lcm(a,b),c), n*a//3, n*a+1 def unc(x): return x//a + x//b + x//c - x//AB - x//BC - x//AC + x//ABC while unc(s-1) - n > 0: m = (r+s)//2 if unc(m) - n > 0: s = m else: r = m return max(i*((s-1)//i) for i in [a,b,c]) - Junaid Mansuri (LeetCode ID)@hotmail.com
ugly-number-iii
Solution in Python 3 (beats 100.00 %) (Binary Search) (ten lines)
junaidmansuri
0
480
ugly number iii
1,201
0.285
Medium
18,187
https://leetcode.com/problems/smallest-string-with-swaps/discuss/1985185/Python3-UNION-FIND-()**-Explained
class Solution: def union(self, a, b): self.parent[self.find(a)] = self.find(b) def find(self, a): if self.parent[a] != a: self.parent[a] = self.find(self.parent[a]) return self.parent[a] def smallestStringWithSwaps(self, s: str, pairs: List[List[int]]) -> str: # 1. Union-Find self.parent = list(range(len(s))) for a, b in pairs: self.union(a, b) # 2. Grouping group = defaultdict(lambda: ([], [])) for i, ch in enumerate(s): parent = self.find(i) group[parent][0].append(i) group[parent][1].append(ch) # 3. Sorting res = [''] * len(s) for ids, chars in group.values(): ids.sort() chars.sort() for ch, i in zip(chars, ids): res[i] = ch return ''.join(res)
smallest-string-with-swaps
✔️ [Python3] UNION-FIND (❁´▽`❁)*✲゚*, Explained
artod
55
2,700
smallest string with swaps
1,202
0.576
Medium
18,188
https://leetcode.com/problems/smallest-string-with-swaps/discuss/1985417/Easy-Python-Solution-oror-Union-Find-Explanation-oror-faster-than-94.67
class Solution: def smallestStringWithSwaps(self, s: str, pairs: List[List[int]]) -> str: # Start of Union Find Data Structure p = list(range(len(s))) # parent # each element in the pairs == node # used to store each node's parent based on its index # eg. pairs = [[0,3],[1,2]], p = [0, 1, 1, 0] # element 3 in pairs == p index 3 == 0 (because parent node of 3 is 0) def find(x): if x != p[x]: p[x] = find(p[x]) return p[x] def union(x, y): px = find(x) py = find(y) if px != py: p[py] = px # End of Union Find Data Structure # Grouping for x, y in pairs: union(x, y) dic = defaultdict(list) for idx, el in enumerate(p): dic[find(el)].append(idx) # eg. pairs = [[0,3],[1,2]], dic = {0: [0, 3], 1: [1, 2]} # Sorting res = list(s) for key in dic.keys(): idx_list = dic[key] char_list = [s[i] for i in idx_list] char_list.sort() # eg. idx_list = [0, 3], char_list = [b, d] # for loop below, idx = [0, b], char = [3, d] for idx, char in zip(idx_list, char_list): res[idx] = char return "".join(res)
smallest-string-with-swaps
✅✅✅Easy [Python] Solution || Union Find Explanation || faster than 94.67%
ziqinyeow
4
456
smallest string with swaps
1,202
0.576
Medium
18,189
https://leetcode.com/problems/smallest-string-with-swaps/discuss/1501837/Clean-and-Efficient-Python3-Solution-Using-the-UnionFind-Paradigm
class Solution: def smallestStringWithSwaps(self, s: str, pairs: List[List[int]]) -> str: num_nodes = len(s) self.uf = UnionFind(num_nodes) for i,j in pairs: self.uf.union(i,j) indexes_by_root = {} chars_by_root = {} for i in range(num_nodes): root = self.uf.find(i) if root not in indexes_by_root: indexes_by_root[root] = [i] chars_by_root[root] = [s[i]] else: indexes_by_root[root].append(i) chars_by_root[root].append(s[i]) result = [None] * num_nodes for root in indexes_by_root: sorted_characters = sorted(chars_by_root[root]) for index, slot in enumerate(indexes_by_root[root]): result[slot] = sorted_characters[index] result = ''.join(result) return result class UnionFind: def __init__(self, n): self.parent = list(range(n)) self.rank = [1] * n return def find(self, x): if x == self.parent[x]: return x else: self.parent[x] = self.find(self.parent[x]) return self.parent[x] def union(self, x, y): parent_x = self.find(x) parent_y = self.find(y) if parent_x != parent_y: if self.rank[parent_x]>=self.rank[parent_y]: self.parent[parent_y] = parent_x self.rank[parent_x] += self.rank[parent_y] else: self.parent[parent_x] = parent_y self.rank[parent_y] += self.rank[parent_x] return
smallest-string-with-swaps
Clean and Efficient Python3 Solution Using the UnionFind Paradigm
sayan007
4
349
smallest string with swaps
1,202
0.576
Medium
18,190
https://leetcode.com/problems/smallest-string-with-swaps/discuss/1985347/Pythonoror98.27-DFS
class Solution: def smallestStringWithSwaps(self, s: str, pairs: List[List[int]]) -> str: def dfs(idx, arr): arr.append(idx) visited[idx] = True for nei in graph[idx]: if not visited[nei]: visited[nei] = True dfs(nei, arr) graph = collections.defaultdict(list) for a, b in pairs: graph[a].append(b) graph[b].append(a) n = len(s) s_list = list(s) visited = [False] * n for idx in range(n): if not visited[idx]: arr = [] dfs(idx, arr) arr.sort() letter = [s[i] for i in arr] letter.sort() for i in range(len(arr)): s_list[arr[i]] = letter[i] return ''.join(s_list)
smallest-string-with-swaps
Python||98.27% DFS
gulugulugulugulu
2
129
smallest string with swaps
1,202
0.576
Medium
18,191
https://leetcode.com/problems/smallest-string-with-swaps/discuss/2308250/PYTHON-or-DFS-or-GRAPH-BASED-SOL-or-EXPLAINED-or-EASY-or
class Solution: def smallestStringWithSwaps(self, s: str, pairs: List[List[int]]) -> str: n = len(s) visited = [False]*n canGo = defaultdict(list) mainList = [] for i,j in pairs: canGo[i].append(j) canGo[j].append(i) def dfs(node,path): visited[node] = True path.append(node) for adj in canGo[node]: if visited[adj] == False: dfs(adj,path) for i in range(n): if visited[i] == True: continue path = [] dfs(i,path) mainList.append(path) for lst in mainList: lst.sort() tmp = [s[i] for i in lst] tmp.sort() for i in range(len(lst)): s = s[:lst[i]] + tmp[i] + s[lst[i]+1:] return s
smallest-string-with-swaps
PYTHON | DFS | GRAPH BASED SOL | EXPLAINED | EASY |
reaper_27
1
66
smallest string with swaps
1,202
0.576
Medium
18,192
https://leetcode.com/problems/smallest-string-with-swaps/discuss/1692768/Python-solution-or-92-faster
class Solution: def smallestStringWithSwaps(self, s: str, pairs: List[List[int]]) -> str: n = len(s) parent = list(range(n)) rank = [1]*n def find(node): if parent[node]!=node: parent[node] = find(parent[node]) return parent[node] def union(node1,node2): p1,p2 = find(node1),find(node2) if p1==p2: return if rank[p1]>rank[p2]: p1,p2 = p2,p1 parent[p1] = p2 rank[p2] += rank[p1] for n1,n2 in pairs: union(n1,n2) d = defaultdict(list) for i in range(n): d[find(i)].append(s[i]) for l in d.values(): l.sort(reverse=True) ret = [] for i in range(n): ret.append(d[find(i)].pop()) return ''.join(ret)
smallest-string-with-swaps
Python solution | 92% faster
1579901970cg
1
244
smallest string with swaps
1,202
0.576
Medium
18,193
https://leetcode.com/problems/smallest-string-with-swaps/discuss/1692768/Python-solution-or-92-faster
class Solution: def smallestStringWithSwaps(self, s: str, pairs: List[List[int]]) -> str: n = len(s) l = [[] for _ in range(n)] parent = list(range(n)) for n1,n2 in pairs: l[n1].append(n2) l[n2].append(n1) d = defaultdict(list) visited = set() def dfs(node, root): if node not in visited: visited.add(node) d[root].append(s[node]) parent[node] = root for child in l[node]: dfs(child, root) for i in range(n): if i not in visited: dfs(i,i) for vec in d.values(): vec.sort(reverse=True) ret = [] for i in range(n): ret.append(d[parent[i]].pop()) return ''.join(ret)
smallest-string-with-swaps
Python solution | 92% faster
1579901970cg
1
244
smallest string with swaps
1,202
0.576
Medium
18,194
https://leetcode.com/problems/smallest-string-with-swaps/discuss/1653105/92-faster-oror-Thought-Process-oror-For-Beginners-oror-Easy-and-Concise
class Solution: def smallestStringWithSwaps(self, s: str, pairs: List[List[int]]) -> str: graph = defaultdict(list) for a,b in pairs: graph[a].append(b) graph[b].append(a) col = [] self.seen = set() def grp_making(point): nonlocal local if point in self.seen: return local.append(point) self.seen.add(point) for p in graph[point]: grp_making(p) for k in graph.keys(): if k not in self.seen: local = [] grp_making(k) col.append(local) res = list(s) for grp in col: tmp = "" for ind in grp: tmp += s[ind] tmp = sorted(tmp) grp.sort() i = 0 for ind in grp: res[ind] = tmp[i] i+=1 return ''.join(res)
smallest-string-with-swaps
📌📌 92% faster || Thought Process || For Beginners || Easy & Concise 🐍
abhi9Rai
1
245
smallest string with swaps
1,202
0.576
Medium
18,195
https://leetcode.com/problems/smallest-string-with-swaps/discuss/1469915/Python-UnionFind-with-step-by-step-explanation
class Solution: def smallestStringWithSwaps(self, s: str, pairs: List[List[int]]) -> str: ''' Take s = "dcab", pairs = [[0,3],[1,2]] as example. 1. At first we create UnionFind structure. 2. Next step is filling it with pairs. Here let's look more precisely: self.root = [0,1,2,3] at first, then we merge 0&amp;3 and 1&amp;2 => self.root = [0,1,1,0], so we're uniting some roots. 3. Create 2 dict: first to keep letters and second to keep idx. 4. Traverse input string. 5. Look for # in code to get how dict1 and dict2 look like. 6. We sort them to get lexicographically smallest first 7. Next we take key, 0 at first, and as we have `key: list` => we can pick up letter based on idx as well. As letters are sorted in smallest to biggest order => we take smallest first and put it into position that is written in dict2 (it is from smallest to biggest without sort) 8. At first we fill: ['b', _, _, 'd'] and next we fill with 1 key. ''' graph = UnionFind(len(s)) for pair in pairs: graph.union(pair[0], pair[1]) dict1 = {} dict2 = {} for i in range(len(s)): root = graph.find(i) if root not in dict1: dict1[root] = [] if root not in dict2: dict2[root] = [] dict1[root].append(s[i]) dict2[root].append(i) result = [0 for _ in range(len(s))] # dict1: {0: ['d', 'b'], 1: ['c', 'a']} # dict2: {0: [0, 3], 1: [1, 2]} for k in dict1: dict1[k].sort() # we sort to get lexicographically # smallest letters first for i in range(len(dict2[k])): result[dict2[k][i]] = dict1[k][i] return "".join(result) class UnionFind: def __init__(self, size): self.root = [i for i in range(size)] self.rank = [1 for _ in range(size)] self.count = size def find(self, vert): if self.root[vert] == vert: return vert self.root[vert] = self.find(self.root[vert]) return self.root[vert] def union(self, v1, v2): r1 = self.find(v1) r2 = self.find(v2) if r1 != r2: if self.rank[r1] > self.rank[r2]: self.root[r2] = r1 elif self.rank[r1] < self.rank[r2]: self.root[r1] = r2 else: self.root[r2] = r1 self.rank[r1] += 1 self.count -= 1
smallest-string-with-swaps
Python UnionFind with step-by-step explanation
SleeplessChallenger
1
294
smallest string with swaps
1,202
0.576
Medium
18,196
https://leetcode.com/problems/smallest-string-with-swaps/discuss/2833578/python-union-find
class Solution: def smallestStringWithSwaps(self, s: str, pairs: List[List[int]]) -> str: u = [i for i in range(len(s))] def find_root(n): p = u[n] if p == n: return p else: r = find_root(p) u[n] = r return r for a, b in pairs: a_root = find_root(a) b_root = find_root(b) u[a_root] = b_root root_set = collections.defaultdict(list) for i in range(len(s)): root_set[find_root(i)].append(s[i]) root_set_p = collections.defaultdict(int) for k in root_set: root_set[k].sort() ret = [] for i in range(len(s)): r_i = find_root(i) ret.append(root_set[r_i][root_set_p[r_i]]) root_set_p[r_i] += 1 return "".join(ret)
smallest-string-with-swaps
python union find
xsdnmg
0
2
smallest string with swaps
1,202
0.576
Medium
18,197
https://leetcode.com/problems/smallest-string-with-swaps/discuss/2072337/Python-fast-and-simple-(98-Runtime-98-Memory)
class Solution: def smallestStringWithSwaps(self, s: str, pairs: List[List[int]]) -> str: v = defaultdict(list) for a, b in pairs: v[a].append(b) v[b].append(a) s = list(s) idxs, chrs = [], [] for i in range(len(s)): if s[i] != "" and i in v: idxs.append([]) chrs.append([]) stack = [i] while stack: idx = stack.pop() if s[idx] != "": stack.extend(v[idx]) idxs[-1].append(idx) chrs[-1].append(s[idx]) s[idx] = "" for idx, ch in zip(idxs, chrs): idx.sort() ch.sort() for i, c in zip(idx, ch): s[i] = c return "".join(s)
smallest-string-with-swaps
Python, fast and simple (98% Runtime, 98% Memory)
MihailP
0
98
smallest string with swaps
1,202
0.576
Medium
18,198
https://leetcode.com/problems/smallest-string-with-swaps/discuss/1986752/Python-Union-find-solution
class Solution: def find_parent(self, parent, x) -> int: if parent[x] != x: parent[x] = self.find_parent(parent, parent[x]) return parent[x] def union_parent(self, parent, a, b): a = self.find_parent(parent, a) b = self.find_parent(parent, b) if a < b: parent[b] = a else: parent[a] = b def smallestStringWithSwaps(self, s: str, pairs: List[List[int]]) -> str: if len(pairs) == 0: return s parent_of_s = [idx for idx in range(len(s))] for pair in pairs: if pair[0] == pair[1]: continue self.union_parent(parent_of_s, pair[0], pair[1]) # Collect interchangeable characters into dictionary dic = {} for idx in range(len(s)): if parent_of_s[idx] in dic: dic[parent_of_s[idx]].append(idx) else: dic[parent_of_s[idx]] = [idx] # Handles a set of children whose parent belong to another parent set. # ex) 0: [0, 1, 2, 3], 3: [4, 5, 6, 7] # parent of 3 is 3? No, it is 0 # So, dic[3] is integrated to dic[0] # parent of 0 is 0? Yes, so dic[0] no need to change for key in reversed(list(dic.keys())): if parent_of_s[key] != key: dic[parent_of_s[key]].extend(dic[key]) dic.pop(key) # Relocate interchangeable characters in sorted order. char_list = ['' for _ in range(len(s))] for key in dic: list_of_index = dic[key] list_of_char = [s[x] for x in list_of_index] list_of_char.sort() list_of_index.sort() for index_of_s, index_of_char in zip(list_of_index, range(len(list_of_char))): char_list[index_of_s] = list_of_char[index_of_char] return ''.join(char_list)
smallest-string-with-swaps
Python Union find solution
LeetMus
0
37
smallest string with swaps
1,202
0.576
Medium
18,199