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/di-string-match/discuss/1121091/Python-two-phases-solution
class Solution: def diStringMatch(self, S: str) -> List[int]: N = len(S) result = [0] * (N + 1) # start from 0 # and track the current minimal and maximal number. mi = mx = 0 n = 0 for i in range(N): if S[i] == 'I': mx += 1 result[i+1] = mx else: mi -= 1 result[i+1] = mi # because the maximum number must be N # add the 'diff' to shift all numbers into the corret range diff = N - mx for i in range(N+1): result[i] += diff return result
di-string-match
Python two phases solution
pochy
0
25
di string match
942
0.768
Easy
15,300
https://leetcode.com/problems/di-string-match/discuss/1032257/Python3-simple-and-efficient-solution
class Solution: def diStringMatch(self, S: str) -> List[int]: x = [] a = 0 b = len(S) for i in range(b): if S[i] == 'I': x.append(a) a += 1 else: x.append(b) b -= 1 x.append(b) return x
di-string-match
Python3 simple and efficient solution
EklavyaJoshi
0
45
di string match
942
0.768
Easy
15,301
https://leetcode.com/problems/di-string-match/discuss/1232339/python-easy-solution-or
class Solution: def diStringMatch(self, s: str) -> List[int]: a=0 b=len(s) ans=[] for j in s: if j=='I': ans.append(a) a+=1 else: ans.append(b) b-=1 ans.append(a) return ans
di-string-match
python easy solution |
chikushen99
-1
56
di string match
942
0.768
Easy
15,302
https://leetcode.com/problems/find-the-shortest-superstring/discuss/1231147/Python3-travelling-sales-person-(TSP)
class Solution: def shortestSuperstring(self, words: List[str]) -> str: n = len(words) graph = [[0]*n for _ in range(n)] # graph as adjacency matrix for i in range(n): for j in range(n): if i != j: for k in range(len(words[j])): if words[i].endswith(words[j][:k]): graph[i][j] = len(words[j]) - k @cache def fn(prev, mask): """Return length of shortest superstring &amp; current choice of word.""" if mask == 0: return 0, None vv, kk = inf, None for k in range(n): if mask &amp; 1<<k: v, _ = fn(k, mask ^ 1<<k) offset = len(words[k]) if prev == -1 else graph[prev][k] if v + offset < vv: vv, kk = v + offset, k return vv, kk ans = [] prev = -1 mask = (1<<n) - 1 while mask: _, k = fn(prev, mask) if ans: ans.append(words[k][-graph[prev][k]:]) else: ans.append(words[k]) prev = k mask ^= 1<<k return "".join(ans)
find-the-shortest-superstring
[Python3] travelling sales person (TSP)
ye15
1
441
find the shortest superstring
943
0.448
Hard
15,303
https://leetcode.com/problems/delete-columns-to-make-sorted/discuss/427225/Python3-6-line-96ms-beats-99-easy-to-understand
class Solution: def minDeletionSize(self, A: List[str]) -> int: zipped=list(map(list,zip(*A))) count=0 for item in zipped: if item!=sorted(item): count+=1 return count
delete-columns-to-make-sorted
Python3 6 line 96ms beats 99%, easy to understand
wangzi100
3
244
delete columns to make sorted
944
0.696
Easy
15,304
https://leetcode.com/problems/delete-columns-to-make-sorted/discuss/953723/Python-most-simple-O(NM)-time-O(1)-space
class Solution: def minDeletionSize(self, A: List[str]) -> int: res = 0 for pos in range(len(A[0])): for word in range(len(A)-1): if A[word][pos] > A[word+1][pos]: res += 1 break return res
delete-columns-to-make-sorted
Python most simple O(NM) time O(1) space
IKM98
2
223
delete columns to make sorted
944
0.696
Easy
15,305
https://leetcode.com/problems/delete-columns-to-make-sorted/discuss/382127/Solution-in-Python-3-(beats-~100)-(one-line)
class Solution: def minDeletionSize(self, A: List[str]) -> int: return sum(list(i) != sorted(i) for i in zip(*A)) - Junaid Mansuri (LeetCode ID)@hotmail.com
delete-columns-to-make-sorted
Solution in Python 3 (beats ~100%) (one line)
junaidmansuri
2
509
delete columns to make sorted
944
0.696
Easy
15,306
https://leetcode.com/problems/delete-columns-to-make-sorted/discuss/1309418/CLEANEST-CODE-no-extra-space-just-check-each-column-manually-whether-it-is-unsorted-%3A)
class Solution: def minDeletionSize(self, strs: List[str]) -> int: C = len(strs[0]) res = 0 for col in range(C): unsorted_flag = False for si in range(1, len(strs)): if strs[si][col] < strs[si-1][col]: unsorted_flag = True if unsorted_flag: res += 1 # this col is unsorted return res
delete-columns-to-make-sorted
CLEANEST CODE no extra space, just check each column manually whether it is unsorted :)
yozaam
1
91
delete columns to make sorted
944
0.696
Easy
15,307
https://leetcode.com/problems/delete-columns-to-make-sorted/discuss/2828234/Solution-without-sorting-oror-99.5-Faster
class Solution: def minDeletionSize(self, strs: List[str]) -> int: length = len(strs[0]) res= ''.join(strs) count =0 for idx in range(length): index=idx while(index+length<len(res)): if(ord(res[index])>ord(res[index+length])): count+=1 break index+=length return count
delete-columns-to-make-sorted
Solution without sorting || 99.5 % Faster
hasan2599
0
2
delete columns to make sorted
944
0.696
Easy
15,308
https://leetcode.com/problems/delete-columns-to-make-sorted/discuss/2804920/Simple-Python-Solution
class Solution: def minDeletionSize(self, strs: List[str]) -> int: n = len(strs[0]) l =[] j =0 #return n while j < n: a =[] for i in strs: a.append(i[j]) l.append(a) j+=1 c =0 for i in l: if sorted(i) != i: c+=1 return c
delete-columns-to-make-sorted
Simple Python Solution
Shagun_Mittal
0
2
delete columns to make sorted
944
0.696
Easy
15,309
https://leetcode.com/problems/delete-columns-to-make-sorted/discuss/2668287/Easy-approach
class Solution: def minDeletionSize(self, strs: List[str]) -> int: m, n = len(strs),len(strs[0]) ret = 0 for j in range(n): for i in range(m-1): if strs[i][j]> strs[i+1][j]: ret+=1 break return ret
delete-columns-to-make-sorted
Easy approach
prakhar_28581
0
3
delete columns to make sorted
944
0.696
Easy
15,310
https://leetcode.com/problems/delete-columns-to-make-sorted/discuss/2572849/Easy-Python-Solution
class Solution: def minDeletionSize(self, strs: List[str]) -> int: width = len(strs[0]) height = len(strs) unsorted = 0 for col in range(width): for row in range(1, height): if strs[row-1][col] > strs[row][col]: unsorted += 1 break return unsorted
delete-columns-to-make-sorted
Easy Python Solution
complete_noob
0
25
delete columns to make sorted
944
0.696
Easy
15,311
https://leetcode.com/problems/delete-columns-to-make-sorted/discuss/2367150/Readable-python-solution-hashmap
class Solution: def minDeletionSize(self, strs: List[str]) -> int: cols={} l=len(strs) l_s = len(strs[0]) delete = set() for i in range(l): for col in range(l_s): if col in cols: if cols[col]>strs[i][col]: delete.add(col) cols[col] = strs[i][col] return len(delete)
delete-columns-to-make-sorted
Readable python solution- hashmap
sunakshi132
0
27
delete columns to make sorted
944
0.696
Easy
15,312
https://leetcode.com/problems/delete-columns-to-make-sorted/discuss/1975052/Easiest-and-Simplest-Python-3-Solution-or-100-Faster-or-Beginner-Friendly-or-List-Operation
class Solution: def minDeletionSize(self, strs: List[str]) -> int: k=0 ss="" temp=[] ct=0 while k!=len(strs[0]): ss="" for i in range(len(strs)): ss=ss+strs[i][k] temp.append(ss) k+=1 for i in temp: test=list(i) test.sort() test="".join(test) if i!=test: ct+=1 return (ct)
delete-columns-to-make-sorted
Easiest & Simplest Python 3 Solution | 100% Faster | Beginner-Friendly | List Operation
RatnaPriya
0
89
delete columns to make sorted
944
0.696
Easy
15,313
https://leetcode.com/problems/delete-columns-to-make-sorted/discuss/1952767/Python-beats-100-and-EASY
class Solution: def minDeletionSize(self, strs: List[str]) -> int: ans = 0 for i in zip(*strs): if list(i) != sorted(i): ans += 1 return ans
delete-columns-to-make-sorted
Python beats 100% & EASY
psplove80048
0
62
delete columns to make sorted
944
0.696
Easy
15,314
https://leetcode.com/problems/delete-columns-to-make-sorted/discuss/1952677/easy-python-code
class Solution: def minDeletionSize(self, strs: List[str]) -> int: count = 0 for i in range(len(strs[0])): a = [] for j in range(len(strs)): a.append(strs[j][i]) if len(a)>1: if a[-1]<a[-2]: count += 1 break return count
delete-columns-to-make-sorted
easy python code
dakash682
0
46
delete columns to make sorted
944
0.696
Easy
15,315
https://leetcode.com/problems/delete-columns-to-make-sorted/discuss/1905313/Python-beginner-friendly-solution-using-2-loops-and-sorting
class Solution: def minDeletionSize(self, strs: List[str]) -> int: count = 0 for i in range(len(strs[0])): temp = "" for j in range(len(strs)): temp += strs[j][i] if ''.join(sorted(temp)) != temp: count += 1 return count
delete-columns-to-make-sorted
Python beginner friendly solution using 2 loops and sorting
alishak1999
0
36
delete columns to make sorted
944
0.696
Easy
15,316
https://leetcode.com/problems/delete-columns-to-make-sorted/discuss/1772086/python-3-easy-solution
class Solution: def minDeletionSize(self, strs: List[str]) -> int: n = len(strs) res = 0 for col in zip(*strs): for i in range(n - 1): if col[i] > col[i+1]: res += 1 break return res
delete-columns-to-make-sorted
python 3, easy solution
dereky4
0
104
delete columns to make sorted
944
0.696
Easy
15,317
https://leetcode.com/problems/delete-columns-to-make-sorted/discuss/1450068/Zip-2-times-73-speed
class Solution: def minDeletionSize(self, strs: List[str]) -> int: count = 0 for col in zip(*strs): for a, b in zip(col, col[1:]): if a > b: count += 1 break return count
delete-columns-to-make-sorted
Zip 2 times, 73% speed
EvgenySH
0
90
delete columns to make sorted
944
0.696
Easy
15,318
https://leetcode.com/problems/delete-columns-to-make-sorted/discuss/1173829/Python-pythonic
class Solution: def minDeletionSize(self, strs: List[str]) -> int: result = 0 for i in range(len(strs[0])): temp = [x[i] for x in strs] result += 0 if temp == sorted(temp) else 1 return result
delete-columns-to-make-sorted
[Python] pythonic
cruim
0
59
delete columns to make sorted
944
0.696
Easy
15,319
https://leetcode.com/problems/delete-columns-to-make-sorted/discuss/1040023/Python3-easy-solution-using-%22zip%22-and-%22set%22
class Solution: def minDeletionSize(self, A: List[str]) -> int: d = set() A = list(zip(*A)) for i in range(len(A)): if not sorted(A[i]) == list(A[i]): d.add(i) return len(d)
delete-columns-to-make-sorted
Python3 easy solution using "zip" and "set"
EklavyaJoshi
0
66
delete columns to make sorted
944
0.696
Easy
15,320
https://leetcode.com/problems/delete-columns-to-make-sorted/discuss/606424/Intuitive-solution-and-easy-to-understand
class Solution: def minDeletionSize(self, A: List[str]) -> int: d = 0 for t in zip(*A): # Confirm if all chars are follow increasing order c = t[0] for nc in t[1:]: if nc < c: # Found decreasing and break d += 1 break else: c = nc return d
delete-columns-to-make-sorted
Intuitive solution and easy to understand
puremonkey2001
0
59
delete columns to make sorted
944
0.696
Easy
15,321
https://leetcode.com/problems/delete-columns-to-make-sorted/discuss/587921/Simple-Python-Solution
class Solution: def minDeletionSize(self, A: List[str]) -> int: deletionIndices=[] x=[] length=len(A[0]) counter=-1 for i in range(length): check=[] acheck=[] for j in range(len(A)): check.append(A[j][i]) acheck=sorted(check) if check!=acheck: deletionIndices.append(i) break return len(deletionIndices)
delete-columns-to-make-sorted
Simple Python Solution
Ayu-99
0
86
delete columns to make sorted
944
0.696
Easy
15,322
https://leetcode.com/problems/minimum-increment-to-make-array-unique/discuss/1897470/PYTHON-SOL-oror-WELL-EXPLAINED-oror-SORTING-ororGREEDYoror-APPROACH-EXPLAINED-oror-SIMPLE-oror-O(n*log(n))oror
class Solution: def minIncrementForUnique(self, nums: List[int]) -> int: nums.sort() n = len(nums) ans = 0 for i in range(1,n): if nums[i] <= nums[i-1]: # this is the case for making item unique diff = nums[i-1] + 1 - nums[i] ans += diff nums[i] = nums[i-1] + 1 return ans
minimum-increment-to-make-array-unique
PYTHON SOL || WELL EXPLAINED || SORTING ||GREEDY|| APPROACH EXPLAINED || SIMPLE || O(n*log(n))||
reaper_27
8
271
minimum increment to make array unique
945
0.504
Medium
15,323
https://leetcode.com/problems/minimum-increment-to-make-array-unique/discuss/1156808/O(n)-Python3-%3A-Easy-to-understand
class Solution: def minIncrementForUnique(self, A: List[int]) -> int: A.sort() count = 0 for i in range(1, len(A)): cur = A[i] prev = A[i-1] if(prev >= cur ): A[i] = prev + 1 count += prev - cur + 1 return count
minimum-increment-to-make-array-unique
O(n) Python3 : Easy to understand
abhijeetmallick29
1
197
minimum increment to make array unique
945
0.504
Medium
15,324
https://leetcode.com/problems/minimum-increment-to-make-array-unique/discuss/2336640/Using-Bool-Array
class Solution: def minIncrementForUnique(self, nums: List[int]) -> int: map_array = [False]*(10**6); for i in range(len(nums)): map_array[nums[i]] = True; nums.sort(); moves_count = 0; prev_max = 0; for i in range(1,len(nums)): if nums[i] == nums[i-1]: prev_max = max(prev_max,nums[i]); while map_array[prev_max] != False: prev_max += 1; map_array[prev_max] = True; moves_count += (prev_max-nums[i]); return moves_count;
minimum-increment-to-make-array-unique
Using Bool Array
DUMMY_BUG
0
22
minimum increment to make array unique
945
0.504
Medium
15,325
https://leetcode.com/problems/minimum-increment-to-make-array-unique/discuss/2097620/Python3-or-Simple-and-short-solution-or-O(nlogn)-or-O(1)-space
class Solution: def minIncrementForUnique(self, nums: List[int]) -> int: nums.sort() count = 0 for i in range(1, len(nums)): if nums[i]<=nums[i-1]: count+= (nums[i-1]+1 - nums[i]) nums[i] = nums[i-1]+1 return count
minimum-increment-to-make-array-unique
Python3 | Simple and short solution | O(nlogn) | O(1) space
HemantRana
0
39
minimum increment to make array unique
945
0.504
Medium
15,326
https://leetcode.com/problems/minimum-increment-to-make-array-unique/discuss/2068756/Python3-easy-sort-and-then-iterate
class Solution: def minIncrementForUnique(self, nums: List[int]) -> int: nums.sort() n = len(nums) moves = 0 prev = nums[0] for i in range(1, n): if nums[i] <= prev: moves = moves + prev +1 - nums[i] nums[i] = prev +1 prev = nums[i] return moves Runtime: 1151 ms, faster than 48.92% of Python3 online submissions for Minimum Increment to Make Array Unique. Memory Usage: 28.3 MB, less than 50.69% of Python3 online submissions for Minimum Increment to Make Array Unique.
minimum-increment-to-make-array-unique
Python3 easy sort and then iterate
emerald19
0
66
minimum increment to make array unique
945
0.504
Medium
15,327
https://leetcode.com/problems/minimum-increment-to-make-array-unique/discuss/1687157/Python-or-Stack
class Solution: def minIncrementForUnique(self, nums: List[int]) -> int: nums.sort() new=nums[0]+1 stk=set({nums[0]}) ans=0 for n in nums[1:]: if n not in stk: stk.add(n) new=n+1 else: ans+=new-n stk.add(new) new+=1 return ans
minimum-increment-to-make-array-unique
Python | Stack
heckt27
0
38
minimum increment to make array unique
945
0.504
Medium
15,328
https://leetcode.com/problems/minimum-increment-to-make-array-unique/discuss/1510656/Python3-Solution-with-using-sorting
class Solution: def minIncrementForUnique(self, nums: List[int]) -> int: nums.sort() cnt = 0 for idx in range(1, len(nums)): prev = nums[idx - 1] if prev >= nums[idx]: cnt += prev - nums[idx] + 1 nums[idx] = prev + 1 return cnt
minimum-increment-to-make-array-unique
[Python3] Solution with using sorting
maosipov11
0
110
minimum increment to make array unique
945
0.504
Medium
15,329
https://leetcode.com/problems/minimum-increment-to-make-array-unique/discuss/959042/Python3-greedy-O(NlogN)
class Solution: def minIncrementForUnique(self, A: List[int]) -> int: ans = cap = 0 for x in sorted(A): ans += max(0, cap - x) cap = max(cap, x) + 1 return ans
minimum-increment-to-make-array-unique
[Python3] greedy O(NlogN)
ye15
0
87
minimum increment to make array unique
945
0.504
Medium
15,330
https://leetcode.com/problems/minimum-increment-to-make-array-unique/discuss/405471/Python-3-(beats-~99)-(three-lines)
class Solution: def minIncrementForUnique(self, A: List[int]) -> int: m, c, _ = -math.inf, 0, A.sort() for a in A: if a <= m: c += 1 + m - a m += 1 else: m = a return c
minimum-increment-to-make-array-unique
Python 3 (beats ~99%) (three lines)
junaidmansuri
-2
536
minimum increment to make array unique
945
0.504
Medium
15,331
https://leetcode.com/problems/minimum-increment-to-make-array-unique/discuss/405471/Python-3-(beats-~99)-(three-lines)
class Solution: def minIncrementForUnique(self, A: List[int]) -> int: m, c, _ = -math.inf, 0, A.sort() for a in A: (c, m) = (c + (1 + m - a), m + 1) if a <= m else (c, a) return c - Junaid Mansuri
minimum-increment-to-make-array-unique
Python 3 (beats ~99%) (three lines)
junaidmansuri
-2
536
minimum increment to make array unique
945
0.504
Medium
15,332
https://leetcode.com/problems/validate-stack-sequences/discuss/1106110/Easy-python-solution-or-86-memory-86-time
class Solution: def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool: stack = [] for i in pushed: stack.append(i) while stack and popped and stack[-1] == popped[0]: stack.pop() popped.pop(0) return not stack
validate-stack-sequences
Easy python solution | 86% memory 86% time
vanigupta20024
6
259
validate stack sequences
946
0.676
Medium
15,333
https://leetcode.com/problems/validate-stack-sequences/discuss/1854875/python3-stack-solution-with-try-and-except
class Solution: def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool: s = [] ipush = 0 ipop = 0 try: while ipush < len(pushed) or ipop < len(popped): if len(s) == 0 or (len(s) != 0 and s[-1] != popped[ipop]): s.append(pushed[ipush]) ipush += 1 elif s[-1] == popped[ipop]: s.pop() ipop += 1 except IndexError: return False return True
validate-stack-sequences
python3 stack solution with try and except
DheerajGadwala
2
17
validate stack sequences
946
0.676
Medium
15,334
https://leetcode.com/problems/validate-stack-sequences/discuss/1853257/Readable-Python-solution
class Solution: def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool: stack = [] for num in pushed: stack.append(num) while len(stack) > 0 and stack[-1] == popped[0]: stack.pop() popped.pop(0) if len(stack) == 0: return True else: return False
validate-stack-sequences
Readable Python solution
zebra-f
2
33
validate stack sequences
946
0.676
Medium
15,335
https://leetcode.com/problems/validate-stack-sequences/discuss/1853628/python3or-fastest-solution
class Solution: def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool: stack=[] index=0 n=len(pushed) for i in pushed: stack.append(i) while len(stack)>0 and index<n and popped[index]==stack[-1]: stack.pop() index+=1 return index==n
validate-stack-sequences
python3| fastest solution
Anilchouhan181
1
56
validate stack sequences
946
0.676
Medium
15,336
https://leetcode.com/problems/validate-stack-sequences/discuss/1220344/Python-Solution
class Solution: def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool: stack, pushed, popped = [], collections.deque(pushed), collections.deque(popped) while pushed or popped: try: while not stack or stack[-1] != popped[0]: stack += [pushed.popleft()] stack.pop(), popped.popleft() except: return False return True
validate-stack-sequences
Python Solution
dev-josh
1
64
validate stack sequences
946
0.676
Medium
15,337
https://leetcode.com/problems/validate-stack-sequences/discuss/2845458/python-easy-to-understand
class Solution: def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool: tmp, i = [],0 for num in pushed: tmp.append(num) #if tmp is not empty and the last item of tmp is equal to popped[i], #then it means the item of popped[i] can be popped for this sequence. #because the first popped item is the last item of tmp, #if popped[i] isn't equal to tmp[-1], it can't be popped. while tmp and tmp[-1]==popped[i]: tmp.pop() i += 1 if not tmp: return True else: return False
validate-stack-sequences
python easy to understand
xiaolaotou
0
1
validate stack sequences
946
0.676
Medium
15,338
https://leetcode.com/problems/validate-stack-sequences/discuss/2831764/Python-Solution-Stack-Approach-oror-Easy-Understanding
class Solution: def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool: #this is what happening in examples -> if stack[-1]==popped[0] then do pop in stack and popped till they are same stack=[] j=0 for i in pushed: stack.append(i) while j<len(popped) and len(stack)!=0 and stack[-1]==popped[j]: stack.pop() j+=1 return len(stack)==0
validate-stack-sequences
Python Solution -Stack Approach || Easy- Understanding
T1n1_B0x1
0
1
validate stack sequences
946
0.676
Medium
15,339
https://leetcode.com/problems/validate-stack-sequences/discuss/2830413/Python.-Stack-solution-with-explanation.
class Solution: def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool: pushed = pushed[::-1] stack = [] for i in popped: if stack and stack[-1] == i: stack.pop() else: while pushed: cur = pushed.pop() stack.append(cur) if i == cur: stack.pop() break return not stack
validate-stack-sequences
Python. Stack solution with explanation.
ebarykin
0
9
validate stack sequences
946
0.676
Medium
15,340
https://leetcode.com/problems/validate-stack-sequences/discuss/2241045/O(1)-space
class Solution: def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool: i=0 j=0 for e in pushed: pushed[i]=e while i>=0 and popped[j]==pushed[i]: j+=1 i-=1 i+=1 return i==0
validate-stack-sequences
O(1) space
HaoChenNus
0
9
validate stack sequences
946
0.676
Medium
15,341
https://leetcode.com/problems/validate-stack-sequences/discuss/2043454/Python-simulation
class Solution: def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool: stack = [] i = j = 0 while i < len(pushed) or j < len(popped): if stack and j < len(popped) and stack[-1] == popped[j]: j += 1 stack.pop() else: if i == len(pushed): return False stack.append(pushed[i]) i += 1 return True
validate-stack-sequences
Python, simulation
blue_sky5
0
26
validate stack sequences
946
0.676
Medium
15,342
https://leetcode.com/problems/validate-stack-sequences/discuss/1903682/Python-easy-to-read-and-understand-or-stack
class Solution: def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool: stack = [] while popped: if stack and popped[0] == stack[-1]: popped.pop(0) stack.pop() elif pushed: stack.append(pushed.pop(0)) else: return False return True
validate-stack-sequences
Python easy to read and understand | stack
sanial2001
0
50
validate stack sequences
946
0.676
Medium
15,343
https://leetcode.com/problems/validate-stack-sequences/discuss/1897500/PYTHON-SOL-oror-EXPLAINED-WELL-oror-STACK-oror-LINEAR-TIME-AND-SPACE-oror
class Solution: def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool: stack = [] idx = 0 for i in pushed: stack.append(i) while stack and popped[idx] == stack[-1]: stack.pop() idx += 1 return stack == []
validate-stack-sequences
PYTHON SOL || EXPLAINED WELL || STACK || LINEAR TIME AND SPACE ||
reaper_27
0
21
validate stack sequences
946
0.676
Medium
15,344
https://leetcode.com/problems/validate-stack-sequences/discuss/1856281/Tricked-Solution
class Solution: def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool: rel=["k"] popped.append("z") popped[:]=popped[::-1] #by this, we can use as a stack for i in pushed: rel.append(i) while rel[-1]==popped[-1]: #k and z are inserted to rel and popped to subdue Index Out Of Range rel.pop() popped.pop() return len(popped)==1 #as we have inserted z in popped so now length should be equal to one
validate-stack-sequences
Tricked Solution
AjayKadiri
0
6
validate stack sequences
946
0.676
Medium
15,345
https://leetcode.com/problems/validate-stack-sequences/discuss/1856214/Python3-95.52-or-Stack-Simulation-(Greedy)-or-Easy-Implementaion-and-Commented
class Solution: def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool: # simulation stack st = [] # simulation queue q = deque(popped) # greedy cancel (pop st and q) the sequences when you can for ele in pushed: st.append(ele) # greedy while st and q and st[-1] == q[0]: st.pop() q.popleft() # if the q is not caceled out, return False return not q
validate-stack-sequences
Python3 95.52% | Stack Simulation (Greedy) | Easy Implementaion & Commented
doneowth
0
10
validate stack sequences
946
0.676
Medium
15,346
https://leetcode.com/problems/validate-stack-sequences/discuss/1856185/Python-or-64-ms-or-Stack
class Solution: def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool: pushed_size = len(pushed) popped_index = 0 pushed_index = 0 stack = [] for i in range(pushed_size * 2): if not stack: stack.append(pushed[pushed_index]) pushed_index +=1 continue if (popped[popped_index] == stack[-1]): stack.pop() popped_index += 1 continue; else: if pushed_index >= pushed_size: return False else: stack.append(pushed[pushed_index]) pushed_index +=1 continue return True
validate-stack-sequences
Python | 64 ms | Stack
chinjiec
0
6
validate stack sequences
946
0.676
Medium
15,347
https://leetcode.com/problems/validate-stack-sequences/discuss/1855648/Simple-Python3-Solution
class Solution: def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool: pop_idx, stack = 0, [] for push_val in pushed: stack.append(push_val) while len(stack) and stack[-1] == popped[pop_idx]: stack.pop() pop_idx+=1 return len(stack) == 0
validate-stack-sequences
Simple Python3 Solution
user6774u
0
12
validate stack sequences
946
0.676
Medium
15,348
https://leetcode.com/problems/validate-stack-sequences/discuss/1854800/PYTHON-STACK-solution-step-by-step-(76ms)
class Solution: def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool: LENGTH = len ( pushed ); #Putting in a sentinel at the end to prevent index error with pointers pushed.append( - 1 ); popped.append( - 1 ); #Creating a new stack with a sentinel at the bottom stackTracker = [ -1 ]; #Two pointers starting at the beginning of each list push_pointer = 0; pop_pointer = 0; #Actions tell me the operations requried to #Complete all push and pop operations ACTIONS = (LENGTH - 1) * 2; #We use the pointers to keep track of actions while ( push_pointer + pop_pointer ) <= ACTIONS : #At each level, look at the current push and pop current_pop = popped[ pop_pointer ]; current_push = pushed[ push_pointer ]; #See if we have either a valid pop or push operation #A valid pop will be if there is a matching with our stack's top validPop = ( current_pop == stackTracker[ - 1 ] ); #A valid push will be if there is room in our push pointer #To move it again ( if not, it will be at the sentinel ) validPush = push_pointer < LENGTH; #If we can pop if validPop: #Pop from our stack, and move the pointer stackTracker.pop(); pop_pointer += 1; #If we can't pop, but can push #Push that value onto the top of our stack #And move the pointer elif validPush: stackTracker.append( pushed [ push_pointer ] ); push_pointer += 1; #If we can neither push nor pop #Return False elif not validPop and not validPush: return False; #Once we make it to the end, #And have succesfully completed all actions #The while loop will exit #We can return True return True;
validate-stack-sequences
PYTHON STACK solution step-by-step (76ms)
greg_savage
0
10
validate stack sequences
946
0.676
Medium
15,349
https://leetcode.com/problems/validate-stack-sequences/discuss/1854527/Python-stack-solution
class Solution: def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool: ans = [] i = 0 for j in pushed: ans.append(j) # print(i,j,ans,popped) while i<len(popped) and len(ans)!=0 and popped[i]==ans[-1]: i+=1 ans.pop() if len(ans) == 0: return True else: return False
validate-stack-sequences
Python stack solution
Brillianttyagi
0
7
validate stack sequences
946
0.676
Medium
15,350
https://leetcode.com/problems/validate-stack-sequences/discuss/1854384/Easy-to-Understand-Python3-solution
class Solution: def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool: new_arr = [] while pushed or popped: if popped and new_arr: if popped[0] == new_arr[-1]: new_arr.pop(-1) popped.pop(0) continue if pushed : new_arr.append(pushed[0]) pushed.pop(0) else: return False return True
validate-stack-sequences
Easy to Understand Python3 solution
shubham3
0
4
validate stack sequences
946
0.676
Medium
15,351
https://leetcode.com/problems/validate-stack-sequences/discuss/1854347/Python-or-Easy-solution-with-commented-explanation
class Solution: def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool: stack=[] #As the question says that pushed and popped have same length, then pushed will get empty first after all operations while len(pushed)!=0: stack.append(pushed.pop(0)) #Start pushing the elements instack while len(popped)!=0 and len(stack)!=0 and popped[0]==stack[-1]: #If the top of stack and first of popped match..bingo..we pop both of them out stack.pop() popped.pop(0) #At the end of while loop all the match will get popped out #In the end, only the ones which aren't able to pop will be left which will be shown by the length of stack... #Hence... return len(stack)==0
validate-stack-sequences
Python | Easy solution with commented explanation
RickSanchez101
0
12
validate stack sequences
946
0.676
Medium
15,352
https://leetcode.com/problems/validate-stack-sequences/discuss/1854203/Python3-Simple-Stack-solution
class Solution: def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool: st = [] popped.reverse() for i in range(len(pushed)): if pushed[i] == popped[-1]: popped.pop() while st and st[-1] == popped[-1]: st.pop() popped.pop() else: st.append(pushed[i]) return True if st == popped else False
validate-stack-sequences
[Python3] Simple Stack solution
nandhakiran366
0
7
validate stack sequences
946
0.676
Medium
15,353
https://leetcode.com/problems/validate-stack-sequences/discuss/1854145/Python3-Solution-with-using-stack
class Solution: def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool: it = 0 stack = [] for elem in pushed: stack.append(elem) while stack and it < len(popped) and stack[-1] == popped[it]: stack.pop() it += 1 return it == len(popped)
validate-stack-sequences
[Python3] Solution with using stack
maosipov11
0
9
validate stack sequences
946
0.676
Medium
15,354
https://leetcode.com/problems/validate-stack-sequences/discuss/1854046/Python-Very-Easy-O(N)
class Solution: def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool: stack, b = [], 0 for i in popped: if stack and stack[-1] == i: stack.pop() continue while b < len(pushed) and pushed[b] != i: stack.append(pushed[b]) b += 1 b += 1 return not stack
validate-stack-sequences
✅ Python Very Easy O(N)
dhananjay79
0
14
validate stack sequences
946
0.676
Medium
15,355
https://leetcode.com/problems/validate-stack-sequences/discuss/1853960/Python-Easy-to-understand-O(1)-Space-and-Faster-Than-95
class Solution: def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool: stack=list() i=0 j=0 n=len(pushed) m=len(popped) while(i<n): stack.append(pushed[i]) i+=1 while(len(stack)>0 and stack[-1]==popped[j]): stack.pop() j+=1 return (len(stack)==0)
validate-stack-sequences
Python Easy to understand O(1) Space and Faster Than 95%
bhawesh_bhashkar
0
9
validate stack sequences
946
0.676
Medium
15,356
https://leetcode.com/problems/validate-stack-sequences/discuss/1853885/Self-Understandable-Python-(2-methods)-%3A
class Solution: def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool: stack=[] i=0 for p in pushed: stack.append(p) while stack and stack[-1]==popped[i]: stack.pop() i+=1 if stack: return False return True
validate-stack-sequences
Self Understandable Python (2 methods) :
goxy_coder
0
34
validate stack sequences
946
0.676
Medium
15,357
https://leetcode.com/problems/validate-stack-sequences/discuss/1853885/Self-Understandable-Python-(2-methods)-%3A
class Solution: def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool: if pushed==popped or pushed==popped[::-1]: return True i,j=0,0 stack=[] m=0 while i<=len(pushed) and j<len(popped): if m==i: # item can be pushed only once into stack stack.append(pushed[i]) m=i+1 if stack[-1]!=popped[j]: i+=1 elif stack[-1]==popped[j]: stack.pop() j+=1 if not stack: i+=1 if i>=len(pushed): break if stack: return False return True
validate-stack-sequences
Self Understandable Python (2 methods) :
goxy_coder
0
34
validate stack sequences
946
0.676
Medium
15,358
https://leetcode.com/problems/validate-stack-sequences/discuss/1853761/Python-3-or-Easy-Solution-or-O(N)
class Solution: def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool: pop_idx, stack = 0, [] for push_val in pushed: stack.append(push_val) while len(stack) and stack[-1] == popped[pop_idx]: stack.pop() pop_idx+=1 return len(stack) == 0
validate-stack-sequences
Python 3 | Easy Solution | O(N)
sathwickreddy
0
20
validate stack sequences
946
0.676
Medium
15,359
https://leetcode.com/problems/validate-stack-sequences/discuss/1853672/Python-or-TC-O(N)SC-O(N)-or-EASY-Code-or-Faster-than-97-or
class Solution(object): def validateStackSequences(self, pushed, popped): """ :type pushed: List[int] :type popped: List[int] :rtype: bool """ popIdx = 0 stack = [] for push in pushed: stack.append(push) while stack and popIdx < len(popped) and stack[-1] == popped[popIdx]: stack.pop() popIdx += 1 return popIdx == len(popped)
validate-stack-sequences
Python | TC-O(N)/SC-O(N) | EASY Code | Faster than 97% |
Patil_Pratik
0
9
validate stack sequences
946
0.676
Medium
15,360
https://leetcode.com/problems/validate-stack-sequences/discuss/1853330/Python-Simple-Python-Solution-Using-Stack-and-Iterative-Approach
class Solution: def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool: stack = [] i , j = 0 , 0 while i<len(pushed): stack.append(pushed[i]) while stack and j<len(popped) and stack[-1]==popped[j]: stack.pop() j=j+1 i=i+1 if j == len(popped): return True else: return False
validate-stack-sequences
[ Python ] ✔✔ Simple Python Solution Using Stack and Iterative Approach 🔥✌
ASHOK_KUMAR_MEGHVANSHI
0
28
validate stack sequences
946
0.676
Medium
15,361
https://leetcode.com/problems/validate-stack-sequences/discuss/1853191/Python-Easy-understand-illustrate-with-comment
class Solution: def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool: val = [pushed.pop(0)] # val = list() is more clean but more one time loop in while while pushed or popped: # two list have value if val and val[-1] == popped[0] : # if last value in val-list is equal to first value in popped then remove them val.pop() popped.pop(0) elif pushed : # append first value in pushed to val-list val.append(pushed.pop(0)) elif popped : # non value in pushed, so compare popped and val but not pass first if => Can't pop last value of val-list return 0 return 1 # non value in pushed and popped => none value in val-list
validate-stack-sequences
[Python] Easy-understand illustrate with comment
crazypuppy
0
14
validate stack sequences
946
0.676
Medium
15,362
https://leetcode.com/problems/validate-stack-sequences/discuss/1853168/Python-Solution
class Solution: def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool: my_res = [] for i in pushed: my_res.append(i) while my_res and my_res[-1] == popped[0]: popped = popped[1:] my_res.pop() return (my_res) == []
validate-stack-sequences
✔Python Solution
Coding_Tan3
0
10
validate stack sequences
946
0.676
Medium
15,363
https://leetcode.com/problems/validate-stack-sequences/discuss/1853161/Elixir-and-Python3-Simple-Pattern-Matching-Solution
class Solution: def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool: u_h, *u_t = pushed return self.test(u_t, popped, [u_h]) def test(self, pushed, popped, test): l_u, l_o, l_t = len(pushed), len(popped), len(test) if l_u == 0 and l_o == 0 and l_t == 0: return True if l_u > 0: u_h, *u_t = pushed else: u_h, u_t = None, [] if l_o > 0: o_h, *o_t = popped else: o_h, o_t = None, [] if l_t > 0: t_h, *t_t = test else: t_h, t_t = None, [] if o_h == t_h: return self.test(pushed, o_t, t_t) elif l_u > 0: test.insert(0, u_h) return self.test(u_t, popped, test) else: return False
validate-stack-sequences
Elixir and Python3, Simple Pattern-Matching Solution
bpfaust
0
14
validate stack sequences
946
0.676
Medium
15,364
https://leetcode.com/problems/validate-stack-sequences/discuss/1853115/Easy-Intuitive-Solution-in-Python
class Solution: def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool: s1 = [] i = 0 for p in pushed: s1.append(p) while s1 and s1[-1] == popped[i]: s1.pop() i += 1 if not s1: return True else: return False
validate-stack-sequences
Easy Intuitive Solution in Python
Jazzyb1999
0
16
validate stack sequences
946
0.676
Medium
15,365
https://leetcode.com/problems/validate-stack-sequences/discuss/1853112/Python-Stack-or-Beats-98
class Solution: def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool: stack = [] pop_index = 0 for i in pushed: stack.append(i) while stack and stack[-1] == popped[pop_index]: stack.pop() pop_index += 1 if len(stack) > 0: return False return True
validate-stack-sequences
[Python] Stack | Beats 98%
tejeshreddy111
0
28
validate stack sequences
946
0.676
Medium
15,366
https://leetcode.com/problems/validate-stack-sequences/discuss/1365420/Not-the-Fastest-but-easy-understand-with-explanation-(python3)
class Solution: def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool: ans = [] # If "popped" is not empty, we keep worknig on it. while len(popped) != 0: # If ans is empty, we should append the first element from the "pushed". # Also, we must remember to remove the element from the "pushed". if len(ans) == 0: ans.append(int(pushed[0])) pushed.pop(0) # Create an index that allows us to find the last element of the "ans". index = len(ans)-1 # If the "ans"'s last ele is not equal to the first ele of "popped", then we keep adding the ele from "pushed". if int(ans[index]) != int(popped[0]): if len(pushed) != 0: add = pushed[0] ans.append(add) pushed.pop(0) # Considering when the "pushed" is empty, we have nothing to add in the "ans". else: break # Else, we have to remove the ele from the "ans" and the "popped". else: ans.pop() popped.pop(0) return len(ans) == 0
validate-stack-sequences
Not the Fastest, but easy understand with explanation (python3)
An_222
0
69
validate stack sequences
946
0.676
Medium
15,367
https://leetcode.com/problems/validate-stack-sequences/discuss/1326038/Python3-solution-single-pass-using-stack
class Solution: def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool: x = -1 l = [] for i in popped: if i not in l: a = pushed.index(i) l += pushed[x+1:a] x = a else: if l[-1] == i: l.pop() else: return False return True
validate-stack-sequences
Python3 solution single pass using stack
EklavyaJoshi
0
44
validate stack sequences
946
0.676
Medium
15,368
https://leetcode.com/problems/validate-stack-sequences/discuss/1083998/python-on-solution-using-stack
class Solution: def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool: j = 0 stack,output = [],[] for i in range(len(pushed)): if pushed[i] != popped[j]: stack.append(pushed[i]) elif pushed[i] == popped[j]: j += 1 while stack and stack[-1] == popped[j]: stack.pop() j += 1 return popped[j:] == stack[::-1]
validate-stack-sequences
python on solution using stack
yingziqing123
0
33
validate stack sequences
946
0.676
Medium
15,369
https://leetcode.com/problems/validate-stack-sequences/discuss/1083594/Python-or-Fast-and-Easy-or-Beats-99
class Solution: def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool: l = deque() for i in pushed: l.append(i) while l and popped and l[-1] == popped[0]: popped.pop(0) l.pop() return not popped
validate-stack-sequences
Python | Fast & Easy | Beats 99%
SlavaHerasymov
0
45
validate stack sequences
946
0.676
Medium
15,370
https://leetcode.com/problems/validate-stack-sequences/discuss/1055505/Easy-python-solution-O(N)-runtime
class Solution: def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool: stack = [] for i in pushed: while stack and stack[-1] == popped[0]: stack.pop() popped.pop(0) stack.append(i) while stack and stack[-1] == popped[0]: stack.pop() popped.pop(0) return len(stack) == 0
validate-stack-sequences
Easy python solution - O(N) runtime
Ayush87
0
40
validate stack sequences
946
0.676
Medium
15,371
https://leetcode.com/problems/validate-stack-sequences/discuss/1049309/Python-stack-solution
class Solution: def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool: stack=[] curr=0 for i in range(len(pushed)): stack.append(pushed[i]) while stack and stack[-1]==popped[curr]: stack.pop() curr+=1 return not stack
validate-stack-sequences
Python stack solution
samarthnehe
0
31
validate stack sequences
946
0.676
Medium
15,372
https://leetcode.com/problems/validate-stack-sequences/discuss/966373/Python3-stack-O(N)
class Solution: def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool: i = 0 stack = [] for x in pushed: stack.append(x) while stack and stack[-1] == popped[i]: stack.pop() i += 1 return not stack
validate-stack-sequences
[Python3] stack O(N)
ye15
0
40
validate stack sequences
946
0.676
Medium
15,373
https://leetcode.com/problems/most-stones-removed-with-same-row-or-column/discuss/1689443/For-Beginners-oror-Count-Number-of-Connected-Graphs-O(N)-oror-94-Faster
class Solution: def removeStones(self, stones: List[List[int]]) -> int: def remove_point(a,b): # Function to remove connected points from the ongoing graph. points.discard((a,b)) for y in x_dic[a]: if (a,y) in points: remove_point(a,y) for x in y_dic[b]: if (x,b) in points: remove_point(x,b) x_dic = defaultdict(list) y_dic = defaultdict(list) points= {(i,j) for i,j in stones} for i,j in stones: # Construction of graph by x_coordinates and y_coordinates. x_dic[i].append(j) y_dic[j].append(i) cnt = 0 for a,b in stones: # counting of distinct connected graph. if (a,b) in points: remove_point(a,b) cnt+=1 return len(stones)-cnt
most-stones-removed-with-same-row-or-column
📌📌 For Beginners || Count Number of Connected Graphs O(N) || 94% Faster 🐍
abhi9Rai
22
1,500
most stones removed with same row or column
947
0.588
Medium
15,374
https://leetcode.com/problems/most-stones-removed-with-same-row-or-column/discuss/1900212/PYTHON-SOL-oror-WELL-EXPLAINED-oror-FASTER-THAN-97-oror-APPROACH-EXPLAINED-oror-DFS-oror
class Solution: def removeStones(self, stones: List[List[int]]) -> int: n = len(stones) visited = [False]*n rows = defaultdict(list) cols = defaultdict(list) ans = 0 for i,point in enumerate(stones): rows[point[0]].append(i) cols[point[1]].append(i) def dfs(node): visited[node] = True count = 1 for x in rows[stones[node][0]]: if visited[x] == False: count += dfs(x) for x in cols[stones[node][1]]: if visited[x] == False: count += dfs(x) return count for i in range(n): if visited[i] == False: size = dfs(i) ans += size-1 return ans
most-stones-removed-with-same-row-or-column
PYTHON SOL || WELL EXPLAINED || FASTER THAN 97% || APPROACH EXPLAINED || DFS ||
reaper_27
4
472
most stones removed with same row or column
947
0.588
Medium
15,375
https://leetcode.com/problems/most-stones-removed-with-same-row-or-column/discuss/2488227/python-3-or-clean-union-find
class Solution: def removeStones(self, stones: List[List[int]]) -> int: n = len(stones) rank = [1] * n parent = [i for i in range(n)] def union(i, j): i, j = find(i), find(j) if i == j: return 0 if rank[i] < rank[j]: i, j = j, i rank[i] += rank[j] parent[j] = parent[i] return 1 def find(i): while i != parent[i]: parent[i] = i = parent[parent[i]] return i rows, cols = {}, {} removed = 0 for i, (row, col) in enumerate(stones): if row in rows: removed += union(i, rows[row]) else: rows[row] = i if col in cols: removed += union(i, cols[col]) else: cols[col] = i return removed
most-stones-removed-with-same-row-or-column
python 3 | clean union find
dereky4
2
404
most stones removed with same row or column
947
0.588
Medium
15,376
https://leetcode.com/problems/most-stones-removed-with-same-row-or-column/discuss/1659025/BFS-%2B-hashmap
class Solution: def removeStones(self, stones: List[List[int]]) -> int: # create a completed graph, use graphX to store the node with same x axis and use graphY to store the node with the same y axis # Use BFS # Use visited to store the passed node # for one conneted graph count the (node number -1), and let it be ni # At the end, add all the ni in each connected graphs # Time: O(V+E) Space:O(V+E) hmapX = defaultdict(list) hmapY = defaultdict(list) for st in stones: hmapX[st[0]].append(tuple(st)) hmapY[st[1]].append(tuple(st)) print(hmapX) print(hmapY) visited = set() count = 0 for st in stones: if tuple(st) not in visited: queue =deque([tuple(st)]) while queue: curr = queue.popleft() count += 1 visited.add(curr) for nei in hmapX[curr[0]]: if nei not in visited: queue.append(nei) visited.add(nei) for nei in hmapY[curr[1]]: if nei not in visited: queue.append(nei) visited.add(nei) count -= 1 return count
most-stones-removed-with-same-row-or-column
BFS + hashmap
JackYeh17
2
298
most stones removed with same row or column
947
0.588
Medium
15,377
https://leetcode.com/problems/most-stones-removed-with-same-row-or-column/discuss/2814392/Faster-than-98.5-less-memory-than-86.5
class Solution: def removeStones(self, stones: List[List[int]]) -> int: h=defaultdict(list) v=defaultdict(list) for i, s in enumerate(stones): h[s[0]].append(i) v[s[1]].append(i) l=len(stones) g=[[] for i in range(l)] vlist=[0]*l for i, s in enumerate(stones): g[i]+=[j for j in h[s[0]] if j!=i] g[i]+=[j for j in v[s[1]] if j!=i] ans=l for i in range(l): if not vlist[i]: vlist[i]=1 ans-=1 q=[i] curs=0 while curs<len(q): tmp=q[curs] for j in g[tmp]: if not vlist[j]: vlist[j]=1 q.append(j) curs+=1 return ans
most-stones-removed-with-same-row-or-column
Faster than 98.5%, less memory than 86.5%
mbeceanu
1
94
most stones removed with same row or column
947
0.588
Medium
15,378
https://leetcode.com/problems/most-stones-removed-with-same-row-or-column/discuss/2839263/dictionary-solution
class Solution: def removeStones(self, stones: List[List[int]]) -> int: xdict = {} ydict = {} for x, y in stones: if x not in xdict: xdict[x] = [y] else: xdict[x].append(y) if y not in ydict: ydict[y] = [x] else: ydict[y].append(x) groups = 0 while xdict: ys = set(xdict.popitem()[1]) xs = set() while ys: while ys: y = ys.pop() if y not in ydict: continue for x in ydict.pop(y): xs.add(x) while xs: x = xs.pop() if x not in xdict: continue for y in xdict.pop(x): ys.add(y) groups += 1 return len(stones) - groups
most-stones-removed-with-same-row-or-column
dictionary solution
TrickyUnicorn
0
2
most stones removed with same row or column
947
0.588
Medium
15,379
https://leetcode.com/problems/most-stones-removed-with-same-row-or-column/discuss/2817348/Basic-Union-Find-method-to-solve-the-problem
class Solution: def removeStones(self, stones: List[List[int]]) -> int: p={} def find(m): if m!=p[m]: p[m]=find(p[m]) return p[m] def union(x,y): p.setdefault(x,x) p.setdefault(y,y) r1=find(x) r2=find(y) if r1!=r2: p[r2]=r1 for i,j in stones: union(i,~j) roots=set() for key in p: root=find(key) roots.add(root) return len(stones)-len(roots)
most-stones-removed-with-same-row-or-column
Basic Union Find method to solve the problem
Jai_Trivedi
0
9
most stones removed with same row or column
947
0.588
Medium
15,380
https://leetcode.com/problems/most-stones-removed-with-same-row-or-column/discuss/2816234/Python3-Solution-with-using-dfs
class Solution: def dfs(self, i, stones, visited): visited.add(i) for j in range(len(stones)): if (stones[i][0] == stones[j][0] or stones[i][1] == stones[j][1]) and j not in visited: self.dfs(j, stones, visited) def removeStones(self, stones: List[List[int]]) -> int: visited = set() cnt = 0 for i in range(len(stones)): if i not in visited: self.dfs(i, stones, visited) cnt += 1 return len(stones) - cnt
most-stones-removed-with-same-row-or-column
[Python3] Solution with using dfs
maosipov11
0
11
most stones removed with same row or column
947
0.588
Medium
15,381
https://leetcode.com/problems/most-stones-removed-with-same-row-or-column/discuss/2815389/Python3-pictorial-explanation-with-thought-process-%2B-code
class Solution: def removeStones(self, stones: List[List[int]]) -> int: n = len(stones) freq = defaultdict(int) visited = set() def connect(i,src,label): visited.add(i) freq[label]+=1 for j in range(n): if j not in visited: stone = stones[j] #check if stone is in same row if stone[0]==src[0]: connect(j,stone,label) #check if stone is in same col elif stone[1]==src[1]: connect(j,stone,label) #give lebel number to each component label = 0 for i in range(n): if i not in visited: connect(i,stones[i],label) label+=1 #we can remove all nodes except last node in a chain with more than1 nodes ans = 0 for v in freq.values(): if v>1: ans += v-1 return ans
most-stones-removed-with-same-row-or-column
Python3 pictorial explanation with thought process + code
user9611y
0
4
most stones removed with same row or column
947
0.588
Medium
15,382
https://leetcode.com/problems/most-stones-removed-with-same-row-or-column/discuss/2815331/Python-or-Union-find-or-Approach-explained
class Solution: def removeStones(self, stones: List[List[int]]) -> int: root = [i for i in range(len(stones))] rank = [1] * len(stones) rows = collections.defaultdict(list) cols = collections.defaultdict(list) def unify_stones(): for i in range(len(stones)): r, c = stones[i] for point in rows[r]: union(i, point) for point in cols[c]: union(i, point) rows[r].append(i) cols[c].append(i) for i in range(len(root)): root[i] = find(i) def find(x): if x == root[x]: return x root[x] = find(root[x]) return root[x] def union(x, y): rootX = find(x) rootY = find(y) if rootX != rootY: if rank[rootX] < rank[rootY]: root[rootX] = rootY elif rank[rootY] < rank[rootX]: root[rootY] = rootX else: root[rootY] = rootX rank[rootX] += 1 unify_stones() return len(stones) - len(set(root))
most-stones-removed-with-same-row-or-column
Python | Union find | Approach explained
xyp7x
0
4
most stones removed with same row or column
947
0.588
Medium
15,383
https://leetcode.com/problems/most-stones-removed-with-same-row-or-column/discuss/2815290/Python-Short-DFS-solution-with-graph-%2B-tuple
class Solution: def removeStones(self, stones: List[List[int]]) -> int: graph = collections.defaultdict(list) for i in range(len(stones)): for j in range(i + 1, len(stones)): (x1, y1), (x2, y2) = stones[i], stones[j] if x1 == x2 or y1 == y2: graph[(x1, y1)].append((x2, y2)) graph[(x2, y2)].append((x1, y1)) seen = set() def dfs(start): seen.add(start) for pair in graph[start]: if pair not in seen: dfs(pair) components = 0 for u in graph.keys(): if u not in seen: dfs(u) components += 1 return len(graph) - components
most-stones-removed-with-same-row-or-column
[Python] Short DFS solution with graph + tuple
Nezuko-NoBamboo
0
8
most stones removed with same row or column
947
0.588
Medium
15,384
https://leetcode.com/problems/most-stones-removed-with-same-row-or-column/discuss/2815177/Python-DFS-solution-(connected-graph)
class Solution: def removeStones(self, stones: List[List[int]]) -> int: n = len(stones) adj = defaultdict(set) for i in range(n): r1, c1 = stones[i] for j in range(i+1, n): r2, c2 = stones[j] if r1 == r2 or c1 == c2: adj[i].add(j) adj[j].add(i) seen = set() def dfs(v): if v in seen: return seen.add(v) for e in adj[v]: dfs(e) count = 0 for i in range(n): if i not in seen: dfs(i) count += 1 return n - count
most-stones-removed-with-same-row-or-column
Python DFS solution (connected graph)
zananpech9
0
9
most stones removed with same row or column
947
0.588
Medium
15,385
https://leetcode.com/problems/most-stones-removed-with-same-row-or-column/discuss/2815113/Python3-Easy-oror-BFS-oror-O(n)-oror-Apply-BFS-on-each-components-(explained)
class Solution: def removeStones(self, stones: List[List[int]]) -> int: row_dict = defaultdict(list) col_dict = defaultdict(list) for a,b in stones: row_dict[a].append(b) col_dict[b].append(a) visited = set() ans = 0 que = deque() for a,b in stones: if (a,b) not in visited: #BFS start here for each connected component que.append((a,b)) while que: x,y = que.popleft() if (x,y) in visited: continue visited.add((x,y)) ans+=1 for e in row_dict[x]: #append all points which are in same line as (x,y) if e!=y: que.append((x,e)) for e in col_dict[y]: #append all points which are in same column as (x,y) if e!=x: que.append((e,y)) # here are two line which make code time complexity O(n^2) to O(n) :- # if any point covers its entire row and column points, then again no need to cover these points again. row_dict[x].clear() col_dict[y].clear() # each component can not destroy it self completely , there is only one point always exist , so ans -=1 return ans
most-stones-removed-with-same-row-or-column
🤩 Python3 Easy || BFS || O(n)🔥 || Apply BFS on each components (explained)
Laxman_Singh_Saini
0
10
most stones removed with same row or column
947
0.588
Medium
15,386
https://leetcode.com/problems/most-stones-removed-with-same-row-or-column/discuss/2814912/Union-Approach-Python3
class Solution: def removeStones(self, stones: List[List[int]]) -> int: #Use Unified method, for best practice parents = {} def find(x): if x != parents[x]: parents[x] = find(parents[x]) return parents[x] def union(x,y): parents.setdefault(x,x) parents.setdefault(y,y) r1 = find(x) r2 = find(y) if r1 != r2: parents[r2] = r1 for i,j in stones: union(i,~j) roots = set() for key in parents: root = find(key) roots.add(root) return len(stones) - len(roots)
most-stones-removed-with-same-row-or-column
Union Approach Python3
TheSeer507
0
11
most stones removed with same row or column
947
0.588
Medium
15,387
https://leetcode.com/problems/most-stones-removed-with-same-row-or-column/discuss/2814838/Python-(Faster-than-97)-or-Union-find
class Solution: def removeStones(self, stones: List[List[int]]) -> int: par = {} for r, c in stones: r = -(r + 1) c = c + 1 par[r] = r par[c] = c count = len(par) rank = {} def find(n): if n != par[n]: n = find(par[n]) return n def union(x, y): nonlocal count p1, p2 = find(x), find(y) if p1 == p2: return count -= 1 if rank.get(p1, 1) > rank.get(p2, 1): par[p2] = p1 rank[p1] = rank.get(p1, 1) + 1 else: par[p1] = p2 rank[p2] = rank.get(p2, 1) + 1 for r, c in stones: r = -(r + 1) c = c + 1 union(r, c) return len(stones) - count
most-stones-removed-with-same-row-or-column
Python (Faster than 97%) | Union find
KevinJM17
0
15
most stones removed with same row or column
947
0.588
Medium
15,388
https://leetcode.com/problems/most-stones-removed-with-same-row-or-column/discuss/2814692/Python-Simple-Python-Solution-Using-DFS
class Solution: def removeStones(self, stones: List[List[int]]) -> int: def NextStone(r,c): next_neighbour = [] index = 0 while index < len(stones): row , col = stones[index] if row == r or col == c: next_neighbour.append(stones.pop(index)) else: index = index + 1 for stone in next_neighbour: NextStone(stone[0], stone[1]) result = len(stones) while stones: a,b = stones.pop() NextStone(a,b) result = result - 1 return result
most-stones-removed-with-same-row-or-column
[ Python ] ✅✅ Simple Python Solution Using DFS🥳✌👍
ASHOK_KUMAR_MEGHVANSHI
0
34
most stones removed with same row or column
947
0.588
Medium
15,389
https://leetcode.com/problems/most-stones-removed-with-same-row-or-column/discuss/2814563/Python-solution-with-explanation.
class Solution: def removeStones(self, stones: List[List[int]]) -> int: visited = set() def dfs(cell): if cell in visited: return 0 visited.add(cell) # If stone passes through above code, then it's a part of a new graph # and it's basically the start of a new graph, so we want to mark all it's # neighbours r, c = cell for x, y in stones: if r == x or c == y: dfs(tuple((x, y))) return 1 count = 0 for stone in stones: count += dfs(tuple(stone)) return len(stones) - count
most-stones-removed-with-same-row-or-column
Python solution with explanation.
raghupalash
0
23
most stones removed with same row or column
947
0.588
Medium
15,390
https://leetcode.com/problems/most-stones-removed-with-same-row-or-column/discuss/2814488/Python-BFS-similar-to-rotting-oranges-problem
class Solution: def removeStones(self, A): A = [tuple(x) for x in A] # hashable 2D positions visited = {x: False for x in A} ans = 0 for x in A: if visited[x]: continue q = {x} while q: y = q.pop() # item in same row/column visited[y] = True ans += 1 q.update({z for z in A if not visited[z] and (z[0] == y[0] or z[1] == y[1])}) ans -= 1 # one stone must remain return max(0, ans) ''' 0 1 2 0 X X 1 X X 2 X X 0 1 2 0 X X 1 X 2 X 3 X 0 1 2 0 X X 1 X 2 X row 0 = 2 (1) 1 = 2 (1) 2 = 1 '''
most-stones-removed-with-same-row-or-column
Python BFS, similar to rotting oranges problem
kevv96
0
16
most stones removed with same row or column
947
0.588
Medium
15,391
https://leetcode.com/problems/most-stones-removed-with-same-row-or-column/discuss/2814477/Python3-solution
class Solution: def removeStones(self, stones: List[List[int]]) -> int: rows, cols = defaultdict(list), defaultdict(list) # [1] all stones within the same row for s, (r, c) in enumerate(stones): # and within the same column rows[r].append(s) # belong to the same connected cols[c].append(s) # component; let's store this data seen, n = set(), len(stones) def dfs(s): # [2] this function is used to explore a if s in seen : return 0 # connected component of each stone by seen.add(s) # making recursive calls to adjacent r, c = stones[s] # stones; it returns 1/0 depending on for ss in chain(rows[r], cols[c]): dfs(ss) # whether the component was already return 1 # explored, thus, allowing to count them c = sum(dfs(s) for s in range(n)) # [3] count the number of connected components return n - c
most-stones-removed-with-same-row-or-column
Python3 solution
avs-abhishek123
0
15
most stones removed with same row or column
947
0.588
Medium
15,392
https://leetcode.com/problems/most-stones-removed-with-same-row-or-column/discuss/2814132/Simple-DFS-beats-93
class Solution: def removeStones(self, stones: List[List[int]]) -> int: xs = defaultdict(list) ys = defaultdict(list) for x, y in stones: xs[x].append((x,y)) ys[y].append((x,y)) stones = set((x, y) for x, y in stones) l = len(stones) c = 0 def dfs(p): x, y = p for p1 in xs[x]: if p1 in stones: stones.remove(p1) dfs(p1) for p1 in ys[y]: if p1 in stones: stones.remove(p1) dfs(p1) while stones: c += 1 dfs(stones.pop()) return l-c
most-stones-removed-with-same-row-or-column
Simple DFS beats 93%
Mencibi
0
21
most stones removed with same row or column
947
0.588
Medium
15,393
https://leetcode.com/problems/most-stones-removed-with-same-row-or-column/discuss/2813592/Python3-Commented-DFS-Solution
class Solution: def removeStones(self, stones: List[List[int]]) -> int: # make the trivial case if len(stones) < 2: return 0 # save the indices of the stones rows = collections.defaultdict(list) cols = collections.defaultdict(list) for x,y in stones: rows[y].append(x) cols[x].append(y) # set up the leftover stones leftover = {(x, y) for x, y in stones} # find the number of islands using dfs island = 0 for x, y in stones: if (x, y) in leftover: self.dfs(x, y, leftover, rows, cols) island += 1 return len(stones) - island def dfs(self, x, y, leftover, rows, cols): # throw away the current point as deleted leftover.remove((x,y)) # go through all points on the same row for ry in cols[x]: if (x, ry) in leftover: self.dfs(x, ry, leftover, rows, cols) for rx in rows[y]: if (rx, y) in leftover: self.dfs(rx, y, leftover, rows, cols)
most-stones-removed-with-same-row-or-column
[Python3] - Commented DFS Solution
Lucew
0
19
most stones removed with same row or column
947
0.588
Medium
15,394
https://leetcode.com/problems/most-stones-removed-with-same-row-or-column/discuss/2813282/Python-or-DFS
class Solution: def removeStones(self, stones: List[List[int]]) -> int: visited = {} i = 0 for s in stones: visited[s[0], s[1]] = False for stone in stones: if not visited[stone[0], stone[1]]: self.dfs(stone, visited, stones) i += 1 return len(stones) - i def dfs(self, stone, visited, stones): visited[stone[0], stone[1]] = True for nextStone in stones: if not visited[nextStone[0], nextStone[1]] and (nextStone[0] == stone[0] or nextStone[1] == stone[1]): self.dfs(nextStone, visited, stones)
most-stones-removed-with-same-row-or-column
Python | DFS
rahul_mishra_
0
22
most stones removed with same row or column
947
0.588
Medium
15,395
https://leetcode.com/problems/most-stones-removed-with-same-row-or-column/discuss/2812984/python3-Union-find-solution-for-reference
class Solution: def removeStones(self, stones: List[List[int]]) -> int: S = len(stones) parents = defaultdict(lambda: -1) b = [] ans = 0 def find(x): if parents[x] != -1: parents[x] = find(parents[x]) return parents[x] return x def union(a,b): ps = find(a) pe = find(b) if ps != pe: if ps > pe: ps, pe = pe, ps parents[pe] = ps for i in range(S): for j in range(i+1, S): if stones[i][0] == stones[j][0] or stones[i][1] == stones[j][1]: union(i,j) for k in parents.keys(): b.append(find(k)) for k,v in Counter(b).items(): ans += v-1 return ans
most-stones-removed-with-same-row-or-column
[python3] Union find solution for reference
vadhri_venkat
0
16
most stones removed with same row or column
947
0.588
Medium
15,396
https://leetcode.com/problems/most-stones-removed-with-same-row-or-column/discuss/2812977/Most-stones-removed-with-same-row-or-column-position-solution-in-Python
class Solution: def removeStones(self, stones: List[List[int]]) -> int: def dfs(idx): seen.add(idx) for nidx in adj[idx]: if nidx not in seen: dfs(nidx) adj = defaultdict(set) for i in range(len(stones)): x1, y1 = stones[i][0], stones[i][1] for j in range(i+1, len(stones)): x2, y2 = stones[j][0], stones[j][1] if x1 == x2 or y1 == y2: adj[i].add(j) adj[j].add(i) seen = set() valid_stones = 0 for i in range(len(stones)-1, -1,-1): if i not in seen: dfs(i) valid_stones += 1 return len(stones) - valid_stones
most-stones-removed-with-same-row-or-column
Most stones removed with same row or column position solution in Python
prashantghi8
0
26
most stones removed with same row or column
947
0.588
Medium
15,397
https://leetcode.com/problems/most-stones-removed-with-same-row-or-column/discuss/2812960/Python3-Treat-like-connected-graph
class Solution: def removeStones(self, stones: List[List[int]]) -> int: d1, d2 = defaultdict(lambda: set()), {} for [R, C] in stones: r, c = R + 1, C + 1 k = (r << 14) + c d1[-r].add(k) d1[c].add(k) d2[k] = [-r, c] rc = len(stones) def rec(s): nonlocal rc if s not in d2: return [r,c] = d2[s] del d2[s] s1 = d1[r] s2 = d1[c] s1.remove(s) s2.remove(s) for i in list(s1) + list(s2): rec(i) for stone in list(d2.keys()): if stone in d2: rc -= 1 rec(stone) return rc
most-stones-removed-with-same-row-or-column
Python3 - Treat like connected graph
godshiva
0
9
most stones removed with same row or column
947
0.588
Medium
15,398
https://leetcode.com/problems/most-stones-removed-with-same-row-or-column/discuss/2812856/Python3-oror-Hashmap-DFS
class Solution: def removeStones(self, stones: List[List[int]]) -> int: self.vis = set() dtr, dtc = defaultdict(lambda: []), defaultdict(lambda: []) for stone in stones: dtr[stone[0]].append(stone[1]) dtc[stone[1]].append(stone[0]) self.res = 0 def dfs(point): for c in dtr[point[0]]: if ((point[0], c)) not in self.vis: self.vis.add((point[0], c)) self.res += 1 dfs((point[0], c)) for r in dtc[point[1]]: if (r, point[1]) not in self.vis: self.vis.add((r, point[1])) self.res += 1 dfs((r, point[1])) for r, c in stones: if (r, c) not in self.vis: self.vis.add((r, c)) dfs((r, c)) return self.res
most-stones-removed-with-same-row-or-column
Python3 || Hashmap DFS
rupamkarmakarcr7
0
15
most stones removed with same row or column
947
0.588
Medium
15,399