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/divide-array-into-equal-pairs/discuss/2054417/One-line-very-fast-solution-Python3-beats-99
class Solution: def divideArray(self, nums: List[int]) -> bool: a = [False for i in Counter(nums).values() if i % 2 != 0] return all(a)
divide-array-into-equal-pairs
One line, very fast solution Python3 beats 99%
Encelad
0
36
divide array into equal pairs
2,206
0.746
Easy
30,600
https://leetcode.com/problems/divide-array-into-equal-pairs/discuss/2036061/Python-simple-solution
class Solution: def divideArray(self, n: List[int]) -> bool: n = sorted(n,reverse=True) for i in range(0,len(n)//2+1,2): if n[i] != n[i+1]: return False return True
divide-array-into-equal-pairs
Python simple solution
StikS32
0
48
divide array into equal pairs
2,206
0.746
Easy
30,601
https://leetcode.com/problems/divide-array-into-equal-pairs/discuss/1995151/Beginner-Simple-O(n2)-Solution
class Solution: def divideArray(self, nums: List[int]) -> bool: nums.sort() size = len(nums) // 2 count = 0 for i in range(0,len(nums),2): for j in range(len(nums)): if i == j-1: if nums[i] == nums[j]: count += 1 if count == size: return True else: return False
divide-array-into-equal-pairs
Beginner Simple O(n^2) Solution
itsmeparag14
0
31
divide array into equal pairs
2,206
0.746
Easy
30,602
https://leetcode.com/problems/divide-array-into-equal-pairs/discuss/1954653/python-Beginner-friendly-hashmap
class Solution: def divideArray(self, nums: List[int]) -> bool: dict={} for i in nums: dict[i]=dict.get(i,0)+1 for i in dict: if dict[i]%2!=0: return False return True
divide-array-into-equal-pairs
python, Beginner friendly, hashmap
Aniket_liar07
0
52
divide array into equal pairs
2,206
0.746
Easy
30,603
https://leetcode.com/problems/divide-array-into-equal-pairs/discuss/1944140/Python-dollarolution-(Simple-2-line-Solution)
class Solution: def divideArray(self, nums: List[int]) -> bool: d = Counter(nums) return all(value%2 == 0 for value in d.values())
divide-array-into-equal-pairs
Python $olution (Simple 2 line Solution)
AakRay
0
37
divide array into equal pairs
2,206
0.746
Easy
30,604
https://leetcode.com/problems/divide-array-into-equal-pairs/discuss/1926076/Python3-simple-solution-using-dictionary
class Solution: def divideArray(self, nums: List[int]) -> bool: d = {} for i in nums: x = str(i) d[x] = d.get(x,0) + 1 for i in d.values(): if i % 2 != 0: return False return True
divide-array-into-equal-pairs
Python3 simple solution using dictionary
EklavyaJoshi
0
39
divide array into equal pairs
2,206
0.746
Easy
30,605
https://leetcode.com/problems/divide-array-into-equal-pairs/discuss/1924338/Python-or-One-Liner-or-Counter
class Solution: def divideArray(self, nums): return all(v % 2 == 0 for v in Counter(nums).values())
divide-array-into-equal-pairs
Python | One-Liner | Counter
domthedeveloper
0
43
divide array into equal pairs
2,206
0.746
Easy
30,606
https://leetcode.com/problems/divide-array-into-equal-pairs/discuss/1921594/Python-Solution
class Solution: def divideArray(self, nums: List[int]) -> bool: dic = {} for i in nums: if i not in dic: dic[i] = 1 else: dic[i] += 1 for i in dic.keys(): if dic[i] % 2 != 0: return False return True
divide-array-into-equal-pairs
Python Solution
MS1301
0
49
divide array into equal pairs
2,206
0.746
Easy
30,607
https://leetcode.com/problems/divide-array-into-equal-pairs/discuss/1917520/Python3-solution-99-faster
class Solution: def divideArray(self, nums: List[int]) -> bool: n = len(nums)/2 hist = {} for i in range(len(nums)): if nums[i] in hist.keys(): hist[nums[i]]+=1 else: hist[nums[i]]=1 for val in hist.values(): if val%2: return False return True
divide-array-into-equal-pairs
Python3 solution 99% faster
Hitanshee
0
42
divide array into equal pairs
2,206
0.746
Easy
30,608
https://leetcode.com/problems/divide-array-into-equal-pairs/discuss/1910040/Python-O(N)-Simple-Solution
class Solution: def divideArray(self, nums: List[int]) -> bool: from collections import defaultdict nums_count=defaultdict(lambda : 0) for i in nums: nums_count[i]+=1 for key in nums_count: if nums_count[key]%2!=0: return False return True
divide-array-into-equal-pairs
Python O(N) Simple Solution
samuelstephen
0
43
divide array into equal pairs
2,206
0.746
Easy
30,609
https://leetcode.com/problems/divide-array-into-equal-pairs/discuss/1904250/Python3-Faster-Than-91-Memory-Less-Than-91.03
class Solution: def divideArray(self, nums: List[int]) -> bool: m = {} for i in nums: if i in m: m[i] += 1 else: m[i] = 1 for i in m: if m[i] % 2 != 0: return False return True
divide-array-into-equal-pairs
Python3 Faster Than 91%, Memory Less Than 91.03%
Hejita
0
34
divide array into equal pairs
2,206
0.746
Easy
30,610
https://leetcode.com/problems/divide-array-into-equal-pairs/discuss/1901895/Python-3-Dictionary-approach.-99-faster
class Solution: def divideArray(self, nums: List[int]) -> bool: dict1= {} for i in nums: if i not in dict1: dict1[i] = 1 else: dict1[i]+= 1 counter = 0 for keys, values in dict1.items(): if values % 2 != 0: counter += 1 if counter != 0: return False else: return True
divide-array-into-equal-pairs
Python 3 Dictionary approach. 99% faster
sjshah
0
27
divide array into equal pairs
2,206
0.746
Easy
30,611
https://leetcode.com/problems/divide-array-into-equal-pairs/discuss/1899734/Python3-Checking-Hash-Table-or-faster-than-91-or-less-than-90
class Solution: def divideArray(self, nums: List[int]) -> bool: dict_ = {} for n in nums: if n not in dict_: dict_[n] = 1 else: dict_[n] += 1 for k in dict_: if dict_[k] % 2 != 0: return False else: return True
divide-array-into-equal-pairs
✔Python3 Checking Hash Table | faster than 91% | less than 90%
khRay13
0
36
divide array into equal pairs
2,206
0.746
Easy
30,612
https://leetcode.com/problems/divide-array-into-equal-pairs/discuss/1884224/Python-easy-solution-using-count
class Solution: def divideArray(self, nums: List[int]) -> bool: for i in set(nums): if nums.count(i) % 2 != 0: return False return True
divide-array-into-equal-pairs
Python easy solution using count
alishak1999
0
47
divide array into equal pairs
2,206
0.746
Easy
30,613
https://leetcode.com/problems/divide-array-into-equal-pairs/discuss/1878558/Python-(Simple-Approach-and-Beginner-Friendly)
class Solution: def divideArray(self, nums: List[int]) -> bool: dict = Counter(nums) for n in dict.values(): if n % 2 != 0: return False return True
divide-array-into-equal-pairs
Python (Simple Approach and Beginner-Friendly)
vishvavariya
0
28
divide array into equal pairs
2,206
0.746
Easy
30,614
https://leetcode.com/problems/divide-array-into-equal-pairs/discuss/1878128/python-3-oror-one-line-oror-O(n)-O(n)
class Solution: def divideArray(self, nums: List[int]) -> bool: return all(count % 2 == 0 for count in collections.Counter(nums).values())
divide-array-into-equal-pairs
python 3 || one line || O(n) / O(n)
dereky4
0
29
divide array into equal pairs
2,206
0.746
Easy
30,615
https://leetcode.com/problems/divide-array-into-equal-pairs/discuss/1874858/Python3-1-line
class Solution: def divideArray(self, nums: List[int]) -> bool: return all(x & 1 == 0 for x in Counter(nums).values())
divide-array-into-equal-pairs
[Python3] 1-line
ye15
0
24
divide array into equal pairs
2,206
0.746
Easy
30,616
https://leetcode.com/problems/divide-array-into-equal-pairs/discuss/1873597/python-easy-solution
class Solution: def divideArray(self, nums: List[int]) -> bool: count = defaultdict(int) for num in nums: count[num] += 1 for v in count.values(): if v % 2 != 0: return False return True
divide-array-into-equal-pairs
python easy solution
byuns9334
0
47
divide array into equal pairs
2,206
0.746
Easy
30,617
https://leetcode.com/problems/divide-array-into-equal-pairs/discuss/1868413/Python3-O(n)-time-O(n)-space
class Solution: def divideArray(self, nums: List[int]) -> bool: numCounter = defaultdict(int) for num in nums: numCounter[num] += 1 for num in numCounter: if numCounter[num] % 2 != 0: return False return True
divide-array-into-equal-pairs
Python3 O(n) time O(n) space
peterhwang
0
28
divide array into equal pairs
2,206
0.746
Easy
30,618
https://leetcode.com/problems/divide-array-into-equal-pairs/discuss/1866913/Python-or-1-line-or-Counter
class Solution: def divideArray(self, nums: List[int]) -> bool: return all(x % 2 == 0 for x in Counter(nums).values())
divide-array-into-equal-pairs
Python | 1 line | Counter
leeteatsleep
0
28
divide array into equal pairs
2,206
0.746
Easy
30,619
https://leetcode.com/problems/divide-array-into-equal-pairs/discuss/1864527/Python-solution
class Solution: def divideArray(self, nums: List[int]) -> bool: n=len(nums)//2 from collections import Counter count=Counter(nums) for i in count: if count[i]%2!=0: return False return True
divide-array-into-equal-pairs
Python solution
g0urav
0
28
divide array into equal pairs
2,206
0.746
Easy
30,620
https://leetcode.com/problems/divide-array-into-equal-pairs/discuss/1864272/Python-O(n)-readable-solution.
class Solution: def divideArray(self, nums: List[int]) -> bool: #counting appearances count = collections.Counter(nums) #if a number has an odd frequency, it can't be split as the constraints require, so we can just return false for k, v in count.items(): if v % 2: return False return True
divide-array-into-equal-pairs
Python O(n) readable solution.
cheeto1
0
55
divide array into equal pairs
2,206
0.746
Easy
30,621
https://leetcode.com/problems/divide-array-into-equal-pairs/discuss/1864154/Python-xor-one-liner-O(N)O(log(N))
class Solution: def divideArray(self, nums: List[int]) -> bool: return reduce(lambda t, n : t ^ 1 << n, nums, 0) == 0
divide-array-into-equal-pairs
Python, xor one-liner, O(N)/O(log(N))
blue_sky5
0
43
divide array into equal pairs
2,206
0.746
Easy
30,622
https://leetcode.com/problems/divide-array-into-equal-pairs/discuss/1864101/Python3-O(N)-One-liner
class Solution: def divideArray(self, nums: List[int]) -> bool: return not any(v % 2 for v in Counter(nums).values())
divide-array-into-equal-pairs
[Python3] O(N) - One-liner
dwschrute
0
16
divide array into equal pairs
2,206
0.746
Easy
30,623
https://leetcode.com/problems/maximize-number-of-subsequences-in-a-string/discuss/2501496/Python-Easy-Solution
class Solution: def maximumSubsequenceCount(self, string: str, pattern: str) -> int: text = pattern[0]+string text1 = string + pattern[1] cnt,cnt1 = 0,0 ans,ans1 = 0,0 for i in range(len(text)): if text[i] == pattern[0]: cnt+=1 elif text[i] == pattern[1]: ans+= cnt if pattern[0] == pattern[1]: ans = ((cnt)*(cnt-1))//2 # appending at the last for i in range(len(text1)): if text1[i] == pattern[0]: cnt1+=1 elif text1[i] == pattern[1]: ans1+= cnt1 if pattern[0] == pattern[1]: ans1 = ((cnt1)*(cnt1-1))//2 return max(ans1,ans)
maximize-number-of-subsequences-in-a-string
Python Easy Solution
Abhi_009
0
26
maximize number of subsequences in a string
2,207
0.328
Medium
30,624
https://leetcode.com/problems/maximize-number-of-subsequences-in-a-string/discuss/2310586/Brute-Force-Clean-to-see-and-elegant-code.-Python3-52-faster
class Solution: def maximumSubsequenceCount(self, text: str, pattern: str) -> int: # Logic: # I am sure if I filter letters of pattern, I can accomplish my task. # I am sure if I append the first letter of the pattern in the filtered string, # at the beginning and the second letter of the pattern at the end, I can get the maximum # number subsequences which is the pattern. # I need to count the occurrance of pattern[0] and pattern[1] #After I filtered, The only letters in string are pattern[0] and pattern[1] #let_ONE=0 #The maximum number of subsequence up to the current index #let_TWO=0 # The second letter counter==pattern[1] filtered=[] for let in text: if let in pattern: filtered.append(let) return max(self.maxFinder(False,filtered,pattern), self.maxFinder(True,filtered,pattern)) def maxFinder(self,atTheBeginning,string,pattern): let_ONE=0 let_TWO=0 if not atTheBeginning: let_TWO=1 for index in range(len(string)-1,-1,-1): if string[index]==pattern[0]: let_ONE+=let_TWO if string[index]==pattern[1]: let_TWO+=1 if atTheBeginning: let_ONE+=let_TWO return let_ONE
maximize-number-of-subsequences-in-a-string
Brute Force, Clean to see and elegant code. Python3 52% faster
Sefinehtesfa34
0
10
maximize number of subsequences in a string
2,207
0.328
Medium
30,625
https://leetcode.com/problems/maximize-number-of-subsequences-in-a-string/discuss/2028636/python-java-DP-solution-(Time-On-space-O1)
class Solution: def maximumSubsequenceCount(self, text: str, pattern: str) -> int: if pattern[0] == pattern[1]: letter = 1 for i in range (len(text)) : if text[i] == pattern[0] : letter += 1 return letter*(letter-1)//2 else : letter = 1 ans1 = 0 for i in range (len(text)) : if text[i] == pattern[0] : letter += 1 elif text[i] == pattern[1] : ans1 += letter letter = 1 ans2 = 0 for i in range (len(text)-1, -1, -1) : if text[i] == pattern[1] : letter += 1 elif text[i] == pattern[0] : ans2 += letter return max(ans1, ans2)
maximize-number-of-subsequences-in-a-string
python, java - DP solution (Time On, space O1)
ZX007java
0
69
maximize number of subsequences in a string
2,207
0.328
Medium
30,626
https://leetcode.com/problems/maximize-number-of-subsequences-in-a-string/discuss/1874866/Python3-count
class Solution: def maximumSubsequenceCount(self, text: str, pattern: str) -> int: ans = cnt0 = cnt1 = 0 for ch in text: if ch == pattern[1]: ans += cnt0 cnt1 += 1 if ch == pattern[0]: cnt0 += 1 return ans + max(cnt0, cnt1)
maximize-number-of-subsequences-in-a-string
[Python3] count
ye15
0
15
maximize number of subsequences in a string
2,207
0.328
Medium
30,627
https://leetcode.com/problems/maximize-number-of-subsequences-in-a-string/discuss/1865770/Solution-in-Python-O(N)
class Solution: def maximumSubsequenceCount(self, text: str, pattern: str) -> int: first=0 second=0 answer=0 for i in text: if i==pattern[0]: first+=1 if i==pattern[1]: second+=1 if pattern[0]!=pattern[1]: answer+=first else: answer+=(first-1) return max(answer+second,answer+first)
maximize-number-of-subsequences-in-a-string
Solution in Python O(N)
g0urav
0
11
maximize number of subsequences in a string
2,207
0.328
Medium
30,628
https://leetcode.com/problems/maximize-number-of-subsequences-in-a-string/discuss/1864116/Python3-O(N)-with-Counter-(explained)
class Solution: def maximumSubsequenceCount(self, text: str, pattern: str) -> int: a, b = pattern[0], pattern[1] counter = Counter(text) def num_subseq(): rc = Counter(text) # counter for text[i:] ans = 0 for c in text: rc[c] -= 1 if c == a: ans += rc[b] return ans return num_subseq() + max(counter[a], counter[b])
maximize-number-of-subsequences-in-a-string
[Python3] O(N) with Counter (explained)
dwschrute
0
12
maximize number of subsequences in a string
2,207
0.328
Medium
30,629
https://leetcode.com/problems/minimum-operations-to-halve-array-sum/discuss/1984994/python-3-oror-priority-queue
class Solution: def halveArray(self, nums: List[int]) -> int: s = sum(nums) goal = s / 2 res = 0 for i, num in enumerate(nums): nums[i] = -num heapq.heapify(nums) while s > goal: halfLargest = -heapq.heappop(nums) / 2 s -= halfLargest heapq.heappush(nums, -halfLargest) res += 1 return res
minimum-operations-to-halve-array-sum
python 3 || priority queue
dereky4
2
79
minimum operations to halve array sum
2,208
0.452
Medium
30,630
https://leetcode.com/problems/minimum-operations-to-halve-array-sum/discuss/1865234/Python3-HEAP-()-Explained
class Solution: def halveArray(self, nums: List[int]) -> int: s = sum(nums) nums = [-i for i in nums] heapify(nums) total, halve, res = s, s/2, 0 while total > halve: total += nums[0]/2 heapreplace(nums, nums[0]/2) res += 1 return res
minimum-operations-to-halve-array-sum
✔️ [Python3] HEAP (🌸◠‿◠), Explained
artod
1
110
minimum operations to halve array sum
2,208
0.452
Medium
30,631
https://leetcode.com/problems/minimum-operations-to-halve-array-sum/discuss/2779878/python-max-heap
class Solution: def halveArray(self, nums: List[int]) -> int: res, max_heap, total, curr_total = 0, [], sum(nums), sum(nums) for n in nums: heappush(max_heap, -n) while max_heap: n = -heappop(max_heap) res += 1 curr_total -= n / 2 if curr_total <= total / 2: break heappush(max_heap, -n / 2) return res
minimum-operations-to-halve-array-sum
python max heap
JasonDecode
0
2
minimum operations to halve array sum
2,208
0.452
Medium
30,632
https://leetcode.com/problems/minimum-operations-to-halve-array-sum/discuss/2230609/Simple-Python-3-Solution-with-HeapQ
class Solution: def halveArray(self, nums: List[int]) -> int: """ List of positive ints. Reduce the sum of nums to at least half by halving selected nums. Find the minimum count of these halving needed. Cannot reduce more in one step than halving the biggest number. After each halving the biggest number changes. Need to keep sort and quick removal and insert. This sounds like heap is optimal here. # Computational (Time) Complexity Complexity cannot be faster than N. Because I need a sum at the beginning. If iterated sorting of complexity N * Log N is used, then total complexity is N**2 Log N. If heap is used, then complexity of insert is C or worst Log N, so total complexity is N Log N. # Memory (Space) Complexity Memory space needed is constant. """ original_sum = sum(nums) nums = [float(-n) for n in nums] heapq.heapify(nums) if len(nums) == 0: return 0 current_sum = original_sum n_operations = 0 while current_sum * 2 > original_sum: neg_biggest = heapq.heappop(nums) current_sum -= -neg_biggest /2 heapq.heappush(nums, neg_biggest / 2) n_operations += 1 return n_operations
minimum-operations-to-halve-array-sum
Simple Python 3 Solution with HeapQ
vaclavkosar
0
39
minimum operations to halve array sum
2,208
0.452
Medium
30,633
https://leetcode.com/problems/minimum-operations-to-halve-array-sum/discuss/1874873/Python3-priority-queue
class Solution: def halveArray(self, nums: List[int]) -> int: pq = [-x for x in nums] heapify(pq) sm = ss = sum(nums) ans = 0 while sm > ss/2: ans += 1 x = heappop(pq) sm -= -x/2 heappush(pq, x/2) return ans
minimum-operations-to-halve-array-sum
[Python3] priority queue
ye15
0
16
minimum operations to halve array sum
2,208
0.452
Medium
30,634
https://leetcode.com/problems/minimum-operations-to-halve-array-sum/discuss/1866024/Python-solution
class Solution: def halveArray(self, nums: List[int]) -> int: answer=0 sum1=sum(nums) sum2=sum1 final=0 import heapq for i in range(len(nums)): nums[i]=-1*nums[i] heapq.heapify(nums) while True: p=heapq.heappop(nums) p=-1*p sum2-=(p/2) answer+=1 if (sum1-sum2)>=(sum1/2): return answer heapq.heappush(nums,-(p/2))
minimum-operations-to-halve-array-sum
Python solution
g0urav
0
16
minimum operations to halve array sum
2,208
0.452
Medium
30,635
https://leetcode.com/problems/minimum-operations-to-halve-array-sum/discuss/1864231/Python-Heapq
class Solution: def halveArray(self, nums: List[int]) -> int: import heapq target = sum(nums) / 2 arr = [-i for i in nums] heapq.heapify(arr) res = 0 while target > 0: # everything will be negative over here, so we will add the halved value n = heapq.heappop(arr) / 2 target += n res += 1 heapq.heappush(arr,n) return res
minimum-operations-to-halve-array-sum
Python Heapq
codingteam225
0
27
minimum operations to halve array sum
2,208
0.452
Medium
30,636
https://leetcode.com/problems/minimum-white-tiles-after-covering-with-carpets/discuss/1874969/Python3-dp
class Solution: def minimumWhiteTiles(self, floor: str, numCarpets: int, carpetLen: int) -> int: @cache def fn(i, n): """Return min while tiles at k with n carpets left.""" if n < 0: return inf if i >= len(floor): return 0 if floor[i] == '1': return min(fn(i+carpetLen, n-1), 1 + fn(i+1, n)) return fn(i+1, n) return fn(0, numCarpets)
minimum-white-tiles-after-covering-with-carpets
[Python3] dp
ye15
2
51
minimum white tiles after covering with carpets
2,209
0.338
Hard
30,637
https://leetcode.com/problems/minimum-white-tiles-after-covering-with-carpets/discuss/1874969/Python3-dp
class Solution: def minimumWhiteTiles(self, floor: str, numCarpets: int, carpetLen: int) -> int: dp = [[0]*(1 + numCarpets) for _ in range(len(floor)+1)] for i in range(len(floor)-1, -1, -1): for j in range(0, numCarpets+1): if floor[i] == '1': dp[i][j] = 1 + dp[i+1][j] if j: if i+carpetLen >= len(floor): dp[i][j] = 0 else: dp[i][j] = min(dp[i+carpetLen][j-1], dp[i][j]) else: dp[i][j] = dp[i+1][j] return dp[0][numCarpets]
minimum-white-tiles-after-covering-with-carpets
[Python3] dp
ye15
2
51
minimum white tiles after covering with carpets
2,209
0.338
Hard
30,638
https://leetcode.com/problems/minimum-white-tiles-after-covering-with-carpets/discuss/1865059/DP-%2B-edge-case-optimization-with-explanations
class Solution: def minimumWhiteTiles(self, floor: str, numCarpets: int, carpetLen: int) -> int: n = len(floor) # edge case handling if numCarpets * carpetLen >= n: return 0 if carpetLen == 1: return max(sum([int(c) for c in floor]) - numCarpets, 0) # DP initialization dp = [[None] * (numCarpets + 1) for _ in range(n + 1)] for j in range(numCarpets + 1): dp[0][j] = 0 for i in range(1, n + 1): dp[i][0] = dp[i - 1][0] + int(floor[i - 1]) # DP transition formula for i in range(1, n + 1): for j in range(1, numCarpets + 1): dp[i][j] = min(dp[i - 1][j] + int(floor[i - 1]), dp[max(i - carpetLen, 0)][j - 1]) return dp[n][numCarpets]
minimum-white-tiles-after-covering-with-carpets
DP + edge case optimization with explanations
xil899
1
37
minimum white tiles after covering with carpets
2,209
0.338
Hard
30,639
https://leetcode.com/problems/minimum-white-tiles-after-covering-with-carpets/discuss/1870132/DP-solution
class Solution: def minimumWhiteTiles(self, floor: str, numCarpets: int, carpetLen: int) -> int: dp=[[0 for i in range(numCarpets+1)] for j in range(len(floor)+1)] for i in range(1,len(floor)+1): if floor[i-1]=='1': dp[i][0]=dp[i-1][0]+1 else: dp[i][0]=dp[i-1][0] for j in range(1,numCarpets+1): for i in range(1,len(floor)+1): dp[i][j]=min(dp[max(0,i-carpetLen)][j-1],dp[i-1][j]+(floor[i-1]=='1')) return dp[-1][numCarpets]
minimum-white-tiles-after-covering-with-carpets
DP solution
g0urav
0
23
minimum white tiles after covering with carpets
2,209
0.338
Hard
30,640
https://leetcode.com/problems/minimum-white-tiles-after-covering-with-carpets/discuss/1867834/Python-DP-Solution-Optimized
class Solution: def minimumWhiteTiles(self, floor: str, numCarpets: int, carpetLen: int) -> int: # number of white tiles up in the first i tiles c_sums=[] cur=0 for x in floor: cur+=int(x) c_sums.append(cur) if carpetLen == 1: return max(0,c_sums[-1]-numCarpets) # the minimum number of white tiles still visible when using k tiles to cover the first i tiles @cache def dp(i,k): # no tiles left if k <= 0: return c_sums[i-1] # cover all white tiles if i <= k*carpetLen: return 0 # everytile is white if i == c_sums[i-1]: return i-k*carpetLen # either not cover the ith(last) tile or cover it return min(dp(i-1,k) + int(floor[i-1]), dp(i-carpetLen,k-1)) return dp(len(floor),numCarpets)
minimum-white-tiles-after-covering-with-carpets
[Python] DP Solution Optimized
haydarevren
0
17
minimum white tiles after covering with carpets
2,209
0.338
Hard
30,641
https://leetcode.com/problems/minimum-white-tiles-after-covering-with-carpets/discuss/1867834/Python-DP-Solution-Optimized
class Solution: def minimumWhiteTiles(self, floor: str, numCarpets: int, carpetLen: int) -> int: @cache def dp(i,k): if i<=k*carpetLen: return 0 return min(dp(i-1,k) + int(floor[i-1]), dp(i-carpetLen,k-1) if k>0 else float("inf")) return dp(len(floor),numCarpets)
minimum-white-tiles-after-covering-with-carpets
[Python] DP Solution Optimized
haydarevren
0
17
minimum white tiles after covering with carpets
2,209
0.338
Hard
30,642
https://leetcode.com/problems/minimum-white-tiles-after-covering-with-carpets/discuss/1864301/Python-3-Binary-search-%2B-DP-with-comments
class Solution: def minimumWhiteTiles(self, floor: str, numCarpets: int, carpetLen: int) -> int: # get all locations for white loc = [i for i in range(len(floor)) if floor[i] == '1'] if not loc: return 0 @lru_cache(None) # calculate maximum white tiles covered def dp(i, numCarpets): # if no carpets or reached the end of loc if numCarpets == 0 or i >= len(loc): return 0 # if remaining caprets could cover till the end of loc if loc[i] + numCarpets * carpetLen - 1 >= loc[-1]: return len(loc) - i ans = -float('inf') # maximum carpets required to reach the next loc required = math.ceil((loc[i+1] - loc[i]) / carpetLen) for k in range(min(required, numCarpets)+1): new_i = bisect.bisect(loc, loc[i] + k*carpetLen - 1) ans = max(ans, new_i - i + dp(max(i+1, new_i), numCarpets - k)) return ans return len(loc) - dp(0, numCarpets)
minimum-white-tiles-after-covering-with-carpets
[Python 3] Binary search + DP with comments
chestnut890123
0
30
minimum white tiles after covering with carpets
2,209
0.338
Hard
30,643
https://leetcode.com/problems/count-hills-and-valleys-in-an-array/discuss/1866869/Python3-One-pass-oror-O(1)-space
class Solution: def countHillValley(self, nums: List[int]) -> int: #cnt: An integer to store total hills and valleys #left: Highest point of hill or lowest point of valley left of the current index cnt, left = 0, nums[0] for i in range(1, len(nums)-1): if (left<nums[i] and nums[i]>nums[i+1]) or (left>nums[i] and nums[i]<nums[i+1]): cnt+=1 left=nums[i] return cnt
count-hills-and-valleys-in-an-array
[Python3] One pass || O(1) space
__PiYush__
3
82
count hills and valleys in an array
2,210
0.581
Easy
30,644
https://leetcode.com/problems/count-hills-and-valleys-in-an-array/discuss/2658124/Python-Solution-or-Easy-to-understand
class Solution: def countHillValley(self, nums: List[int]) -> int: def remove_adjacent(nums): #removing adjacent duplicates as they neither add to a hill or valley i = 1 while i < len(nums): if nums[i] == nums[i-1]: nums.pop(i) i -= 1 i += 1 return nums nums=remove_adjacent(nums) count=0 for i in range(1,len(nums)-1): if (nums[i-1]<=nums[i] and nums[i]>nums[i+1]) or (nums[i-1]>nums[i] and nums[i]<=nums[i+1]): count+=1 return count
count-hills-and-valleys-in-an-array
Python Solution | Easy to understand
prakashpcssinha
0
6
count hills and valleys in an array
2,210
0.581
Easy
30,645
https://leetcode.com/problems/count-hills-and-valleys-in-an-array/discuss/2430016/python
class Solution: def countHillValley(self, nums: List[int]) -> int: ans = 0 i = 1 prev = nums[0] flag = False while i < len(nums) - 1: if (nums[i] > prev and nums[i] > nums[i + 1]) or(nums[i] < prev and nums[i] < nums[i + 1]): ans += 1 prev = nums[i] print(nums[i]) elif nums[i] != nums[i+1]: prev = nums[i] i += 1 return ans
count-hills-and-valleys-in-an-array
python
akashp2001
0
71
count hills and valleys in an array
2,210
0.581
Easy
30,646
https://leetcode.com/problems/count-hills-and-valleys-in-an-array/discuss/2384941/Python3-Easy-if-else-solution-Faster-than-97
class Solution: def countHillValley(self, nums: List[int]) -> int: n=0 i=0 l=len(nums) new=0 # to keep track of whether nums[i] is part of nums[0] prev=-1 while i <l-1: if i ==0: pass elif nums[i-1]<nums[i]>nums[i+1]: n+=1 elif nums[i-1]>nums[i]<nums[i+1]: n+=1 elif new==1 and (prev<nums[i-1]==nums[i]>nums[i+1]): n+=1 elif new==1 and (prev>nums[i-1]==nums[i]<nums[i+1]): n+=1 if nums[i]!=nums[0]: #change new flag when the first time nums[i] is different from nums[0] new=1 if nums[i]!=nums[i+1]: prev = nums[i] #track previous different number i+=1 return n
count-hills-and-valleys-in-an-array
[Python3] Easy if else solution -Faster than 97%
sunakshi132
0
66
count hills and valleys in an array
2,210
0.581
Easy
30,647
https://leetcode.com/problems/count-hills-and-valleys-in-an-array/discuss/2234225/Easy-Understanding-or-Python-Single-Pass-or-TC%3A-O(n)-or-SC%3A-O(1)
class Solution: def countHillValley(self, nums: List[int]) -> int: HillValleyCount = 0 for i in range(1, len(nums)-1): if nums[i] == nums[i+1]: nums[i] = nums[i-1] elif nums[i] > nums[i-1] and nums[i] > nums[i+1]: HillValleyCount += 1 elif nums[i] < nums[i-1] and nums[i] < nums[i+1]: HillValleyCount += 1 return HillValleyCount
count-hills-and-valleys-in-an-array
Easy Understanding | Python Single Pass | TC: O(n) | SC: O(1)
Jayesh_Suryavanshi
0
74
count hills and valleys in an array
2,210
0.581
Easy
30,648
https://leetcode.com/problems/count-hills-and-valleys-in-an-array/discuss/2190155/Python-Solution-reduce
class Solution: def countHillValley(self, nums: List[int]) -> int: arr = reduce(lambda x, i: x + [nums[i]] if x[-1] != nums[i] else x, range(1, len(nums)), [nums[0]]) return reduce(lambda x, i: x + (arr[i] > arr[i - 1] and arr[i] > arr[i + 1] or arr[i] < arr[i - 1] and arr[i] < arr[i + 1]), range(1, len(arr) - 1), 0)
count-hills-and-valleys-in-an-array
Python Solution reduce
hgalytoby
0
52
count hills and valleys in an array
2,210
0.581
Easy
30,649
https://leetcode.com/problems/count-hills-and-valleys-in-an-array/discuss/2190155/Python-Solution-reduce
class Solution: def countHillValley(self, nums: List[int]) -> int: arr = [nums[0]] for i in range(1, len(nums)): if arr[-1] != nums[i]: arr.append(nums[i]) result = 0 for i in range(1, len(arr) - 1): if arr[i] > arr[i - 1] and arr[i] > arr[i + 1] or arr[i] < arr[i - 1] and arr[i] < arr[i + 1]: result += 1 return result
count-hills-and-valleys-in-an-array
Python Solution reduce
hgalytoby
0
52
count hills and valleys in an array
2,210
0.581
Easy
30,650
https://leetcode.com/problems/count-hills-and-valleys-in-an-array/discuss/2124580/python-Detailed-Solution
class Solution: def countHillValley(self, nums: List[int]) -> int: i, cnt = 1, 0 while i < len(nums) - 1: before, after = i - 1, i + 1 f1, f2 = False, False while True: if f1 and f2: break if before < 0 or after >= len(nums): break if nums[before] == nums[i]: before -= 1 else: f1 = True if nums[after] == nums[i]: after += 1 else: f2 = True if f1 and f2: if nums[before] < nums[i] and nums[after] < nums[i] or nums[before] > nums[i] and nums[after] > nums[i]: cnt += 1 i = after - 1 i += 1 return cnt
count-hills-and-valleys-in-an-array
python Detailed Solution
Hejita
0
85
count hills and valleys in an array
2,210
0.581
Easy
30,651
https://leetcode.com/problems/count-hills-and-valleys-in-an-array/discuss/2045887/Python-solution
class Solution: def countHillValley(self, nums: List[int]) -> int: count = 0 equal_neighbors = False for i in range(1, len(nums) - 1): if nums[i] == nums[i + 1] and equal_neighbors: continue if nums[i] == nums[i + 1]: equal_neighbors = True save_place = nums[i - 1] continue if equal_neighbors: hill = save_place < nums[i] and nums[i + 1] < nums[i] valley = nums[i + 1] > nums[i] and save_place > nums[i] if hill or valley: count += 1 else: hill = nums[i - 1] < nums[i] and nums[i + 1] < nums[i] valley = nums[i - 1] > nums[i] and nums[i + 1] > nums[i] if hill or valley: count += 1 equal_neighbors = False return count
count-hills-and-valleys-in-an-array
Python solution
Yoxbox
0
63
count hills and valleys in an array
2,210
0.581
Easy
30,652
https://leetcode.com/problems/count-hills-and-valleys-in-an-array/discuss/2031906/java-python-rearrange-array
class Solution: def countHillValley(self, nums: List[int]) -> int: ans = 0 num = 0 lis = [] for n in nums: if n != num : num = n lis.append(num) for i in range(2,len(lis)): if (lis[i-2] < lis[i-1] and lis[i-1] > lis[i]) or (lis[i-2] > lis[i-1] and lis[i-1] < lis[i]): ans+=1 return ans
count-hills-and-valleys-in-an-array
java, python - rearrange array
ZX007java
0
40
count hills and valleys in an array
2,210
0.581
Easy
30,653
https://leetcode.com/problems/count-hills-and-valleys-in-an-array/discuss/1958694/Python-dollarolution-(99-faster)
class Solution: def countHillValley(self, nums: List[int]) -> int: count, i = 0, 1 while i < len(nums)-1: x = nums[i-1] while i < len(nums)-2 and nums[i] == nums[i+1]: i += 1 if nums[i] > x and nums[i] > nums[i+1]: count += 1 elif nums[i] < x and nums[i] < nums[i+1]: count += 1 i += 1 return count
count-hills-and-valleys-in-an-array
Python $olution (99% faster)
AakRay
0
79
count hills and valleys in an array
2,210
0.581
Easy
30,654
https://leetcode.com/problems/count-hills-and-valleys-in-an-array/discuss/1949697/4-Lines-Python-Solution-oror-90-Faster-oror-Memory-less-than-80
class Solution: def countHillValley(self, nums: List[int]) -> int: N=[nums[i] for i in range(len(nums)-1) if nums[i]!=nums[i+1]]+[nums[-1]] ; ans=0 for i in range(1,len(N)-1): if (N[i]<N[i-1] and N[i]<N[i+1]) or (N[i]>N[i-1] and N[i]>N[i+1]): ans+=1 return ans
count-hills-and-valleys-in-an-array
4-Lines Python Solution || 90% Faster || Memory less than 80%
Taha-C
0
55
count hills and valleys in an array
2,210
0.581
Easy
30,655
https://leetcode.com/problems/count-hills-and-valleys-in-an-array/discuss/1949697/4-Lines-Python-Solution-oror-90-Faster-oror-Memory-less-than-80
class Solution: def countHillValley(self, N: List[int]) -> int: ans=0 for i in range(1,len(N)-1): if N[i]==N[i+1]: N[i]=N[i-1] if (N[i]<N[i-1] and N[i]<N[i+1]) or (N[i]>N[i-1] and N[i]>N[i+1]): ans+=1 return ans
count-hills-and-valleys-in-an-array
4-Lines Python Solution || 90% Faster || Memory less than 80%
Taha-C
0
55
count hills and valleys in an array
2,210
0.581
Easy
30,656
https://leetcode.com/problems/count-hills-and-valleys-in-an-array/discuss/1870596/python-3-oror-simple-O(n)O(1)
class Solution: def countHillValley(self, nums: List[int]) -> int: prevDir = res = 0 for i in range(1, len(nums)): if nums[i] > nums[i-1]: res += prevDir == -1 prevDir = 1 elif nums[i] < nums[i-1]: res += prevDir == 1 prevDir = -1 return res
count-hills-and-valleys-in-an-array
python 3 || simple O(n)/O(1)
dereky4
0
33
count hills and valleys in an array
2,210
0.581
Easy
30,657
https://leetcode.com/problems/count-hills-and-valleys-in-an-array/discuss/1869924/Count-Hills-and-Valleys-in-an-Array-oror-Python3-oror-Simple-while-loop-3-pointer-solution
class Solution: def countHillValley(self, nums: List[int]) -> int: j = 2 #main pointer i = j-1 k = j-2 count = 0 while(j<len(nums)): if(nums[i]>nums[k] and nums[i]>nums[j]): count+=1 j+=1 i=j-1 k=j-2 elif(nums[i]<nums[k] and nums[i]<nums[j]): count+=1 j+=1 i=j-1 k=j-2 elif(nums[i] == nums[j]): j+=1 else: j+=1 i=j-1 k=j-2 return count
count-hills-and-valleys-in-an-array
Count Hills and Valleys in an Array || Python3 || Simple while loop 3 pointer solution
darshanraval194
0
28
count hills and valleys in an array
2,210
0.581
Easy
30,658
https://leetcode.com/problems/count-hills-and-valleys-in-an-array/discuss/1866531/Python3-or-Only-keep-climax-or-easy-understanding
class Solution: def countHillValley(self, A: List[int]) -> int: # only keep climax A = [k for k, v in groupby(A)] ans = 0 # find hills and valleys for i in range(1, len(A)-1): if A[i-1]>A[i]<A[i+1] or A[i-1]<A[i]>A[i+1]: ans += 1 return ans
count-hills-and-valleys-in-an-array
Python3 | Only keep climax | easy-understanding
zhuzhengyuan824
0
13
count hills and valleys in an array
2,210
0.581
Easy
30,659
https://leetcode.com/problems/count-hills-and-valleys-in-an-array/discuss/1866047/Python-or-Remove-Consecutive-Dups
class Solution: def countHillValley(self, nums: List[int]) -> int: ans, nums = 0, [x for i, x in enumerate(nums) if nums[i-1] != x] for i in range(1, len(nums) - 1): is_hill = nums[i-1] < nums[i] > nums[i+1] is_valley = nums[i-1] > nums[i] < nums[i+1] ans += is_hill or is_valley return ans
count-hills-and-valleys-in-an-array
Python | Remove Consecutive Dups
leeteatsleep
0
17
count hills and valleys in an array
2,210
0.581
Easy
30,660
https://leetcode.com/problems/count-hills-and-valleys-in-an-array/discuss/1865865/Python-Simple-Solution-or-Easy-To-Understand
class Solution: def countHillValley(self, nums: List[int]) -> int: c = 0 for i in range(1,len(nums)-1): a = "" b = "" x = i y = i if nums[i]==nums[i-1] and i!=1: continue else: while x>=0: if nums[x]>nums[i]: a = "U" break if nums[x]<nums[i]: a = "L" break x-=1 while y<len(nums): if nums[y]>nums[i]: b = "U" break if nums[y]<nums[i]: b = "L" break y+=1 if (a=="U" and b=="U") or (a=="L" and b=="L"): c+=1 return c
count-hills-and-valleys-in-an-array
Python Simple Solution | Easy To Understand
AkashHooda
0
19
count hills and valleys in an array
2,210
0.581
Easy
30,661
https://leetcode.com/problems/count-hills-and-valleys-in-an-array/discuss/1865757/Python-O(N)O(1)
class Solution: def countHillValley(self, nums: List[int]) -> int: direction = 0 result = 0 for i in range(1, len(nums)): if nums[i] > nums[i-1]: result += direction == -1 direction = 1 elif nums[i] < nums[i-1]: result += direction == 1 direction = -1 return result
count-hills-and-valleys-in-an-array
Python, O(N)/O(1)
blue_sky5
0
22
count hills and valleys in an array
2,210
0.581
Easy
30,662
https://leetcode.com/problems/count-hills-and-valleys-in-an-array/discuss/1865566/Python-or-Easy-Understanding
class Solution: def countHillValley(self, nums: List[int]) -> int: n = len(nums) count = 0 i = 1 while i < n-1: skip = 1 if nums[i] > nums[i-1] and nums[i] > nums[i+1]: count += 1 elif nums[i] < nums[i-1] and nums[i] < nums[i+1]: count += 1 elif nums[i] == nums[i+1]: after = i while after < n -1 and nums[after] == nums[after+1]: after += 1 skip += 1 if after == n-1: return count elif nums[i] > nums[i-1] and nums[after] > nums[after+1]: count += 1 elif nums[i] < nums[i-1] and nums[after] < nums[after+1]: count += 1 i += skip return count
count-hills-and-valleys-in-an-array
Python | Easy Understanding
Mikey98
0
58
count hills and valleys in an array
2,210
0.581
Easy
30,663
https://leetcode.com/problems/count-hills-and-valleys-in-an-array/discuss/1865565/Efficient-Python-5-lines-solution-with-explanation
class Solution: def countHillValley(self, nums: List[int]) -> int: count, last = 0, nums[0] for i in range(1, len(nums)-1): last = nums[i-1] if nums[i] != nums[i-1] else last count += 1 if (last < nums[i] > nums[i+1] or last > nums[i] < nums[i+1]) else 0 return count
count-hills-and-valleys-in-an-array
Efficient Python 5-lines solution with explanation
yangshun
0
77
count hills and valleys in an array
2,210
0.581
Easy
30,664
https://leetcode.com/problems/count-hills-and-valleys-in-an-array/discuss/1865565/Efficient-Python-5-lines-solution-with-explanation
class Solution: def countHillValley(self, nums: List[int]) -> int: count, new = 0, [nums[0]] # Create a new array with non-consecutive values for i in range(1, len(nums)): if nums[i] != nums[i-1]: new.append(nums[i]) for i in range(1, len(new)-1): count += 1 if (new[i-1] < new[i] > new[i+1] or new[i-1] > new[i] < new[i+1]) else 0 return count
count-hills-and-valleys-in-an-array
Efficient Python 5-lines solution with explanation
yangshun
0
77
count hills and valleys in an array
2,210
0.581
Easy
30,665
https://leetcode.com/problems/count-collisions-on-a-road/discuss/1865694/One-liner-in-Python
class Solution: def countCollisions(self, directions: str) -> int: return sum(d!='S' for d in directions.lstrip('L').rstrip('R'))
count-collisions-on-a-road
One-liner in Python
LuckyBoy88
65
1,200
count collisions on a road
2,211
0.419
Medium
30,666
https://leetcode.com/problems/count-collisions-on-a-road/discuss/1865926/Short-Easy-Python-Solution-With-Explanation
class Solution: def countCollisions(self, directions: str) -> int: ans = 0 # At the beginning, leftest car can go without collide # At the beginning, rightest car can go without collide leftc = rightc = 0 for c in directions: # if left side, no car stop or right answer + 0 # if left side start to have car go right or stop # then cars after that are bound to be stopped so answer + 1 if c == "L": ans += leftc else: leftc = 1 for c in directions[::-1]: # if right side, no car stop or left answer + 0 # if right side start to have car go left or stop # then cars after that are bound to be stopped so answer + 1 if c == "R": ans += rightc else: rightc = 1 return ans
count-collisions-on-a-road
Short Easy Python Solution With Explanation
jlu56
12
500
count collisions on a road
2,211
0.419
Medium
30,667
https://leetcode.com/problems/count-collisions-on-a-road/discuss/1865578/Efficient-Python-solution-O(N)-time-O(1)-space-with-clear-explanation
class Solution: def countCollisions(self, directions: str) -> int: has_stationary, right, collisions = False, 0, 0 for direction in directions: if direction == 'R': # Just record number of right-moving cars. We will resolve them when we encounter a left-moving/stationary car. right += 1 elif direction == 'L' and (has_stationary or right > 0): # Left-moving cars which don't have any existing right-moving/stationary cars to their left can be ignored. They won't hit anything. # But if there are right-moving/stationary cars, it will result in collisions and we can resolve them. # We reset right to 0 because they have collided and will become stationary cars. collisions += 1 + right right = 0 has_stationary = True elif direction == 'S': # Resolve any right-moving cars and reset right to 0 because they are now stationary. collisions += right right = 0 has_stationary = True return collisions
count-collisions-on-a-road
Efficient Python solution O(N) time O(1) space with clear explanation
yangshun
3
255
count collisions on a road
2,211
0.419
Medium
30,668
https://leetcode.com/problems/count-collisions-on-a-road/discuss/1865578/Efficient-Python-solution-O(N)-time-O(1)-space-with-clear-explanation
class Solution: def countCollisions(self, directions: str) -> int: has_stationary, right, collisions = False, 0, 0 for direction in directions: if direction == 'R': right += 1 elif (direction == 'L' and (has_stationary or right > 0)) or direction == 'S': collisions += (1 if direction == 'L' else 0) + right right = 0 has_stationary = True return collisions
count-collisions-on-a-road
Efficient Python solution O(N) time O(1) space with clear explanation
yangshun
3
255
count collisions on a road
2,211
0.419
Medium
30,669
https://leetcode.com/problems/count-collisions-on-a-road/discuss/1865795/Python3-or-Two-pass
class Solution: def countCollisions(self, directions: str) -> int: temp = [] for dire in directions: temp.append(dire) directions = temp n = len(directions) if n == 0 or n == 1: return 0 ans = 0 # while for i in range(1,n): if directions[i-1] == "R" and directions[i] == "L": ans += 2 directions[i] = "S" directions[i-1] = "S" elif directions[i-1] == "R" and directions[i] == "S": ans += 1 directions[i] = "S" directions[i-1] = "S" elif directions[i-1] == "S" and directions[i] == "L": ans += 1 directions[i] = "S" directions[i-1] = "S" for i in range(n-2,-1,-1): if directions[i] == "R" and directions[i+1] == "L": ans += 2 directions[i+1] = "S" directions[i] = "S" elif directions[i] == "R" and directions[i+1] == "S": ans += 1 directions[i+1] = "S" directions[i] = "S" elif directions[i] == "S" and directions[i+1] == "L": ans += 1 directions[i+1] = "S" directions[i] = "S" return ans
count-collisions-on-a-road
Python3 | Two pass
goyaljatin9856
1
27
count collisions on a road
2,211
0.419
Medium
30,670
https://leetcode.com/problems/count-collisions-on-a-road/discuss/1990073/Python3-O(n)-time-O(1)-space-Solution
class Solution: def countCollisions(self, directions: str) -> int: R_counter = 0 s_flag = False res = 0 for char in directions: if char == 'R': R_counter += 1 s_flag = False elif char == 'S': if not s_flag: res += R_counter s_flag = True R_counter = 0 else: if s_flag: res += 1 else: if R_counter: res += 2 + (R_counter - 1) s_flag = True R_counter = 0 return res
count-collisions-on-a-road
Python3 O(n) time O(1) space Solution
xxHRxx
0
61
count collisions on a road
2,211
0.419
Medium
30,671
https://leetcode.com/problems/count-collisions-on-a-road/discuss/1949970/1-Line-Python-Solution-oror-95-Faster-oror-Memory-less-than-90
class Solution: def countCollisions(self, D: str) -> int: return sum(d!='S' for d in D.lstrip('L').rstrip('R'))
count-collisions-on-a-road
1-Line Python Solution || 95% Faster || Memory less than 90%
Taha-C
0
81
count collisions on a road
2,211
0.419
Medium
30,672
https://leetcode.com/problems/count-collisions-on-a-road/discuss/1949970/1-Line-Python-Solution-oror-95-Faster-oror-Memory-less-than-90
class Solution: def countCollisions(self, D: str) -> int: D=D.lstrip('L').rstrip('R') ; ans=0 ; carsFromRight=0 for i in range(len(D)): if D[i]=='R': carsFromRight+=1 else: ans+=(carsFromRight if D[i]=='S' else carsFromRight+1) carsFromRight=0 return ans
count-collisions-on-a-road
1-Line Python Solution || 95% Faster || Memory less than 90%
Taha-C
0
81
count collisions on a road
2,211
0.419
Medium
30,673
https://leetcode.com/problems/count-collisions-on-a-road/discuss/1904417/Python3-3-Pass-Solution-with-O(1)-extra-space
class Solution: def countCollisions(self, directions: str) -> int: n, ans = len(directions), 0 front, tail = 0, n-1 while front < n: if directions[front] != "L": break front += 1 while tail > -1: if directions[tail] != "R": break tail -= 1 for idx in range(front, tail + 1): ans += 1 if directions[idx] != "S" else 0 return ans
count-collisions-on-a-road
Python3 3-Pass Solution with O(1) extra space
CanYing0913
0
40
count collisions on a road
2,211
0.419
Medium
30,674
https://leetcode.com/problems/count-collisions-on-a-road/discuss/1889813/Python-Stack-Solution
class Solution: def countCollisions(self, directions: str) -> int: collisions = 0 st = [directions[0]] for i in range(1, len(directions)): d = directions[i] if st[-1] == 'R' and (d == 'L' or d == 'S'): st.pop() collisions += 2 if d == 'L' else 1 while st and st[-1] == 'R': st.pop() collisions += 1 st.append('S') elif d == 'L' and st[-1] == 'S': collisions += 1 elif d == 'S': st = [d] elif d == 'R': st.append(d) return collisions
count-collisions-on-a-road
✅ Python Stack Solution
chetankalra11
0
81
count collisions on a road
2,211
0.419
Medium
30,675
https://leetcode.com/problems/count-collisions-on-a-road/discuss/1875683/Python-easy-to-read-and-understand
class Solution: def countCollisions(self, directions: str) -> int: l, r = 0, 0 ans = 0 for i in directions: if i == "L": ans += l else: l = 1 for i in directions[::-1]: if i == "R": ans += r else: r = 1 return ans
count-collisions-on-a-road
Python easy to read and understand
sanial2001
0
46
count collisions on a road
2,211
0.419
Medium
30,676
https://leetcode.com/problems/count-collisions-on-a-road/discuss/1870874/Python3-or-Two-Pass
class Solution: def countCollisions(self, directions: str) -> int: hset={'RL','SL','RS'} j=1 ans=0 directions=list(directions) while j<len(directions): currDir=directions[j-1]+directions[j] if currDir in hset: if currDir=='RL': ans+=2 else: ans+=1 directions[j-1]='S' directions[j]='S' j+=1 j=len(directions)-1 while j>0: currDir=directions[j-1]+directions[j] if currDir in hset: if currDir=='RL': ans+=2 else: ans+=1 directions[j-1]='S' directions[j]='S' j-=1 return ans
count-collisions-on-a-road
[Python3] | Two Pass
swapnilsingh421
0
18
count collisions on a road
2,211
0.419
Medium
30,677
https://leetcode.com/problems/count-collisions-on-a-road/discuss/1867419/python3-simple-clean-code-100-in-time-and-space
class Solution: def countCollisions(self, directions: str) -> int: staying, res, cnt = 0, 0, 0 for d in directions: if d == 'R': staying = 1 cnt += 1 elif d == 'S': res += cnt cnt = 0 staying = 1 else: if staying: res += 1 res += cnt cnt = 0 return res # T.C. O(N) // the main for loop # S.C. O(1)
count-collisions-on-a-road
python3 simple clean code 100% in time and space
conlinwang
0
12
count collisions on a road
2,211
0.419
Medium
30,678
https://leetcode.com/problems/count-collisions-on-a-road/discuss/1866572/Python3-or-Monotonic-%22No-collision%22-Stack
class Solution: def countCollisions(self, A: str) -> int: stk = [] ans = 0 for x in A: while stk and ((stk[-1]=='R' and x=='L') or (stk[-1]=='R' and x=='S') or (stk[-1]=='S' and x=='L')): if stk[-1]=='R' and x=='L': ans += 2 elif (stk[-1]=='R' and x=='S') or (stk[-1]=='S' and x=='L'): ans += 1 stk.pop() # staying after collision x = 'S' stk.append(x) return ans
count-collisions-on-a-road
Python3 | Monotonic "No collision" Stack
zhuzhengyuan824
0
22
count collisions on a road
2,211
0.419
Medium
30,679
https://leetcode.com/problems/count-collisions-on-a-road/discuss/1865763/Python-or-O(n)-O(1)-or-Simple-straightforward-solution
class Solution: def countCollisions(self, directions: str) -> int: c=0 d=directions prev=d[0] rc=0 for i in range(1, len(d)): if d[i]=='L' and prev=='R': c+=2 c+=rc rc=0 prev='S' elif d[i]=='L' and prev=='S': c+=1 prev='S' elif d[i]=='S' and prev=='R': c+=1 c+=rc rc=0 prev=d[i] elif d[i]=='R' and prev=='R': rc+=1 prev=d[i] else: prev=d[i] return c
count-collisions-on-a-road
[Python] | O(n) / O(1) | Simple straightforward solution
MJ111
0
20
count collisions on a road
2,211
0.419
Medium
30,680
https://leetcode.com/problems/count-collisions-on-a-road/discuss/1865586/Python-I-Stack
class Solution: def countCollisions(self, directions: str) -> int: count = 0 stack = [] for char in directions: # if the stack is empty, and the direction is left, we just continue if not stack and char == 'L': continue # otherwise we add the direction in the stack ('S' or 'R') because they might lead to collisions elif not stack and char != 'L': stack.append(char) # stack is not empty else: # the top element in the stack cur = stack[-1] # cases that will not lead to collisions if char == cur or cur == 'S' and char == 'R' or cur == 'L' and char == 'S' or cur == 'L' and char == 'R': stack.append(char) # collision happen but the top of the stack is already 'S' no need to append elif cur == 'S' and char == 'L': count += 1 # collision happen, append a 'S' at the top elif cur == 'R' and char == 'S': count += 1 stack.pop() stack.append('S') # collision happen, append a 'S' at the top elif cur == 'R' and char == 'L': count += 2 stack.pop() stack.append('S') # here, the stack only contains 'R' and 'S' # we only need to deal with the 'R' before 'S' case n = len(stack) i = 0 while i < n: rs = 1 if stack[i] == 'S': i += 1 elif stack[i] == 'R': if i == n-1: return count elif stack[i] != stack[i+1]: count += 1 i += 1 else: while i < n-1 and stack[i] == 'R' and stack[i] == stack[i+1]: rs += 1 i += 1 if i == n-1: return count else: count += rs i += 1 return count
count-collisions-on-a-road
Python I Stack
Mikey98
0
71
count collisions on a road
2,211
0.419
Medium
30,681
https://leetcode.com/problems/maximum-points-in-an-archery-competition/discuss/1866042/Python3-DP-100-with-Detailed-Explanation
class Solution: def maximumBobPoints(self, numArrows: int, aliceArrows: List[int]) -> List[int]: # Initialization with round 1 (round 0 is skipped) dp = {(0, 0): (0, numArrows), (0, aliceArrows[1] + 1): (1, numArrows - (aliceArrows[1] + 1))} # Loop from round 2 for i in range(2, 12): prev = dp dp = {} # Consider two possible strategies for each state from last round: to bid and not to bid for key in prev: # Base case: not to bid in this round. Score and arrows left do not change. # Simply append 0 at the end to the key. newkey1 = list(key) newkey1.append(0) score, arrowleft = prev[key] newval1 = (score, arrowleft) dp[tuple(newkey1)] = newval1 # If we still have enough arrows, we can bid in this round if arrowleft >= aliceArrows[i] + 1: newkey2 = list(key) newkey2.append(aliceArrows[i] + 1) newval2 = (score + i, arrowleft - (aliceArrows[i] + 1)) dp[tuple(newkey2)] = newval2 # Select the bidding history with max score maxscore, res = 0, None for key in dp: score, _ = dp[key] if score > maxscore: maxscore = score res = list(key) # Taking care of the corner case, where too many arrows are given if sum(res) < numArrows: res[0] = numArrows - sum(res) return res
maximum-points-in-an-archery-competition
[Python3] DP 100% with Detailed Explanation
hsjiang
1
68
maximum points in an archery competition
2,212
0.489
Medium
30,682
https://leetcode.com/problems/maximum-points-in-an-archery-competition/discuss/1865913/Python-3-Try-All-Possible-212-Sequences-Bitmasking
class Solution: def maximumBobPoints(self, numArrows: int, aliceArrows: List[int]) -> List[int]: bobArrows = [] for i in range(12): bobArrows.append(aliceArrows[i] + 1) maxScore, maxBinNum = 0, None for binNum in range(2 ** 12): tempScore, tempArrows = 0, 0 tempBinNum = binNum k = 0 while tempBinNum > 0: if tempBinNum % 2 == 1: tempScore += k tempArrows += bobArrows[k] tempBinNum //= 2 k += 1 if tempArrows <= numArrows and tempScore > maxScore: maxScore = tempScore maxBinNum = binNum output = [0] * 12 k = 0 while maxBinNum > 0: if maxBinNum % 2 == 1: output[k] = bobArrows[k] maxBinNum //= 2 k += 1 if sum(output) < numArrows: output[0] += numArrows - sum(output) return output
maximum-points-in-an-archery-competition
Python 3 - Try All Possible 2^12 Sequences - Bitmasking
xil899
1
52
maximum points in an archery competition
2,212
0.489
Medium
30,683
https://leetcode.com/problems/maximum-points-in-an-archery-competition/discuss/1865585/Python-backtracking-with-explanation
class Solution: def maximumBobPoints(self, numArrows: int, aliceArrows: List[int]) -> List[int]: max_score = [0, None] def calc(i, remaining, score, arrows): # Base case. Update max score. if remaining == 0 or i == -1: if score > max_score[0]: max_score[0] = score max_score[1] = arrows[:] return # Special handling for the last section. Use up all the arrows. if i == 0: arrows[i] = remaining calc(i - 1, 0, score + i, arrows) arrows[i] = 0 return # Try to compete with Alice if there are enough arrows. arrowsNeeded = aliceArrows[i] + 1 if remaining >= arrowsNeeded: arrows[i] = arrowsNeeded calc(i - 1, remaining - arrowsNeeded, score + i, arrows) arrows[i] = 0 # Skip this section and go to the next section. calc(i - 1, remaining, score, arrows) # Kick off the recursion calc(len(aliceArrows) - 1, numArrows, 0, [0 for _ in aliceArrows]) return max_score[1]
maximum-points-in-an-archery-competition
Python backtracking with explanation
yangshun
1
165
maximum points in an archery competition
2,212
0.489
Medium
30,684
https://leetcode.com/problems/maximum-points-in-an-archery-competition/discuss/2552766/Python-3-DP-Solution
class Solution: def maximumBobPoints(self, numArrows: int, aliceArrows: List[int]) -> List[int]: # DP, table to store the max score for current section and number of arrows dp = [[-1 for _ in range(numArrows + 1)] for _ in range(12)] # minArrowsForBobToWin stores bob arrows to win in each section # bobMaxScore stores result bob arrows for max score minArrowsForBobToWin, bobMaxScore = [aliceArrows[i] + 1 for i in range(len(aliceArrows))], [0 for _ in range(12)] # Helper function to find max score for each number of arrows upto the actual number of arrows # for all the sections upto a given section def findMaxScore(section: int, numArrows: int, dp: List[List[int]], minArrowsForBobToWin: List[int]) -> int: # base case # return score 0 for arrows <= 0 or section <= 0 if numArrows <= 0 or section <= 0: return 0 # returning precalculated result if dp[section][numArrows] != -1: return dp[section][numArrows] # Variables to store the scores if the current section is taken or not taken, notTaken = 0, 0 # if remaining arrows >= minArrowsForBobToWin[section] then we can take current section # and call recursively if numArrows >= minArrowsForBobToWin[section]: taken = section + findMaxScore(section - 1, numArrows - minArrowsForBobToWin[section], dp, minArrowsForBobToWin) # recursive call without taking current section notTaken = findMaxScore(section - 1, numArrows, dp, minArrowsForBobToWin) # get max score from taken and not taken case dp[section][numArrows] = max(taken, notTaken) return dp[section][numArrows] # find maximum score bob can obtain findMaxScore(11, numArrows, dp, minArrowsForBobToWin) # find bob's arrows for each section starting from max score section for i in range(11, 0, -1): if numArrows >= minArrowsForBobToWin[i] and dp[i][numArrows] > dp[i - 1][numArrows]: bobMaxScore[i] = minArrowsForBobToWin[i] numArrows -= minArrowsForBobToWin[i] if numArrows <= 0: break # add remaining arrows in section 0 if numArrows > 0: bobMaxScore[0] = numArrows return bobMaxScore
maximum-points-in-an-archery-competition
Python 3 DP Solution
hemantdhamija
0
23
maximum points in an archery competition
2,212
0.489
Medium
30,685
https://leetcode.com/problems/maximum-points-in-an-archery-competition/discuss/1992464/Python3-bitmask-and-DP-%2B-backtrack
class Solution: def maximumBobPoints(self, numArrows: int, aliceArrows: List[int]) -> List[int]: bobArrows = [x+1 for x in aliceArrows] def genconfig(length): if length == 0: return [''] else: return ['1' + x for x in genconfig(length-1)] + \ ['0' + x for x in genconfig(length-1)] configs = genconfig(11) score, res = -sys.maxsize, None for con in configs: arrow_needed = sum([bobArrows[x+1] for x in range(11) if con[x] == '1']) if arrow_needed <= numArrows: temp_score = sum([x+1 for x in range(11) if con[x] == '1']) if temp_score > score: score = temp_score res = [numArrows - arrow_needed] + [bobArrows[x+1] if con[x] == '1' else 0 for x in range(11)] return res #dp knapsack + backtrack #grid = [([[0, 0] for x in range(12)]) for _ in range(numArrows+1)] #aliceArrows = [x + 1 for x in aliceArrows] #for t in range(1, 12): # target = aliceArrows[t] # for k in range(numArrows+1): # if k >= target: # if grid[k-target][t-1][0] + t >= grid[k][t-1][0]: # grid[k][t][0] = grid[k-target][t-1][0] + t # grid[k][t][1] = target # else: # grid[k][t][0] = grid[k][t-1][0] # else: # grid[k][t][0] = grid[k][t-1][0] #res = [] #for t in range(11, 0, -1): # score, choice = grid[numArrows][t] # res.append(choice) # numArrows -= choice #res.append(numArrows) #return res[::-1]
maximum-points-in-an-archery-competition
Python3 bitmask & DP + backtrack
xxHRxx
0
48
maximum points in an archery competition
2,212
0.489
Medium
30,686
https://leetcode.com/problems/maximum-points-in-an-archery-competition/discuss/1886201/Checking-allowed-combinations-91-speed
class Solution: def maximumBobPoints(self, numArrows: int, aliceArrows: List[int]) -> List[int]: allowed = [i + 1 for i in aliceArrows] ans, max_points = dict(), 0 level = [] for i in range(1, 12): if allowed[i] < numArrows: level.append([{i: allowed[i]}, numArrows - allowed[i], i + 1]) elif allowed[i] == numArrows: ans, max_points = {i: allowed[i]}, i while level: new_level = [] for shots, remaining, start_idx in level: if start_idx == 12: points = sum(shots.keys()) if points > max_points: ans, max_points = shots, points else: for i in range(start_idx, 12): if allowed[i] < remaining: new_shots = shots.copy() new_shots[i] = allowed[i] new_level.append([new_shots, remaining - allowed[i], i + 1]) elif allowed[i] == remaining: new_shots = shots.copy() new_shots[i] = allowed[i] points = sum(new_shots.keys()) if points > max_points: ans, max_points = new_shots, points else: new_level.append([shots, remaining, i + 1]) level = new_level res = [0] * 12 for i, arrows in ans.items(): res[i] = arrows res[0] = max(0, numArrows - sum(ans.values())) return res
maximum-points-in-an-archery-competition
Checking allowed combinations, 91% speed
EvgenySH
0
80
maximum points in an archery competition
2,212
0.489
Medium
30,687
https://leetcode.com/problems/maximum-points-in-an-archery-competition/discuss/1868426/Python-3-DP-%2B-Bitmask
class Solution: def maximumBobPoints(self, numArrows: int, aliceArrows: List[int]) -> List[int]: self.score_max = -1 self.mask_max = None def dp(i, mask, numArrows): if i == 0: scores = sum(k for k in range(12) if mask &amp; (1 << k)) if scores > self.score_max: self.score_max = scores self.mask_max = mask return if numArrows > aliceArrows[i]: dp(i - 1, mask, numArrows) dp(i - 1, mask ^ (1 << i), numArrows - aliceArrows[i] - 1) else: dp(i - 1, mask, numArrows) dp(11, 0, numArrows) ans = [0] * 12 for i in range(12): if self.mask_max &amp; (1 << i): ans[i] = aliceArrows[i] + 1 rest = numArrows - sum(ans) ans[0] += rest return ans
maximum-points-in-an-archery-competition
[Python 3] DP + Bitmask
chestnut890123
0
24
maximum points in an archery competition
2,212
0.489
Medium
30,688
https://leetcode.com/problems/maximum-points-in-an-archery-competition/discuss/1868208/Python3-faster-than-100
class Solution: def maximumBobPoints(self, numArrows: int, aliceArrows: List[int]) -> List[int]: ## def dp(st,arr): if st == 12 or arr == 0: return 0 mS = dp(st+1,arr) if aliceArrows[st] < arr: return max(mS,dp(st+1,arr-aliceArrows[st]-1) + st) else: return mS ## ans = [0]*12 remarr = numArrows for ii in range(12): if dp(ii+1,remarr) < dp(ii,remarr): ans[ii] = aliceArrows[ii] + 1 remarr -= aliceArrows[ii] + 1 ans[0] += remarr return ans
maximum-points-in-an-archery-competition
Python3 faster than 100%
nonieno
0
17
maximum points in an archery competition
2,212
0.489
Medium
30,689
https://leetcode.com/problems/maximum-points-in-an-archery-competition/discuss/1867910/Python3-Backtracking-Reversely-beat-100
class Solution: def maximumBobPoints(self, numArrows: int, aliceArrows: List[int]) -> List[int]: result = [0]*12 ans = 0 S = [0] for i in range(12): S.append(S[-1] + i) def dfs(idx, path, left, score): nonlocal ans, result if score+S[idx+1] < ans: return if idx == -1 or left == 0: if score > ans: result = path[:] # add remaining arrows result[0] += left ans = score return # bob wins if left > aliceArrows[idx]: path[idx] = aliceArrows[idx]+1 dfs(idx-1, path, left-aliceArrows[idx]-1, score+idx) path[idx] = 0 # alice wins dfs(idx-1, path, left, score) path = [0]*12 dfs(11, path, numArrows, 0) return result
maximum-points-in-an-archery-competition
[Python3] Backtracking Reversely beat 100%
nightybear
0
32
maximum points in an archery competition
2,212
0.489
Medium
30,690
https://leetcode.com/problems/maximum-points-in-an-archery-competition/discuss/1866766/python-DP-solution-Runtime%3A-396-ms-faster-than-100.00-of-Python3
class Solution: def __init__(self): self.mem = {} # {(scoring_section,remaining_arrow_count)} = mask def maximumBobPoints(self, numArrows: int, aliceArrows: List[int]) -> List[int]: (mask,score) = self.dp(numArrows,0,len(aliceArrows)-1,0,aliceArrows) # print("mask:",mask) r = [] zeroTarget = numArrows for i in range(1,len(aliceArrows)): if mask &amp; 1<<i : zeroTarget -= aliceArrows[i]+1 r.append(aliceArrows[i]+1) else : r.append(0) r = [zeroTarget] + r return r def dp(self,numArrows: int, mask , scoring_section , score ,aliceArrows: List[int]) -> (int,int): if numArrows <= 0 : return (mask,score) if scoring_section <= 0: return (mask,score) if (scoring_section,numArrows) in self.mem: return self.mem[(scoring_section,numArrows)] score1 = 0 if numArrows- (aliceArrows[scoring_section]+1) >= 0: mask1,score1 = self.dp(numArrows- (aliceArrows[scoring_section]+1) , mask , scoring_section-1 , score , aliceArrows[:-1]) mask1 |= 1<<scoring_section score1 += scoring_section else : mask1 = mask mask2,score2 = self.dp(numArrows , mask , scoring_section-1 , score , aliceArrows[:-1]) if score1 >= score2 : self.mem[(scoring_section,numArrows)] = (mask1,score1) else : self.mem[(scoring_section,numArrows)] = (mask2,score2) return self.mem[(scoring_section,numArrows)]
maximum-points-in-an-archery-competition
[python] DP solution - Runtime: 396 ms, faster than 100.00% of Python3
cheoljoo
0
24
maximum points in an archery competition
2,212
0.489
Medium
30,691
https://leetcode.com/problems/find-the-difference-of-two-arrays/discuss/2668224/Python-solution.-Clean-code-with-full-comments.-95.96-speed.
class Solution: def findDifference(self, nums1: List[int], nums2: List[int]) -> List[List[int]]: set_1 = list_to_set(nums1) set_2 = list_to_set(nums2) return remove_same_elements(set_1, set_2) # Convert the lists into sets via helper method. def list_to_set(arr: List[int]): s = set() for i in arr: s.add(i) return s # Now when the two lists are sets, use the difference attribute to filter common elements of the two sets. def remove_same_elements(x, y): x, y = list(x - y), list(y - x) return [x, y] # Runtime: 185 ms, faster than 95.96% of Python3 online submissions for Find the Difference of Two Arrays. # Memory Usage: 14.3 MB, less than 51.66% of Python3 online submissions for Find the Difference of Two Arrays. # If you like my work, then I'll appreciate a like. Thanks!
find-the-difference-of-two-arrays
Python solution. Clean code with full comments. 95.96% speed.
375d
3
159
find the difference of two arrays
2,215
0.693
Easy
30,692
https://leetcode.com/problems/find-the-difference-of-two-arrays/discuss/2169618/Python-oneliner
class Solution: def findDifference(self, n1: List[int], n2: List[int]) -> List[List[int]]: return [set(n1) - set(n2),set(n2) - set(n1)]
find-the-difference-of-two-arrays
Python oneliner
StikS32
1
75
find the difference of two arrays
2,215
0.693
Easy
30,693
https://leetcode.com/problems/find-the-difference-of-two-arrays/discuss/2851421/python-easy-2-solution-greatergreater
class Solution: def findDifference(self, nums1: List[int], nums2: List[int]) -> List[List[int]]: x = [i for i in nums1 if i not in nums2]; y = [j for j in nums2 if j not in nums1]; return [list(set(x)) , list(set(y))];
find-the-difference-of-two-arrays
python easy 2 solution-->>
seifsoliman
0
1
find the difference of two arrays
2,215
0.693
Easy
30,694
https://leetcode.com/problems/find-the-difference-of-two-arrays/discuss/2851342/Python-or-Simple-approach-or
class Solution: def findDifference(self, nums1: List[int], nums2: List[int]) -> List[List[int]]: p=[[],[]] for i in set(nums1): if i in nums2: continue else: p[0].append(i) for i in set(nums2): if i in nums1: continue else: p[1].append(i) return p
find-the-difference-of-two-arrays
Python | Simple approach |
priyanshupriyam123vv
0
1
find the difference of two arrays
2,215
0.693
Easy
30,695
https://leetcode.com/problems/find-the-difference-of-two-arrays/discuss/2741858/Solution-Using-Set-Difference
class Solution: def findDifference(self, nums1: List[int], nums2: List[int]) -> List[List[int]]: s = set(nums1) s1 = set(nums2) return [list(s-s1),list(s1-s)]
find-the-difference-of-two-arrays
Solution Using Set Difference
dnvavinash
0
3
find the difference of two arrays
2,215
0.693
Easy
30,696
https://leetcode.com/problems/find-the-difference-of-two-arrays/discuss/2573178/Python-solution-using-set-and-intersection-no-loops!
class Solution: def findDifference(self, nums1: List[int], nums2: List[int]) -> List[List[int]]: result = [] set_nums1 = set(nums1) set_nums2 = set(nums2) intersection = set_nums1.intersection(set_nums2) result.append(list(set_nums1 - intersection)) result.append(list(set_nums2 - intersection)) return result
find-the-difference-of-two-arrays
Python solution using set and intersection, no loops!
samanehghafouri
0
16
find the difference of two arrays
2,215
0.693
Easy
30,697
https://leetcode.com/problems/find-the-difference-of-two-arrays/discuss/2546718/Easiest-Python-solution
class Solution: def findDifference(self, nums1: List[int], nums2: List[int]) -> List[List[int]]: return [list(set(nums1) - set(nums2)),list(set(nums2) - set(nums1))]
find-the-difference-of-two-arrays
Easiest Python solution 😊
betaal
0
18
find the difference of two arrays
2,215
0.693
Easy
30,698
https://leetcode.com/problems/find-the-difference-of-two-arrays/discuss/2544901/Python-Simple-Python-Solution
class Solution: def findDifference(self, nums1: List[int], nums2: List[int]) -> List[List[int]]: result = [] temp_list_one = [] for num in nums1: if num not in nums2 and num not in temp_list_one: temp_list_one.append(num) temp_list_second = [] for num in nums2: if num not in nums1 and num not in temp_list_second: temp_list_second.append(num) result.append(temp_list_one) result.append(temp_list_second) return result
find-the-difference-of-two-arrays
[ Python ] ✅✅ Simple Python Solution 🥳✌👍
ASHOK_KUMAR_MEGHVANSHI
0
25
find the difference of two arrays
2,215
0.693
Easy
30,699