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/number-of-pairs-of-strings-with-concatenation-equal-to-target/discuss/1613355/Python3-one-liner
|
class Solution:
def numOfPairs(self, nums: List[str], target: str) -> int:
return collections.Counter(map(''.join, itertools.permutations(nums, 2))).get(target, 0)
|
number-of-pairs-of-strings-with-concatenation-equal-to-target
|
Python3 one-liner
|
hangyu1130
| 0
| 54
|
number of pairs of strings with concatenation equal to target
| 2,023
| 0.729
|
Medium
| 28,200
|
https://leetcode.com/problems/number-of-pairs-of-strings-with-concatenation-equal-to-target/discuss/1501678/O(n%2Bm)-T-or-O(n%2Bm)-S-or-prefix-function-%2B-hash-table-or-Python-3
|
class Solution:
def numOfPairs(self, nums: List[str], target: str) -> int:
import collections
def prefix_function(string: str) -> list[int]:
"""Return prefix function for string. O(n)
:param string: input string.
:return:
"""
result = [0] * len(string)
result[0] = 0
for i in range(1, len(string)):
k = result[i - 1]
while k > 0 and string[i] != string[k]:
k = result[k-1]
if string[i] == string[k]:
k += 1
result[i] = k
return result
def string_period(string: str) -> int:
"""Return length period of string. O(n)
:param string: input string.
:return:
"""
pi = prefix_function(string)
n = len(string)
k = n - pi[-1]
if n % k == 0:
return k
else:
return n
# First step
content = []
for num in nums:
if target.startswith(num):
is_prefix = True
else:
is_prefix = False
if target.endswith(num):
is_suffix = True
else:
is_suffix = False
content.append((len(num), is_prefix, is_suffix))
# Second step
cnt = collections.Counter()
for length, is_prefix, _ in content:
if is_prefix:
cnt[length] += 1
# Third step
n = len(target)
period = string_period(target)
result = 0
for length, is_prefix, is_suffix in content:
if is_suffix:
value = cnt[n - length]
if value > 0:
if n == 2*length and length % period == 0:
value -= 1
result += value
return result
|
number-of-pairs-of-strings-with-concatenation-equal-to-target
|
O(n+m) T | O(n+m) S | prefix function + hash table | Python 3
|
CiFFiRO
| 0
| 58
|
number of pairs of strings with concatenation equal to target
| 2,023
| 0.729
|
Medium
| 28,201
|
https://leetcode.com/problems/number-of-pairs-of-strings-with-concatenation-equal-to-target/discuss/1499756/Python-Back-Tracking-O(N-*-2)
|
class Solution:
def numOfPairs(self, nums: List[str], target: str) -> int:
def backTracking(res, curr_path, start):
if len(curr_path) == 2:
res.append(curr_path)
return
for i in range(len(nums)):
if not curr_path:
backTracking(res, curr_path + [(nums[i], i)], i + 1)
else:
if i != curr_path[-1][1]:
backTracking(res, curr_path + [(nums[i], i)], i + 1)
else:
continue
return res
L = backTracking([], [], 0)
L = sum([1 for i in L if i[0][0] + i[1][0] == target])
return (L)
|
number-of-pairs-of-strings-with-concatenation-equal-to-target
|
[Python] Back Tracking O(N * 2)
|
Sai-Adarsh
| 0
| 43
|
number of pairs of strings with concatenation equal to target
| 2,023
| 0.729
|
Medium
| 28,202
|
https://leetcode.com/problems/number-of-pairs-of-strings-with-concatenation-equal-to-target/discuss/1499214/Python-3-Solution
|
class Solution:
def numOfPairs(self, nums: List[str], target: str) -> int:
count=0
for i in range(0,len(nums)):
for j in range(i+1,len(nums)):
if (nums[i]+nums[j])==target:
count=count+1
if (nums[j]+nums[i])==target:
count=count+1
return count
|
number-of-pairs-of-strings-with-concatenation-equal-to-target
|
[Python 3] Solution
|
evenly_odd
| 0
| 48
|
number of pairs of strings with concatenation equal to target
| 2,023
| 0.729
|
Medium
| 28,203
|
https://leetcode.com/problems/number-of-pairs-of-strings-with-concatenation-equal-to-target/discuss/1499121/Python-Solution
|
class Solution:
def numOfPairs(self, nums: List[str], target: str) -> int:
n = len(nums)
count = 0
for i in range(n):
a = nums[i]
for j in range(i+1,n):
b = nums[j]
if a+b == target:
count += 1
if b+a == target:
count += 1
return count
|
number-of-pairs-of-strings-with-concatenation-equal-to-target
|
[Python] Solution
|
SaSha59
| 0
| 45
|
number of pairs of strings with concatenation equal to target
| 2,023
| 0.729
|
Medium
| 28,204
|
https://leetcode.com/problems/number-of-pairs-of-strings-with-concatenation-equal-to-target/discuss/1700256/Python3-accepted-solution
|
class Solution:
def numOfPairs(self, nums: List[str], target: str) -> int:
count=0
for i in range(len(nums)):
for j in range(len(nums)):
if(i!=j):
if(nums[i] + nums[j] == target):
count+=1
return count
|
number-of-pairs-of-strings-with-concatenation-equal-to-target
|
Python3 accepted solution
|
sreeleetcode19
| -1
| 92
|
number of pairs of strings with concatenation equal to target
| 2,023
| 0.729
|
Medium
| 28,205
|
https://leetcode.com/problems/maximize-the-confusion-of-an-exam/discuss/1951750/WEEB-DOES-PYTHONC%2B%2B-SLIDING-WINDOW
|
class Solution:
def maxConsecutiveAnswers(self, string: str, k: int) -> int:
result = 0
j = 0
count1 = k
for i in range(len(string)):
if count1 == 0 and string[i] == "F":
while string[j] != "F":
j+=1
count1+=1
j+=1
if string[i] == "F":
if count1 > 0:
count1-=1
if i - j + 1 > result:
result = i - j + 1
j = 0
count2 = k
for i in range(len(string)):
if count2 == 0 and string[i] == "T":
while string[j] != "T":
j+=1
count2+=1
j+=1
if string[i] == "T":
if count2 > 0:
count2-=1
if i - j + 1 > result:
result = i - j + 1
return result
|
maximize-the-confusion-of-an-exam
|
WEEB DOES PYTHON/C++ SLIDING WINDOW
|
Skywalker5423
| 2
| 95
|
maximize the confusion of an exam
| 2,024
| 0.598
|
Medium
| 28,206
|
https://leetcode.com/problems/maximize-the-confusion-of-an-exam/discuss/1624131/python-sliding-window-with-explanation
|
class Solution:
def maxConsecutiveAnswers(self, answerKey: str, k: int) -> int:
n = len(answerKey)
left = ret = numT = numF = 0
for right in range(n):
if answerKey[right]=='T':
numT+=1
else:
numF+=1
while numT>k and numF>k:
if answerKey[left]=='T':
numT-=1
else:
numF-=1
left+=1
ret = max(ret, right-left+1)
return ret
|
maximize-the-confusion-of-an-exam
|
python sliding window with explanation
|
1579901970cg
| 2
| 132
|
maximize the confusion of an exam
| 2,024
| 0.598
|
Medium
| 28,207
|
https://leetcode.com/problems/maximize-the-confusion-of-an-exam/discuss/1521886/Python-Same-Problem-as-'Longest-Consecutive-Subarray-of-1's-With-K-Deletions'
|
class Solution:
def maxConsecutiveAnswers(self, answerKey: str, k: int) -> int:
ifTrueIsAnswer = self.confuseStudents(answerKey, k, "T")
ifFalseIsAnswer = self.confuseStudents(answerKey, k, "F")
return max(ifTrueIsAnswer, ifFalseIsAnswer)
def confuseStudents(self, array, k, key):
left, result = 0, 0
for right in range(len(array)):
if array[right] == key:
k -= 1
if k < 0:
result = max(result, right-left)
while k < 0:
if array[left] == key:
k += 1
left += 1
return max(result, right+1-left)
|
maximize-the-confusion-of-an-exam
|
[Python] Same Problem as 'Longest Consecutive Subarray of 1's With K Deletions'
|
ramit_kumar
| 2
| 124
|
maximize the confusion of an exam
| 2,024
| 0.598
|
Medium
| 28,208
|
https://leetcode.com/problems/maximize-the-confusion-of-an-exam/discuss/1567232/Python-solution-212-ms-better-than-98
|
class Solution:
def maxConsecutiveAnswers(self, answerKey: str, k: int) -> int:
tmpK = k
#check for False
i = 0
for j in range(0,len(answerKey)):
if answerKey[j] == 'T':
k -= 1
if k < 0:
if answerKey[i] == 'T':
k += 1
i += 1
falseCount = j-i+1
k = tmpK
#check for True
i = 0
for j in range(0,len(answerKey)):
if answerKey[j] == 'F':
k -= 1
if k < 0:
if answerKey[i] == 'F':
k += 1
i += 1
trueCount = j-i+1
return max(falseCount, trueCount)
|
maximize-the-confusion-of-an-exam
|
Python solution 212 ms better than 98%
|
akshaykumar19002
| 1
| 100
|
maximize the confusion of an exam
| 2,024
| 0.598
|
Medium
| 28,209
|
https://leetcode.com/problems/maximize-the-confusion-of-an-exam/discuss/1499015/Python3-sliding-window
|
class Solution:
def maxConsecutiveAnswers(self, answerKey: str, k: int) -> int:
def fn(target):
"""Return max consecutive target."""
ans = cnt = ii = 0
for i, x in enumerate(answerKey):
if x == target: cnt += 1
while cnt > k:
if answerKey[ii] == target: cnt -= 1
ii += 1
ans = max(ans, i - ii + 1)
return ans
return max(fn("T"), fn("F"))
|
maximize-the-confusion-of-an-exam
|
[Python3] sliding window
|
ye15
| 1
| 60
|
maximize the confusion of an exam
| 2,024
| 0.598
|
Medium
| 28,210
|
https://leetcode.com/problems/maximize-the-confusion-of-an-exam/discuss/2676084/Ezy-to-understand-two-pointers-python3-solution-or-O(n)-time-or-O(1)-space
|
class Solution:
# O(n) time,
# O(1) space,
# Approach: two pointers,
def maxConsecutiveAnswers(self, answerKey: str, k: int) -> int:
n = len(answerKey)
k_copy = k
longst_true = 0
l, r = 0, 0
while r < n:
if answerKey[r] == 'T':
r +=1
continue
if k_copy > 0:
r +=1
k_copy -=1
continue
longst_true = max(longst_true, r-l)
while l < r and answerKey[l] == 'T':
l +=1
if l == r: r +=1
l +=1
k_copy +=1
longst_true = max(longst_true, r-l)
longst_false = 0
l, r = 0, 0
while r < n:
if answerKey[r] == 'F':
r +=1
continue
if k > 0:
r +=1
k -=1
continue
longst_false = max(longst_false, r-l)
while l < r and answerKey[l] == 'F':
l +=1
if l == r: r +=1
l +=1
k +=1
longst_false = max(longst_false, r-l)
return max(longst_true, longst_false)
|
maximize-the-confusion-of-an-exam
|
Ezy to understand two pointers python3 solution | O(n) time | O(1) space
|
destifo
| 0
| 9
|
maximize the confusion of an exam
| 2,024
| 0.598
|
Medium
| 28,211
|
https://leetcode.com/problems/maximize-the-confusion-of-an-exam/discuss/2646267/Python3-Solution-oror-O(N)-Time-and-O(1)-Space-Complexity
|
class Solution:
def maxConsecutiveAnswers(self, answerKey: str, k: int) -> int:
countTrue=0
countFalse=0
maxTF=0
start=0
n=len(answerKey)
for i in range(n):
if answerKey[i]=="T":
countTrue+=1
else:
countFalse+=1
while countTrue>k and countFalse>k:
if answerKey[start]=="T":
countTrue-=1
else:
countFalse-=1
start+=1
if (countTrue<=k or countFalse<=k) and maxTF<(countTrue+countFalse):
maxTF=countFalse+countTrue
return maxTF
|
maximize-the-confusion-of-an-exam
|
Python3 Solution || O(N) Time & O(1) Space Complexity
|
akshatkhanna37
| 0
| 8
|
maximize the confusion of an exam
| 2,024
| 0.598
|
Medium
| 28,212
|
https://leetcode.com/problems/maximize-the-confusion-of-an-exam/discuss/2310680/Python3-or-Sliding-Window-Technique
|
class Solution:
def maxConsecutiveAnswers(self, answerKey: str, k: int) -> int:
#Time-Complexity: O(n)
#Space-Complexity: O(1)
#sliding window technique!
L = 0
hashmap = {'T': 0,
'F': 0}
answer = 0
for R in range(len(answerKey)):
#process right element
right_char = answerKey[R]
hashmap[right_char] += 1
#stopping condition: if minimum of two counts > k!
#usually, we only enter this while loop if both counts are k!
while min(hashmap['T'], hashmap['F']) > k:
#update our answer as needed!
answer = max(answer, R - L)
#process the left element before shrinking our current sliding window!
if(answerKey[L] == 'T'):
hashmap['T'] -= 1
else:
hashmap['F'] -= 1
L += 1
#continue expanding our current sliding window!
#handle the edge case when the longest consecutive T or F is located at end of string!
#in that case, the count of Trues and Falses we built up until we reached dead end, it's possible
#to convert the lower of the two's count to the other character type so that we have consecutive
#number of T or F, which is sum of two counts we built up in the hashmap!
answer = max(answer, hashmap['T'] + hashmap['F'])
return answer
|
maximize-the-confusion-of-an-exam
|
Python3 | Sliding Window Technique
|
JOON1234
| 0
| 29
|
maximize the confusion of an exam
| 2,024
| 0.598
|
Medium
| 28,213
|
https://leetcode.com/problems/maximize-the-confusion-of-an-exam/discuss/2175999/Using-the-concept-and-approach-of-max-consecutive-ones-iii-oror-Sliding-Window-oror-Simplest-Solution
|
class Solution:
def longestConsecutive(self, array, k):
length = len(array)
l = 0
for r, val in enumerate(array):
k -= (1 - val)
if k < 0:
k += (1 - array[l])
l += 1
return r - l + 1
def maxConsecutiveAnswers(self, answerKey: str, k: int) -> int:
answers_1 = [0 if key == 'F' else 1 for key in answerKey]
answers_2 = [0 if key == 'T' else 1 for key in answerKey]
longestLengthAfterFlipping_0 = self.longestConsecutive(answers_1, k)
longestLengthAfterFlipping_1 = self.longestConsecutive(answers_2, k)
return max(longestLengthAfterFlipping_0, longestLengthAfterFlipping_1)
|
maximize-the-confusion-of-an-exam
|
Using the concept and approach of max consecutive ones iii || Sliding Window || Simplest Solution
|
Vaibhav7860
| 0
| 26
|
maximize the confusion of an exam
| 2,024
| 0.598
|
Medium
| 28,214
|
https://leetcode.com/problems/maximize-the-confusion-of-an-exam/discuss/2010539/Python-160ms
|
class Solution:
def maxConsecutiveAnswers(self, answerKey: str, k: int) -> int:
t = f = mx = i = 0
for j in range(len(answerKey)):
if answerKey[j] == 'T':
t += 1
else:
f += 1
if t > k and f > k: # invalid - just move 1 step
if answerKey[i] == 'T':
t -= 1
else:
f -= 1
i += 1
else:
mx = j-i+1
return mx
|
maximize-the-confusion-of-an-exam
|
Python 160ms
|
qeisar
| 0
| 42
|
maximize the confusion of an exam
| 2,024
| 0.598
|
Medium
| 28,215
|
https://leetcode.com/problems/maximize-the-confusion-of-an-exam/discuss/1928657/6-Lines-Python-Solution-oror-90-Faster-oror-Memory-less-than-88
|
class Solution:
def maxConsecutiveAnswers(self, A: str, k: int) -> int:
w=0 ; i=0 ; C=Counter()
for j in range(len(A)):
C[A[j]]+=1
if C['T']>k and C['F']>k: C[A[i]]-=1 ; i+=1
else: w=max(w,j-i+1)
return w
|
maximize-the-confusion-of-an-exam
|
6-Lines Python Solution || 90% Faster || Memory less than 88%
|
Taha-C
| 0
| 62
|
maximize the confusion of an exam
| 2,024
| 0.598
|
Medium
| 28,216
|
https://leetcode.com/problems/maximize-the-confusion-of-an-exam/discuss/1827576/Python-easy-to-read-and-understand-or-Leetcode-424
|
class Solution:
def maxConsecutiveAnswers(self, answerKey: str, k: int) -> int:
s = answerKey[:]
d = {}
ans, i = 0, 0
for j in range(len(s)):
d[s[j]] = d.get(s[j], 0) + 1
cnt = (j - i + 1) - max(d.values())
while cnt > k:
d[s[i]] -= 1
i = i + 1
cnt = (j - i + 1) - max(d.values())
ans = max(ans, j - i + 1)
return ans
|
maximize-the-confusion-of-an-exam
|
Python easy to read and understand | Leetcode 424
|
sanial2001
| 0
| 97
|
maximize the confusion of an exam
| 2,024
| 0.598
|
Medium
| 28,217
|
https://leetcode.com/problems/maximize-the-confusion-of-an-exam/discuss/1743620/Python3-solution-using-two-helper-functions
|
class Solution:
def maxConsecutiveAnswers(self, answerkey: str, k: int) -> int:
from collections import defaultdict
mydict1=defaultdict(int)
mydict2=defaultdict(int)
n=len(answerkey)
def helper1(k):
left=0
ans=0
for right in range(n):
mydict1[answerkey[right]]+=1
while mydict1["F"]>k:
mydict1[answerkey[left]]-=1
left+=1
ans=max(ans,right-left+1)
return ans
def helper2(k):
left=0
ans=0
for right in range(n):
mydict2[answerkey[right]]+=1
while mydict2["T"]>k:
mydict2[answerkey[left]]-=1
left+=1
ans=max(ans,right-left+1)
return ans
ans1=helper1(k)
ans2=helper2(k)
return max(ans1,ans2)
|
maximize-the-confusion-of-an-exam
|
Python3 solution using two helper functions
|
Karna61814
| 0
| 31
|
maximize the confusion of an exam
| 2,024
| 0.598
|
Medium
| 28,218
|
https://leetcode.com/problems/maximize-the-confusion-of-an-exam/discuss/1544711/python3-2-Pass-slide-window-with-Queue
|
class Solution:
def maxConsecutiveAnswers(self, answerKey: str, k: int) -> int:
# idea is based on 2 pass solution with sliding window
# one pass is for changing T by F and count maximum subStr len of all Fs
# other pass is for changing F by T and count maximum subStr len of all Ts
# queue is used to store indexs of changing chars to slide window
n = len(answerKey)
def changeAndCount(ch,k):
q = deque()
max_window_size = 0
start,end = 0,0
while end < n:
if answerKey[end] == ch:
end +=1
else:
if k :
q.append(end)
k -=1
end +=1
else:
max_window_size = max(max_window_size,end-start)
start = q.popleft()+1
k +=1
max_window_size = max(max_window_size,end-start)
return max_window_size
replace_T = changeAndCount('T',k)
if replace_T == n:
return n
replace_F = changeAndCount('F',k)
return max(replace_T,replace_F)
```
|
maximize-the-confusion-of-an-exam
|
python3 , 2 Pass , slide window with Queue
|
Code-IQ7
| 0
| 28
|
maximize the confusion of an exam
| 2,024
| 0.598
|
Medium
| 28,219
|
https://leetcode.com/problems/maximize-the-confusion-of-an-exam/discuss/1499152/Python-Sliding-Window
|
class Solution:
def maxConsecutiveAnswers(self, nums: str, k: int) -> int:
n = len(nums)
def util(char, K):
ans, l = 0, 0
for r in range(n):
if nums[r] == char:
if K == 0:
while nums[l] != char:
l += 1
l += 1
else :
K-= 1
ans = max(ans, r - l + 1)
return ans
return max(util('F', k), util('T', k))
|
maximize-the-confusion-of-an-exam
|
Python Sliding Window
|
abkc1221
| 0
| 56
|
maximize the confusion of an exam
| 2,024
| 0.598
|
Medium
| 28,220
|
https://leetcode.com/problems/maximum-number-of-ways-to-partition-an-array/discuss/1499024/Python3-binary-search
|
class Solution:
def waysToPartition(self, nums: List[int], k: int) -> int:
prefix = [0]
loc = defaultdict(list)
for i, x in enumerate(nums):
prefix.append(prefix[-1] + x)
if i < len(nums)-1: loc[prefix[-1]].append(i)
ans = 0
if prefix[-1] % 2 == 0: ans = len(loc[prefix[-1]//2]) # unchanged
total = prefix[-1]
for i, x in enumerate(nums):
cnt = 0
diff = k - x
target = total + diff
if target % 2 == 0:
target //= 2
cnt += bisect_left(loc[target], i)
cnt += len(loc[target-diff]) - bisect_left(loc[target-diff], i)
ans = max(ans, cnt)
return ans
|
maximum-number-of-ways-to-partition-an-array
|
[Python3] binary search
|
ye15
| 2
| 227
|
maximum number of ways to partition an array
| 2,025
| 0.321
|
Hard
| 28,221
|
https://leetcode.com/problems/maximum-number-of-ways-to-partition-an-array/discuss/2801817/Python3-Counter-of-(Left-Right)-at-Each-Pivot
|
class Solution:
def waysToPartition(self, nums: List[int], k: int) -> int:
"""This is a good problem. It's not difficult, but is quite complex.
The idea is that once we change a position at i, for all the pivots at
1...i, the sum of the left half stay the same whereas the sum of
the right half changes by delta = k - nums[i]. Similarly, for all the
pivots at i + 1...n - 1, the left half changes by delta, whereas the
right half stay the same.
We can pre-compute all the differences at each pivot position and make
that into a diffs = [d1, d2, .... , dn-1]
Then after a change at i, if we want the pivots at 1...i to form a good
partition, we must have left - (right + delta) = 0 => delta = left - right
In other words, the number of good partitions is the count of d1, d2, ...
di that are equal to delta. Similarly, if we want the pivots at i + 1...
n - 1 to form a good partition, we must have left + delta - right = 0
=> left - right = -delta. In other words, the number of good partitions
is the count of di+1, ...., dn-1 that are equal to -delta.
Based on this, we progressively build a left sum and right sum to
compute the diffs array. And then progressively build a left counter
and right counter to compute the number of matches to delta and -delta.
The difficulty is in the implementation, especially with the indices.
O(N), 7339 ms, faster than 32.20%
"""
N = len(nums)
diffs = []
sl, sr = 0, sum(nums)
for i in range(N - 1):
sl += nums[i]
sr -= nums[i]
diffs.append(sl - sr)
diffs.append(math.inf) # to prevent error in the counter arithemtic
cl, cr = Counter(), Counter(diffs)
res = cl[0] + cr[0]
for i in range(N):
d = k - nums[i]
res = max(res, cl[d] + cr[-d])
cl[diffs[i]] += 1
cr[diffs[i]] -= 1
return res
|
maximum-number-of-ways-to-partition-an-array
|
[Python3] Counter of (Left - Right) at Each Pivot
|
FanchenBao
| 0
| 2
|
maximum number of ways to partition an array
| 2,025
| 0.321
|
Hard
| 28,222
|
https://leetcode.com/problems/minimum-moves-to-convert-string/discuss/1500215/Python3-scan
|
class Solution:
def minimumMoves(self, s: str) -> int:
ans = i = 0
while i < len(s):
if s[i] == "X":
ans += 1
i += 3
else: i += 1
return ans
|
minimum-moves-to-convert-string
|
[Python3] scan
|
ye15
| 28
| 1,200
|
minimum moves to convert string
| 2,027
| 0.537
|
Easy
| 28,223
|
https://leetcode.com/problems/minimum-moves-to-convert-string/discuss/1525838/Easy-Python-Solution-or-Faster-than-99-(24-ms)
|
class Solution:
def minimumMoves(self, s: str) -> int:
i, m = 0, 0
l = len(s)
while i < l:
if s[i] != 'X':
i += 1
elif 'X' not in s[i:i+1]:
i += 2
elif 'X' in s[i:i+2]:
m += 1
i += 3
return m
|
minimum-moves-to-convert-string
|
Easy Python Solution | Faster than 99% (24 ms)
|
the_sky_high
| 5
| 351
|
minimum moves to convert string
| 2,027
| 0.537
|
Easy
| 28,224
|
https://leetcode.com/problems/minimum-moves-to-convert-string/discuss/1722144/Simplest-Python-3-code
|
class Solution:
def minimumMoves(self, s: str) -> int:
sl=list(s)
out=0
for i in range(0,len(sl)-2):
if sl[i]=="X":
sl[i]="O"
sl[i+1]="O"
sl[i+2]="O"
out+=1
elif sl[i]=="O":
continue
if sl[-1]=="X" or sl[-2]=="X":
out+=1
return out
|
minimum-moves-to-convert-string
|
Simplest Python 3 code
|
rajatkumarrrr
| 1
| 92
|
minimum moves to convert string
| 2,027
| 0.537
|
Easy
| 28,225
|
https://leetcode.com/problems/minimum-moves-to-convert-string/discuss/1512345/Python-simple-solution-better-than-97
|
class Solution(object):
def minimumMoves(self, s):
"""
:type s: str
:rtype: int
"""
ans, l = 0, 0
while l < len(s):
if s[l] == 'X':
l+=3
ans +=1
else:
l+=1
return ans
|
minimum-moves-to-convert-string
|
Python simple solution better than 97%
|
avigupta10
| 1
| 116
|
minimum moves to convert string
| 2,027
| 0.537
|
Easy
| 28,226
|
https://leetcode.com/problems/minimum-moves-to-convert-string/discuss/2777309/Python-intiutive-O(N)-time-and-O(1)-solution
|
class Solution:
def minimumMoves(self, s: str) -> int:
i = 0
count = 0
while i<len(s):
if s[i]== "X":
count+=1
i +=3
else:
i+=1
return count
|
minimum-moves-to-convert-string
|
Python intiutive O(N) time and O(1) solution
|
Rajeev_varma008
| 0
| 2
|
minimum moves to convert string
| 2,027
| 0.537
|
Easy
| 28,227
|
https://leetcode.com/problems/minimum-moves-to-convert-string/discuss/2640186/Python3-Simple-Iteration
|
class Solution:
def minimumMoves(self, s: str) -> int:
x = list(s)
x.append('0')
x.append('0')
c = 0
for i in range(len(x) - 2):
if x[i] == 'X':
c+=1
x[i+1] = '0'
x[i+2] = '0'
return c
|
minimum-moves-to-convert-string
|
Python3 Simple Iteration
|
godshiva
| 0
| 5
|
minimum moves to convert string
| 2,027
| 0.537
|
Easy
| 28,228
|
https://leetcode.com/problems/minimum-moves-to-convert-string/discuss/2551670/simple-python-solution
|
class Solution:
def minimumMoves(self, s: str) -> int:
x, y = 0,0
while x < len(s):
if s[x] == 'X':
x += 3
y += 1
else:
x += 1
return y
|
minimum-moves-to-convert-string
|
simple python solution
|
maschwartz5006
| 0
| 28
|
minimum moves to convert string
| 2,027
| 0.537
|
Easy
| 28,229
|
https://leetcode.com/problems/minimum-moves-to-convert-string/discuss/2506930/Single-pointer
|
class Solution:
def minimumMoves(self, s: str) -> int:
# use a single pointer to locate element at index
# if the element is X increment result and move the pointer by 3 (s[i:i+3] = "O")
# if not, move the pointer by 1
# Time O(N) Space: O(1)
n = len(s)
res = 0
i = 0
while i < n:
if s[i] == "X":
i += 3
res += 1
else:
i += 1
return res
|
minimum-moves-to-convert-string
|
Single pointer
|
andrewnerdimo
| 0
| 14
|
minimum moves to convert string
| 2,027
| 0.537
|
Easy
| 28,230
|
https://leetcode.com/problems/minimum-moves-to-convert-string/discuss/2115342/Python-3%3A-Easy-to-understand-(Faster-than-99)-oror-Self-Explanatory
|
class Solution:
def minimumMoves(self, s: str) -> int:
output=0
while "X" in s:
i=s.find('X')
output+=1
s=s[:i]+s[i+3:]
return output
|
minimum-moves-to-convert-string
|
Python 3: Easy to understand (Faster than 99%) || Self-Explanatory
|
kushal2201
| 0
| 85
|
minimum moves to convert string
| 2,027
| 0.537
|
Easy
| 28,231
|
https://leetcode.com/problems/minimum-moves-to-convert-string/discuss/1999896/python-3-oror-greedy-solution-oror-O(n)O(1)
|
class Solution:
def minimumMoves(self, s: str) -> int:
i = res = 0
n = len(s)
while i < n:
if s[i] == 'X':
res += 1
i += 3
else:
i += 1
return res
|
minimum-moves-to-convert-string
|
python 3 || greedy solution || O(n)/O(1)
|
dereky4
| 0
| 90
|
minimum moves to convert string
| 2,027
| 0.537
|
Easy
| 28,232
|
https://leetcode.com/problems/minimum-moves-to-convert-string/discuss/1881593/python-dollarolution
|
class Solution:
def minimumMoves(self, s: str) -> int:
i = 0
count = 0
while i < len(s):
if s[i] == 'X':
count += 1
i += 3
continue
i += 1
return count
|
minimum-moves-to-convert-string
|
python $olution
|
AakRay
| 0
| 45
|
minimum moves to convert string
| 2,027
| 0.537
|
Easy
| 28,233
|
https://leetcode.com/problems/minimum-moves-to-convert-string/discuss/1795983/Simple-Python-Solution-oror-99-Faster-(20ms)-oror-Memory-less-than-99
|
class Solution:
def minimumMoves(self, s: str) -> int:
ans, i = 0, 0
while i< len(s):
if s[i]=='O':
i += 1
continue
else:
ans += 1
i += 3
return ans
|
minimum-moves-to-convert-string
|
Simple Python Solution || 99% Faster (20ms) || Memory less than 99%
|
Taha-C
| 0
| 59
|
minimum moves to convert string
| 2,027
| 0.537
|
Easy
| 28,234
|
https://leetcode.com/problems/minimum-moves-to-convert-string/discuss/1642870/Python-O(n)-time-O(1)-space-easy-solution
|
class Solution:
def minimumMoves(self, s: str) -> int:
n = len(s)
idx = 0
res = 0
while idx < n:
if s[idx] == 'O':
idx += 1
else:
res += 1
idx += 3
return res
|
minimum-moves-to-convert-string
|
Python O(n) time, O(1) space easy solution
|
byuns9334
| 0
| 69
|
minimum moves to convert string
| 2,027
| 0.537
|
Easy
| 28,235
|
https://leetcode.com/problems/minimum-moves-to-convert-string/discuss/1508251/Greedy-O(n)-solution-in-Python
|
class Solution:
def minimumMoves(self, s: str) -> int:
i = cnt = 0
while i < len(s):
if s[i] == "X":
cnt += 1
i += 3
else:
i += 1
return cnt
|
minimum-moves-to-convert-string
|
Greedy O(n) solution in Python
|
mousun224
| 0
| 62
|
minimum moves to convert string
| 2,027
| 0.537
|
Easy
| 28,236
|
https://leetcode.com/problems/minimum-moves-to-convert-string/discuss/1501060/Python-one-pass-O(N)
|
class Solution:
def minimumMoves(self, s: str) -> int:
idx = moves = 0
while idx < len(s):
if s[idx] == 'X':
moves += 1
idx += 3
else:
idx += 1
return moves
|
minimum-moves-to-convert-string
|
Python, one pass O(N)
|
blue_sky5
| 0
| 49
|
minimum moves to convert string
| 2,027
| 0.537
|
Easy
| 28,237
|
https://leetcode.com/problems/minimum-moves-to-convert-string/discuss/1500345/Python-or-O(n)-time-O(1)-Space-or-6-lines
|
class Solution:
def minimumMoves(self, s: str) -> int:
min_moves = i = 0
while i < len(s):
is_x = s[i] == 'X'
min_moves += is_x
i += 2*is_x + 1
return min_moves
|
minimum-moves-to-convert-string
|
Python | O(n) time O(1) Space | 6 lines
|
leeteatsleep
| 0
| 52
|
minimum moves to convert string
| 2,027
| 0.537
|
Easy
| 28,238
|
https://leetcode.com/problems/minimum-moves-to-convert-string/discuss/1700019/Python3-accepted-solution
|
class Solution:
def minimumMoves(self, s: str) -> int:
count=0
li = []
for i in range(0,len(s)-2):
if(s[i]=="X"):
count+=1
s = s[:i] + "OOO" + s[i+3:]
else:
continue
if(s[-3:]=="OXX" or s[-3:]=="OOX" or s[-3:]=="OXO"): count+=1
return count
|
minimum-moves-to-convert-string
|
Python3 accepted solution
|
sreeleetcode19
| -1
| 58
|
minimum moves to convert string
| 2,027
| 0.537
|
Easy
| 28,239
|
https://leetcode.com/problems/minimum-moves-to-convert-string/discuss/1501346/Python3-or-Greedy-Intuitive
|
class Solution:
def safe_val_by_index(self, arr, start, end):
try:
val = arr[start:end]
except IndexError:
return []
return val
def minimumMoves(self, s: str) -> int:
a = list(s)
n = len(a)
p = 'X'
template = ['O']*3
ans = 0
idx = a.index(p) if p in a else -1
while idx >= 0:
# possible substring
# idx-2 .. idx, idx-1 .. idx+1, idx .. idx + 2
moves = [
[(max(0, idx), min(len(a), idx+3)), -1],
[(max(0, idx-1), min(len(a), idx+2)), -1],
[(max(0, idx-2), min(len(a), idx+1)), -1]
]
# default
best_move = moves[0]
for move in moves:
# find susbstring with the most 'X's
move[1] = self.safe_val_by_index(a, *move[0]).count('X')
if move[1] >= best_move[1]:
best_move = move
a[best_move[0][0]:best_move[0][1]] = template
ans += 1
idx = a.index(p) if p in a else -1
return ans
|
minimum-moves-to-convert-string
|
[Python3] | Greedy / Intuitive
|
patefon
| -1
| 40
|
minimum moves to convert string
| 2,027
| 0.537
|
Easy
| 28,240
|
https://leetcode.com/problems/find-missing-observations/discuss/1506196/Divmod-and-list-comprehension-96-speed
|
class Solution:
def missingRolls(self, rolls: List[int], mean: int, n: int) -> List[int]:
missing_val, rem = divmod(mean * (len(rolls) + n) - sum(rolls), n)
if rem == 0:
if 1 <= missing_val <= 6:
return [missing_val] * n
elif 1 <= missing_val < 6:
return [missing_val + 1] * rem + [missing_val] * (n - rem)
return []
|
find-missing-observations
|
Divmod and list comprehension, 96% speed
|
EvgenySH
| 2
| 133
|
find missing observations
| 2,028
| 0.439
|
Medium
| 28,241
|
https://leetcode.com/problems/find-missing-observations/discuss/1500222/Python3-greedy
|
class Solution:
def missingRolls(self, rolls: List[int], mean: int, n: int) -> List[int]:
total = mean * (len(rolls) + n) - sum(rolls)
if not n <= total <= 6*n: return []
q, r = divmod(total, n)
return [q]*(n-r) + [q+1]*r
|
find-missing-observations
|
[Python3] greedy
|
ye15
| 1
| 73
|
find missing observations
| 2,028
| 0.439
|
Medium
| 28,242
|
https://leetcode.com/problems/find-missing-observations/discuss/2820752/Python-No-loops-solutions
|
class Solution:
def missingRolls(self, rolls, mean, n):
m = len(rolls)
sum_target = mean * (n + m)
sum_current = sum(rolls)
sum_remaining = sum_target - sum_current
if not (n <= sum_remaining <= 6*n):
return []
remaining_rolls = [sum_remaining // n]*(n - sum_remaining % n) + [sum_remaining // n + 1]*(sum_remaining % n)
return remaining_rolls
|
find-missing-observations
|
[Python] No loops solutions
|
bison_a_besoncon
| 0
| 3
|
find missing observations
| 2,028
| 0.439
|
Medium
| 28,243
|
https://leetcode.com/problems/find-missing-observations/discuss/2669271/Python-or-Simple-Maths
|
class Solution:
def missingRolls(self, rolls: List[int], mean: int, n: int) -> List[int]:
m = len(rolls)
sum_rolls = sum(rolls)
target = mean * (m + n) - sum_rolls
q = target // n
r = target % n
if q > 6 or q < 1 or (q == 6 and r > 0):
return []
ans = [q] * n
# Optimization: just use r for the index!
while r > 0:
ans[r] += 1
r -= 1
return ans
|
find-missing-observations
|
Python | Simple Maths
|
on_danse_encore_on_rit_encore
| 0
| 8
|
find missing observations
| 2,028
| 0.439
|
Medium
| 28,244
|
https://leetcode.com/problems/find-missing-observations/discuss/1694949/python-simple-solution
|
class Solution:
def missingRolls(self, rolls: List[int], mean: int, n: int) -> List[int]:
m, s = len(rolls), sum(rolls)
x = mean*(m+n)-s
if x < n or x > 6*n:
return []
else:
t = x//n
res = [t for _ in range(n-1)]
res.append(x-t*(n-1))
if res[-1] > 6:
a = res[-1] - 6
for i in range(a):
res[i] += 1
res[-1] = 6
return res
|
find-missing-observations
|
python simple solution
|
byuns9334
| 0
| 96
|
find missing observations
| 2,028
| 0.439
|
Medium
| 28,245
|
https://leetcode.com/problems/find-missing-observations/discuss/1686301/WEEB-DOES-PYTHON-USING-MATH
|
class Solution:
def missingRolls(self, rolls: List[int], mean: int, n: int) -> List[int]:
numTerms = n + len(rolls)
sumOfM = sum(rolls)
sumOfN = mean * numTerms - sumOfM
# (die cannot be > 6) or (sumOfN cannot be negative or die cannot be less than 0)
if sumOfN / n > 6 or sumOfN // n <= 0:
return []
if sumOfN // n == sumOfN / n: # if division leaves no remainder
return [sumOfN // n] * n
else:
remainder = sumOfN % n
return [sumOfN // n] * (n - remainder) + [sumOfN // n + 1] * remainder
|
find-missing-observations
|
WEEB DOES PYTHON USING MATH
|
Skywalker5423
| 0
| 52
|
find missing observations
| 2,028
| 0.439
|
Medium
| 28,246
|
https://leetcode.com/problems/find-missing-observations/discuss/1502434/100-Faster-python-solution
|
class Solution:
def missingRolls(self, rolls: List[int], mean: int, n: int) -> List[int]:
m = len(rolls)
# Mean = sum(rolls) + n*average_n /m+n :-> average = n*average_n
average = mean*(m+n) - sum(rolls)
# Cheak: average cannot be greater than n*6 beacuse maximum value of dice is 6
# Similarly average cannot be less than n, because minimum value of dice is 1
if average>6*n or average<n:
return [] # return empty list
# will store the integer value of int(average/n) for all values in range(n)
# Then will add the reminder average%n for the first average%n elements in ans
ans = [average//n for i in range(n)]
reminder = average%n
for i in range(reminder):
ans[i]+=1
return ans
|
find-missing-observations
|
100% Faster python solution
|
ce17b127
| 0
| 45
|
find missing observations
| 2,028
| 0.439
|
Medium
| 28,247
|
https://leetcode.com/problems/find-missing-observations/discuss/1500378/Easy-Approach-oror-Math-oror-well-Explained
|
class Solution:
def missingRolls(self, rolls: List[int], mean: int, n: int) -> List[int]:
m = len(rolls)
req = mean*(m+n) - sum(rolls)
q,r = divmod(req,n)
if q<=0 or req>n*6:
return []
res = [q]*n
for i in range(r):
res[i]+=1
return res
|
find-missing-observations
|
📌📌 Easy-Approach || Math || well-Explained 🐍
|
abhi9Rai
| 0
| 41
|
find missing observations
| 2,028
| 0.439
|
Medium
| 28,248
|
https://leetcode.com/problems/find-missing-observations/discuss/1500161/Python-O(n)-solution
|
class Solution:
def missingRolls(self, rolls: List[int], mean: int, n: int) -> List[int]:
#finding the equal distribution of remaining sum
temp = mean*(n+len(rolls)) - sum(rolls)
each = temp//n
rem = temp%n
#return empty if out of dice range
if (not (1<=(each + 1)<=6) and rem>0) or not (1<=each<=6):
return []
res = [each]*n
i = 0
#adding the remainder to each possible
while rem > 0 and i<n:
res[i] += 1
rem -= 1
i += 1
return res
|
find-missing-observations
|
Python O(n) solution
|
abkc1221
| 0
| 160
|
find missing observations
| 2,028
| 0.439
|
Medium
| 28,249
|
https://leetcode.com/problems/stone-game-ix/discuss/1500343/Python3-freq-table
|
class Solution:
def stoneGameIX(self, stones: List[int]) -> bool:
freq = defaultdict(int)
for x in stones: freq[x % 3] += 1
if freq[0]%2 == 0: return freq[1] and freq[2]
return abs(freq[1] - freq[2]) >= 3
|
stone-game-ix
|
[Python3] freq table
|
ye15
| 3
| 165
|
stone game ix
| 2,029
| 0.264
|
Medium
| 28,250
|
https://leetcode.com/problems/stone-game-ix/discuss/1501697/python-clean-and-short-solution
|
class Solution:
def stoneGameIX(self, stones: List[int]) -> bool:
stones = [v % 3 for v in stones]
d = defaultdict(int)
for v in stones:
d[v] += 1
while d[1] >= 2 and d[2] >= 2:
d[2] -= 1
d[1] -= 1
if d[0] % 2 == 0: # number of 0s will not influent the result
if (d[1] == 1 and d[2] >= 1) or (d[2] == 1 and d[1] >= 1):
return True
else:
if (d[1] == 0 and d[2] >= 3) or (d[2] == 0 and d[1] >= 3):
return True
if (d[1] == 1 and d[2] >= 4) or (d[2] == 1 and d[1] >= 4):
return True
return False
|
stone-game-ix
|
python clean and short solution
|
pureme
| 1
| 107
|
stone game ix
| 2,029
| 0.264
|
Medium
| 28,251
|
https://leetcode.com/problems/smallest-k-length-subsequence-with-occurrences-of-a-letter/discuss/1502134/PYTHON3-O(n)-using-stack-with-explanation
|
class Solution:
def smallestSubsequence(self, s: str, k: int, letter: str, repetition: int) -> str:
counts,total = 0, 0
n = len(s)
for ch in s:
if ch==letter:
total +=1
stack = []
occ = 0
for idx,ch in enumerate(s):
if ch==letter:
counts +=1
while stack and stack[-1]>ch and len(stack)+ (n-1-idx)>=k and (occ+total-counts-(stack[-1]==letter)+(ch==letter)>=repetition ):
occ -= stack.pop()==letter
if ch!=letter and len(stack)< k-max(0,(repetition-occ)):
stack.append(ch)
elif ch==letter and len(stack)+(total-counts)<k:
stack.append(ch)
occ +=1
return ''.join(stack)
|
smallest-k-length-subsequence-with-occurrences-of-a-letter
|
[PYTHON3] O(n) using stack with explanation
|
irt
| 2
| 300
|
smallest k length subsequence with occurrences of a letter
| 2,030
| 0.387
|
Hard
| 28,252
|
https://leetcode.com/problems/smallest-k-length-subsequence-with-occurrences-of-a-letter/discuss/1860026/Python-Stack-solution
|
class Solution:
def smallestSubsequence(self, s: str, k: int, letter: str, repetition: int) -> str:
s = list(s)
stack = []
countAll = s.count(letter)
count = 0
for ind, i in enumerate(s):
while stack and stack[-1] > i:
if stack[-1] == letter and i != letter:
if countAll+count-1 < repetition:
break
if len(stack)+len(s)-ind-1 < k:
break
if stack[-1] == letter:
count-=1
stack.pop()
stack.append(i)
if i == letter:
count+=1
countAll-=1
temp = 0
while len(stack)+temp > k:
if stack[-1] == letter and count <= repetition:
temp+=1
if stack[-1] == letter:
count-=1
stack.pop()
return "".join(stack)+temp*letter
|
smallest-k-length-subsequence-with-occurrences-of-a-letter
|
Python Stack solution
|
khanter
| 1
| 171
|
smallest k length subsequence with occurrences of a letter
| 2,030
| 0.387
|
Hard
| 28,253
|
https://leetcode.com/problems/smallest-k-length-subsequence-with-occurrences-of-a-letter/discuss/1500303/Python3-10-line-stack
|
class Solution:
def smallestSubsequence(self, s: str, k: int, letter: str, repetition: int) -> str:
rest = sum(x == letter for x in s)
stack = []
for i, x in enumerate(s):
while stack and stack[-1] > x and len(stack) + len(s) - i > k and (stack[-1] != letter or repetition < rest):
if stack.pop() == letter: repetition += 1
if len(stack) < k and (x == letter or len(stack) + repetition < k):
stack.append(x)
if x == letter: repetition -= 1
if x == letter: rest -= 1
return "".join(stack)
|
smallest-k-length-subsequence-with-occurrences-of-a-letter
|
[Python3] 10-line stack
|
ye15
| 0
| 203
|
smallest k length subsequence with occurrences of a letter
| 2,030
| 0.387
|
Hard
| 28,254
|
https://leetcode.com/problems/two-out-of-three/discuss/1513311/Python3-set
|
class Solution:
def twoOutOfThree(self, nums1: List[int], nums2: List[int], nums3: List[int]) -> List[int]:
s1, s2, s3 = set(nums1), set(nums2), set(nums3)
return (s1&s2) | (s2&s3) | (s1&s3)
|
two-out-of-three
|
[Python3] set
|
ye15
| 20
| 1,400
|
two out of three
| 2,032
| 0.726
|
Easy
| 28,255
|
https://leetcode.com/problems/two-out-of-three/discuss/1513311/Python3-set
|
class Solution:
def twoOutOfThree(self, nums1: List[int], nums2: List[int], nums3: List[int]) -> List[int]:
freq = Counter()
for nums in nums1, nums2, nums3: freq.update(set(nums))
return [k for k, v in freq.items() if v >= 2]
|
two-out-of-three
|
[Python3] set
|
ye15
| 20
| 1,400
|
two out of three
| 2,032
| 0.726
|
Easy
| 28,256
|
https://leetcode.com/problems/two-out-of-three/discuss/1525692/Easy-Python-Solution-or-Faster-than-97-(64-ms)
|
class Solution:
def twoOutOfThree(self, nums1: List[int], nums2: List[int], nums3: List[int]) -> List[int]:
ret = []
ret += set(nums1).intersection(set(nums2))
ret += set(nums1).intersection(set(nums3))
ret += set(nums2).intersection(set(nums3))
return set(ret)
|
two-out-of-three
|
Easy Python Solution | Faster than 97% (64 ms)
|
the_sky_high
| 7
| 660
|
two out of three
| 2,032
| 0.726
|
Easy
| 28,257
|
https://leetcode.com/problems/two-out-of-three/discuss/1553645/python3-easy-set-solution
|
class Solution:
def twoOutOfThree(self, nums1: List[int], nums2: List[int], nums3: List[int]) -> List[int]:
set1 = set(nums1)
set2 = set(nums2)
set3 = set(nums3)
set12 = set1.intersection(set2)
set23 = set2.intersection(set3)
set13 = set1.intersection(set3)
return (set12.union(set23)).union(set13)
|
two-out-of-three
|
python3, easy set solution
|
sirenescx
| 3
| 263
|
two out of three
| 2,032
| 0.726
|
Easy
| 28,258
|
https://leetcode.com/problems/two-out-of-three/discuss/2138556/PYTHON-or-Simple-python-solution
|
class Solution:
def twoOutOfThree(self, nums1: List[int], nums2: List[int], nums3: List[int]) -> List[int]:
countMap = {}
for i in set(nums1):
countMap[i] = 1 + countMap.get(i, 0)
for i in set(nums2):
countMap[i] = 1 + countMap.get(i, 0)
for i in set(nums3):
countMap[i] = 1 + countMap.get(i, 0)
res = []
for i in countMap:
if countMap[i] >= 2:
res.append(i)
return res
|
two-out-of-three
|
PYTHON | Simple python solution
|
shreeruparel
| 2
| 152
|
two out of three
| 2,032
| 0.726
|
Easy
| 28,259
|
https://leetcode.com/problems/two-out-of-three/discuss/1859650/Python-efficient-solution
|
class Solution:
def twoOutOfThree(self, nums1: List[int], nums2: List[int], nums3: List[int]) -> List[int]:
all_distinct = set(nums1 + nums2 + nums3)
count = 0
res = []
for i in all_distinct:
if i in nums1:
count += 1
if i in nums2:
count += 1
if i in nums3:
count += 1
if count >= 2:
res.append(i)
count = 0
return res
|
two-out-of-three
|
Python efficient solution
|
alishak1999
| 1
| 104
|
two out of three
| 2,032
| 0.726
|
Easy
| 28,260
|
https://leetcode.com/problems/two-out-of-three/discuss/1566419/Python3-solution-faster-than-99.04-Solutions
|
class Solution:
def twoOutOfThree(self, nums1: List[int], nums2: List[int], nums3: List[int]) -> List[int]:
arr = []
arr.extend(list(set(nums1)))
arr.extend(list(set(nums2)))
arr.extend(list(set(nums3)))
hm = {}
for num in arr:
if num in hm:
hm[num] += 1
else:
hm[num] = 1
return [key for key,val in hm.items() if val > 1]
|
two-out-of-three
|
Python3 solution faster than 99.04% Solutions
|
risabhmishra19
| 1
| 136
|
two out of three
| 2,032
| 0.726
|
Easy
| 28,261
|
https://leetcode.com/problems/two-out-of-three/discuss/1514549/Python3-One-line
|
class Solution:
def twoOutOfThree(self, nums1: List[int], nums2: List[int], nums3: List[int]) -> List[int]:
return list(set(nums1) & set(nums2) | set(nums1) & set(nums3) | set(nums2) & set(nums3))
|
two-out-of-three
|
Python3 One line
|
frolovdmn
| 1
| 92
|
two out of three
| 2,032
| 0.726
|
Easy
| 28,262
|
https://leetcode.com/problems/two-out-of-three/discuss/2812606/easy
|
class Solution:
def twoOutOfThree(self, nums1: List[int], nums2: List[int], nums3: List[int]) -> List[int]:
nums1 = set(nums1)
nums2 = set(nums2)
nums3 = set(nums3)
return list((nums1 & nums2) | (nums2 & nums3) | (nums3 & nums1))
|
two-out-of-three
|
easy
|
nishithakonuganti
| 0
| 2
|
two out of three
| 2,032
| 0.726
|
Easy
| 28,263
|
https://leetcode.com/problems/two-out-of-three/discuss/2800292/python-or-easy-to-understand-or-default-dict
|
class Solution:
def twoOutOfThree(self, nums1: List[int], nums2: List[int], nums3: List[int]) -> List[int]:
h = collections.defaultdict(int)
for item in set(nums1):
h[item] += 1
for item in set(nums2):
h[item] += 1
for item in set(nums3):
h[item] += 1
return [item for item in h if h[item] > 1]
|
two-out-of-three
|
python | easy to understand | default dict
|
IAMdkk
| 0
| 3
|
two out of three
| 2,032
| 0.726
|
Easy
| 28,264
|
https://leetcode.com/problems/two-out-of-three/discuss/2781234/Python-set-intersection-and-union
|
class Solution:
def twoOutOfThree(self, nums1: List[int], nums2: List[int], nums3: List[int]) -> List[int]:
nums1, nums2, nums3 = set(nums1), set(nums2), set(nums3)
answer = list(nums1.intersection(nums2).union(nums2.intersection(nums3)).union(nums1.intersection(nums3)))
return answer
|
two-out-of-three
|
Python set, intersection and union
|
Osama_Qutait
| 0
| 5
|
two out of three
| 2,032
| 0.726
|
Easy
| 28,265
|
https://leetcode.com/problems/two-out-of-three/discuss/2736096/python-one-line-solution-99.63-faster
|
class Solution:
def twoOutOfThree(self, nums1: List[int], nums2: List[int], nums3: List[int]) -> List[int]:
return list(set(nums1)&set(nums2) | set(nums1)&set(nums3) | set(nums2)&set(nums3))
|
two-out-of-three
|
python one line solution 99.63% faster
|
arifkhan1990
| 0
| 13
|
two out of three
| 2,032
| 0.726
|
Easy
| 28,266
|
https://leetcode.com/problems/two-out-of-three/discuss/2730794/Very-simple-and-intuitive-solution-using-Python-sets
|
class Solution:
def twoOutOfThree(self, nums1: List[int], nums2: List[int], nums3: List[int]) -> List[int]:
s1 = set(nums1)
s2 = set(nums2)
s3 = set(nums3)
i12 = s1.intersection(s2)
i23 = s2.intersection(s3)
i13 = s1.intersection(s3)
return list(i12.union(i23).union(i13))
|
two-out-of-three
|
Very simple and intuitive solution using Python sets
|
thematrixmaster
| 0
| 3
|
two out of three
| 2,032
| 0.726
|
Easy
| 28,267
|
https://leetcode.com/problems/two-out-of-three/discuss/2707042/Using-set()
|
class Solution:
def twoOutOfThree(self, nums1: List[int], nums2: List[int], nums3: List[int]) -> List[int]:
s1,s2,s3 = set(nums1),set(nums2),set(nums3)
return (s1&s2) | (s2&s3) | (s1&s3)
|
two-out-of-three
|
Using set()
|
sanjeevpathak
| 0
| 3
|
two out of three
| 2,032
| 0.726
|
Easy
| 28,268
|
https://leetcode.com/problems/two-out-of-three/discuss/2705896/Easy-using-counters-and-set
|
class Solution:
def twoOutOfThree(self, nums1: List[int], nums2: List[int], nums3: List[int]) -> List[int]:
nums1=list(set(nums1))
nums2=list(set(nums2))
nums3=list(set(nums3))
d=nums1+nums2+nums3
dc=Counter(d)
res=[]
for i,j in dc.items():
if(j>1):
res.append(i)
return res
|
two-out-of-three
|
Easy using counters and set
|
Raghunath_Reddy
| 0
| 8
|
two out of three
| 2,032
| 0.726
|
Easy
| 28,269
|
https://leetcode.com/problems/two-out-of-three/discuss/2702297/Python-solution-clean-code-with-full-comments.-95.68-speed
|
class Solution:
def twoOutOfThree(self, nums1: List[int], nums2: List[int], nums3: List[int]) -> List[int]:
a = list_to_set(nums1)
b = list_to_set(nums2)
c = list_to_set(nums3)
return compare_two_sets(a, b) | compare_two_sets(a, c) | compare_two_sets(b, c)
# Define a method that convert a list into a set.
def list_to_set(nums_x: List[int]):
set_x = set()
for i in nums_x:
set_x.add(i)
return set_x
# Define a method that take two sets and returns a set of intersection elements of both sets.
def compare_two_sets(s1, s2):
return set(s1.intersection(s2))
# Runtime: 75 ms, faster than 95.68% of Python3 online submissions for Two Out of Three.
# Memory Usage: 13.9 MB, less than 83.05% of Python3 online submissions for Two Out of Three.
# If you like my work and found it helpful, then I'll appreciate a like. Thanks!
|
two-out-of-three
|
Python solution, clean code with full comments. 95.68% speed
|
375d
| 0
| 24
|
two out of three
| 2,032
| 0.726
|
Easy
| 28,270
|
https://leetcode.com/problems/two-out-of-three/discuss/2643902/100-EASY-TO-UNDERSTANDSIMPLECLEAN
|
class Solution:
def twoOutOfThree(self, nums1: List[int], nums2: List[int], nums3: List[int]) -> List[int]:
output = []
for i in nums1:
if i in nums2 or i in nums3:
if i not in output:
output.append(i)
for j in nums2:
if j in nums3 or j in nums1:
if j not in output:
output.append(j)
return output
|
two-out-of-three
|
🔥100% EASY TO UNDERSTAND/SIMPLE/CLEAN🔥
|
YuviGill
| 0
| 51
|
two out of three
| 2,032
| 0.726
|
Easy
| 28,271
|
https://leetcode.com/problems/two-out-of-three/discuss/2640209/Python3-One-Liner
|
class Solution:
def twoOutOfThree(self, nums1: List[int], nums2: List[int], nums3: List[int]) -> List[int]:
return [k for k, c in Counter(list(set(nums1))+list(set(nums2))+list(set(nums3))).items() if c>1]
|
two-out-of-three
|
Python3 One Liner
|
godshiva
| 0
| 3
|
two out of three
| 2,032
| 0.726
|
Easy
| 28,272
|
https://leetcode.com/problems/two-out-of-three/discuss/2581512/Python-85-Faster-East-to-Understand-Breakdown
|
class Solution:
def twoOutOfThree(self, nums1: List[int], nums2: List[int], nums3: List[int]) -> List[int]:
#distinct list to iterate
dlist = list(set(nums1+nums2+nums3))
#concate list to check, distinct sublist
clist = list(set(nums1))+list(set(nums2))+list(set(nums3))
#output list
olist = []
for num in dlist:
if clist.count(num) >=2:
olist.append(num)
return(olist)
|
two-out-of-three
|
Python 85% Faster - East to Understand Breakdown
|
ovidaure
| 0
| 47
|
two out of three
| 2,032
| 0.726
|
Easy
| 28,273
|
https://leetcode.com/problems/two-out-of-three/discuss/2545039/Python-Scalable-Solution-(without-Sets)
|
class Solution:
def twoOutOfThree(self, nums1: List[int], nums2: List[int], nums3: List[int], minCount=2) -> List[int]:
# make a list of array (so this function also works for n number of arrays)
nums_list = [nums1, nums2, nums3]
# make an array to count the values
counter = [[False]*len(nums_list) for _ in range(100)]
# go over all arrays and count occurences of numbers
for idx, nums in enumerate(nums_list):
for num in nums:
counter[num-1][idx] = True
# make the output
return [num+1 for num, found in enumerate(counter) if sum(found) >= minCount]
|
two-out-of-three
|
[Python] - Scalable Solution (without Sets)
|
Lucew
| 0
| 18
|
two out of three
| 2,032
| 0.726
|
Easy
| 28,274
|
https://leetcode.com/problems/two-out-of-three/discuss/2542544/Python-fast-solution-using-set-intersection-and-union
|
class Solution:
def twoOutOfThree(self, nums1: List[int], nums2: List[int], nums3: List[int]) -> List[int]:
set_nums1 = set(nums1)
set_nums2 = set(nums2)
set_nums3 = set(nums3)
intersect1 = set_nums1.intersection(set_nums2)
intersect2 = set_nums1.intersection(set_nums3)
intersect3 = set_nums2.intersection(set_nums3)
union_all = intersect1.union(intersect2, intersect3)
return list(union_all)
|
two-out-of-three
|
Python fast solution using set, intersection, and union
|
samanehghafouri
| 0
| 23
|
two out of three
| 2,032
| 0.726
|
Easy
| 28,275
|
https://leetcode.com/problems/two-out-of-three/discuss/2522189/Simple-python-solution
|
class Solution:
def twoOutOfThree(self, nums1: List[int], nums2: List[int], nums3: List[int]) -> List[int]:
nums = list(set(nums1))+list(set(nums2))+list(set(nums3))
dic = Counter(nums)
res = []
for k,v in dic.items():
if v >= 2:
res.append(k)
return res
|
two-out-of-three
|
Simple python solution
|
aruj900
| 0
| 37
|
two out of three
| 2,032
| 0.726
|
Easy
| 28,276
|
https://leetcode.com/problems/two-out-of-three/discuss/2418356/Using-Set-Counter-and-list-comprehension-using-Python
|
class Solution:
def twoOutOfThree(self, nums1: List[int], nums2: List[int], nums3: List[int]) -> List[int]:
n1 = list(set(nums1))
n2 = list(set(nums2))
n3 = list(set(nums3))
n1.extend(n2)
n1.extend(n3)
ct = Counter(n1)
res = [k for k, v in ct.items() if v >= 2]
return res
|
two-out-of-three
|
Using Set, Counter and list comprehension using Python
|
ankurbhambri
| 0
| 28
|
two out of three
| 2,032
| 0.726
|
Easy
| 28,277
|
https://leetcode.com/problems/two-out-of-three/discuss/2378871/Python-easy-solution-using-List-and-set
|
class Solution:
def twoOutOfThree(self, nums1: List[int], nums2: List[int], nums3: List[int]) -> List[int]:
ans=[]
s1=list(set(nums1))
s2=list(set(nums2))
s3=list(set(nums3))
for i in s1:
if i in s2 or i in s3:
ans.append(i)
for j in s2:
if j in s1 or j in s3:
ans.append(j)
for k in s3:
if k in s2 or k in s1:
ans.append(k)
return list(set(ans))
|
two-out-of-three
|
Python easy solution using List and set
|
keertika27
| 0
| 27
|
two out of three
| 2,032
| 0.726
|
Easy
| 28,278
|
https://leetcode.com/problems/two-out-of-three/discuss/2350306/Python-or-Set-or-HashMap
|
class Solution:
def twoOutOfThree(self, nums1: List[int], nums2: List[int], nums3: List[int]) -> List[int]:
hash_map={}
for i in set(nums1):
hash_map[i]=1+hash_map.get(i,0)
for i in set(nums2):
hash_map[i]=1+hash_map.get(i,0)
for i in set(nums3):
hash_map[i]=1+hash_map.get(i,0)
return [i for i in hash_map if hash_map[i]>=2]
|
two-out-of-three
|
Python | Set | HashMap
|
dinesh1898
| 0
| 20
|
two out of three
| 2,032
| 0.726
|
Easy
| 28,279
|
https://leetcode.com/problems/two-out-of-three/discuss/2232602/PYTHON-O(n)-USING-SETS
|
class Solution:
def twoOutOfThree(self, nums1: List[int], nums2: List[int], nums3: List[int]) -> List[int]:
s1 = set(nums1)
s2 = set(nums2)
s3 = set(nums3)
hash_map = {}
for i in s1:
hash_map[i] = 1
for i in s2:
if i in hash_map:
hash_map[i] += 1
else:
hash_map[i] = 1
for i in s3:
if i in hash_map:
hash_map[i] += 1
ans = [i for i in hash_map if hash_map[i] >= 2]
return ans
|
two-out-of-three
|
PYTHON O(n) USING SETS
|
akashp2001
| 0
| 49
|
two out of three
| 2,032
| 0.726
|
Easy
| 28,280
|
https://leetcode.com/problems/two-out-of-three/discuss/2090093/Python-oneliner
|
class Solution:
def twoOutOfThree(self, n1: List[int], n2: List[int], n3: List[int]) -> List[int]:
return {item for sublist in [set(n2)&set(n3), set(n1)&set(n2), set(n1)&set(n3)] for item in sublist}
|
two-out-of-three
|
Python oneliner
|
StikS32
| 0
| 65
|
two out of three
| 2,032
| 0.726
|
Easy
| 28,281
|
https://leetcode.com/problems/two-out-of-three/discuss/2018781/python3-One-Line-Solution
|
class Solution:
def twoOutOfThree(self, nums1: List[int], nums2: List[int], nums3: List[int]) -> List[int]:
return (set(nums1) & set(nums2)) | (set(nums1) & set(nums3)) | (set(nums2) & set(nums3))
|
two-out-of-three
|
[python3] One-Line Solution
|
terrencetang
| 0
| 39
|
two out of three
| 2,032
| 0.726
|
Easy
| 28,282
|
https://leetcode.com/problems/two-out-of-three/discuss/2001635/Whacky-list-comp-solution
|
class Solution:
def twoOutOfThree(self, nums1: List[int], nums2: List[int], nums3: List[int]) -> List[int]:
nums = list(set(nums1 + nums2 + nums3))
return [n for n in nums if (n in nums1 and (n in nums2 or n in nums3) or (n in nums2 and n in nums3))]
|
two-out-of-three
|
Whacky list comp solution
|
andrewnerdimo
| 0
| 20
|
two out of three
| 2,032
| 0.726
|
Easy
| 28,283
|
https://leetcode.com/problems/two-out-of-three/discuss/1938021/easy-python-code
|
class Solution:
def twoOutOfThree(self, nums1: List[int], nums2: List[int], nums3: List[int]) -> List[int]:
n = list(set(nums1+nums2+nums3))
output = []
for i in n:
if (i in nums1 and (i in nums2 or i in nums3)) or (i in nums2 and i in nums3):
output.append(i)
return output
|
two-out-of-three
|
easy python code
|
dakash682
| 0
| 52
|
two out of three
| 2,032
| 0.726
|
Easy
| 28,284
|
https://leetcode.com/problems/two-out-of-three/discuss/1937037/Python-Solution-%2B-One-Liner-or-Set-or-Intersection-and-Union
|
class Solution:
def twoOutOfThree(self, nums1, nums2, nums3):
set1, set2, set3 = set(nums1), set(nums2), set(nums3)
set12 = set1.intersection(set2)
set23 = set2.intersection(set3)
set13 = set1.intersection(set3)
return set12.union(set23).union(set13)
|
two-out-of-three
|
Python - Solution + One-Liner | Set | Intersection and Union
|
domthedeveloper
| 0
| 47
|
two out of three
| 2,032
| 0.726
|
Easy
| 28,285
|
https://leetcode.com/problems/two-out-of-three/discuss/1937037/Python-Solution-%2B-One-Liner-or-Set-or-Intersection-and-Union
|
class Solution:
def twoOutOfThree(self, nums1, nums2, nums3):
set1, set2, set3 = set(nums1), set(nums2), set(nums3)
set12 = set1 & set2
set23 = set2 & set3
set13 = set1 & set3
return set12 | set23 | set13
|
two-out-of-three
|
Python - Solution + One-Liner | Set | Intersection and Union
|
domthedeveloper
| 0
| 47
|
two out of three
| 2,032
| 0.726
|
Easy
| 28,286
|
https://leetcode.com/problems/two-out-of-three/discuss/1937037/Python-Solution-%2B-One-Liner-or-Set-or-Intersection-and-Union
|
class Solution:
def twoOutOfThree(self, nums1, nums2, nums3):
set1, set2, set3 = set(nums1), set(nums2), set(nums3)
return set1 & set2 | set2 & set3 | set1 & set3
|
two-out-of-three
|
Python - Solution + One-Liner | Set | Intersection and Union
|
domthedeveloper
| 0
| 47
|
two out of three
| 2,032
| 0.726
|
Easy
| 28,287
|
https://leetcode.com/problems/two-out-of-three/discuss/1937037/Python-Solution-%2B-One-Liner-or-Set-or-Intersection-and-Union
|
class Solution:
def twoOutOfThree(self, nums1, nums2, nums3):
return (lambda s1,s2,s3 : s1&s2 | s2&s3 | s1&s3)(set(nums1),set(nums2),set(nums3))
|
two-out-of-three
|
Python - Solution + One-Liner | Set | Intersection and Union
|
domthedeveloper
| 0
| 47
|
two out of three
| 2,032
| 0.726
|
Easy
| 28,288
|
https://leetcode.com/problems/two-out-of-three/discuss/1825044/1-Line-Python-Solution-oror-75-Faster-oror-Memory-less-than-70
|
class Solution:
def twoOutOfThree(self, nums1: List[int], nums2: List[int], nums3: List[int]) -> List[int]:
return [i for i,v in Counter([*set(nums1), *set(nums2), *set(nums3)]).most_common() if v>=2]
|
two-out-of-three
|
1-Line Python Solution || 75% Faster || Memory less than 70%
|
Taha-C
| 0
| 70
|
two out of three
| 2,032
| 0.726
|
Easy
| 28,289
|
https://leetcode.com/problems/two-out-of-three/discuss/1819465/Python-Easy-to-Understand-Hashmap-Solution-for-beginners
|
class Solution:
def twoOutOfThree(self, nums1: List[int], nums2: List[int], nums3: List[int]) -> List[int]:
dic1 = {}
dic2 = {}
dic3 = {}
lst = []
for n1 in nums1:
if n1 in dic1:
dic1[n1]+=1
else:
dic1[n1]=1
for n2 in nums2:
if n2 in dic2:
dic2[n2]+=1
else:
dic2[n2]=1
for n3 in nums3:
if n3 in dic3:
dic3[n3]+=1
else:
dic3[n3]=1
for k1 in dic1:
if k1 in dic2 or k1 in dic3:
x = k1
lst.append(k1)
for k2 in dic2:
if k2 in dic3 or k2 in dic1:
x = k2
lst.append(k2)
for k3 in dic3:
if k3 in dic1 or k3 in dic2:
x = k3
lst.append(k3)
return set(lst)
|
two-out-of-three
|
Python Easy to Understand Hashmap Solution for beginners
|
Ron99
| 0
| 65
|
two out of three
| 2,032
| 0.726
|
Easy
| 28,290
|
https://leetcode.com/problems/two-out-of-three/discuss/1537793/Hashing-%3A-A-beautiful-concept-greater-Thought-Process-Explained
|
class Solution:
def twoOutOfThree(self, nums1: List[int], nums2: List[int], nums3: List[int]) -> List[int]:
#return a distinct array containing all the values
#that are present in at least two out of the three arrays.
#NOTE - values can be in any order
d1 = {} #will hold the elements and its frequencies of nums1
d2 = {} #will hold the elements and its frequences of nums2
d3 = {} #will hold the elements and its frequencies of nums3
#populating d1 with elements of nums1 -- consumes O(N) Time
for i in nums1:
if i in d1:
d1[i] += 1
else:
d1[i] = 1
#populating d2 with elements of nums2 -- consumes O(N) Time
for i in nums2:
if i in d2:
d2[i] += 1
else:
d2[i] = 1
#populating d3 with elements of nums3 -- consumes O(N) Time
for i in nums3:
if i in d3:
d3[i] += 1
else:
d3[i] = 1
output = [] #this will hold our output
#Core Logic comes here now -->
#We can iterate over each dictionary and check
#if the element is present in atleast 1 other
#dictionary or not. If it is, we add it to our output.
for element in d1:
# consumes O(N) Time
#note : looking up an element in a dictionary is O(1)
if element in d2 or element in d3:
output.append(element)
for element in d2: # consumes O(N) Time
if element in d1 or element in d3:
output.append(element)
for element in d3: # consumes O(N) Time
if element in d2 or element in d1:
output.append(element)
answer = set(output) #to ensure no duplicates are taken
return list(answer) #converts the set to our required form of output
|
two-out-of-three
|
Hashing : A beautiful concept --> Thought Process Explained
|
aarushsharmaa
| 0
| 114
|
two out of three
| 2,032
| 0.726
|
Easy
| 28,291
|
https://leetcode.com/problems/two-out-of-three/discuss/1528452/Python3-Two-kind-of-solutions
|
class Solution:
def twoOutOfThree(self, nums1: List[int], nums2: List[int], nums3: List[int]) -> List[int]:
nums1 = set(nums1)
nums2 = set(nums2)
nums3 = set(nums3)
d = {}
ans = []
for num in nums1:
if num not in d:
d[num] = 0
d[num] += 1
for num in nums2:
if num not in d:
d[num] = 0
d[num] += 1
for num in nums3:
if num not in d:
d[num] = 0
d[num] += 1
for key in d:
if d[key] >= 2:
ans.append(key)
return ans
|
two-out-of-three
|
[Python3] Two kind of solutions
|
maosipov11
| 0
| 73
|
two out of three
| 2,032
| 0.726
|
Easy
| 28,292
|
https://leetcode.com/problems/two-out-of-three/discuss/1528452/Python3-Two-kind-of-solutions
|
class Solution:
def twoOutOfThree(self, nums1: List[int], nums2: List[int], nums3: List[int]) -> List[int]:
nums1 = set(nums1)
nums2 = set(nums2)
nums3 = set(nums3)
return list((nums1&nums2) | (nums2&nums3) | (nums1&nums3))
|
two-out-of-three
|
[Python3] Two kind of solutions
|
maosipov11
| 0
| 73
|
two out of three
| 2,032
| 0.726
|
Easy
| 28,293
|
https://leetcode.com/problems/two-out-of-three/discuss/1523046/Python-or-list-or-set
|
class Solution:
def twoOutOfThree(self, nums1: List[int], nums2: List[int], nums3: List[int]) -> List[int]:
out = []
for key in set(nums1):
if key in set(nums2) or key in set(nums3):
out.append(key)
for key in set(nums2):
if key in set(nums3) and key not in out:
out.append(key)
return out
|
two-out-of-three
|
Python | list | set
|
_rust
| 0
| 69
|
two out of three
| 2,032
| 0.726
|
Easy
| 28,294
|
https://leetcode.com/problems/two-out-of-three/discuss/1520972/Python-Solution-or-Using-Dictionary
|
class Solution:
def twoOutOfThree(self, nums1: List[int], nums2: List[int], nums3: List[int]) -> List[int]:
a = []
table = defaultdict(int)
# to remove duplicates from each list
first = list(OrderedDict.fromkeys(nums1))
second = list(OrderedDict.fromkeys(nums2))
third = list(OrderedDict.fromkeys(nums3))
nums = first + second + third
for i in nums:
table[i] = table[i] + 1
if (table[i] >= 2) and (i not in a):
a.append(i)
return a
|
two-out-of-three
|
Python Solution | Using Dictionary
|
Shreya19595
| 0
| 101
|
two out of three
| 2,032
| 0.726
|
Easy
| 28,295
|
https://leetcode.com/problems/two-out-of-three/discuss/1514408/Python-one-liner
|
class Solution:
def twoOutOfThree(self, nums1: List[int], nums2: List[int], nums3: List[int]) -> List[int]:
return [v for v, c in Counter(itertools.chain(set(nums1), set(nums2), set(nums3))).items() if c >=2]
|
two-out-of-three
|
Python, one-liner
|
blue_sky5
| 0
| 64
|
two out of three
| 2,032
| 0.726
|
Easy
| 28,296
|
https://leetcode.com/problems/minimum-operations-to-make-a-uni-value-grid/discuss/1513319/Python3-median-4-line
|
class Solution:
def minOperations(self, grid: List[List[int]], x: int) -> int:
vals = [x for row in grid for x in row]
if len(set(val%x for val in vals)) > 1: return -1 # impossible
median = sorted(vals)[len(vals)//2] # O(N) possible via "quick select"
return sum(abs(val - median)//x for val in vals)
|
minimum-operations-to-make-a-uni-value-grid
|
[Python3] median 4-line
|
ye15
| 21
| 1,100
|
minimum operations to make a uni value grid
| 2,033
| 0.524
|
Medium
| 28,297
|
https://leetcode.com/problems/minimum-operations-to-make-a-uni-value-grid/discuss/1785741/Python3-Why-median-is-optimal-or-Detailed-Explanation
|
class Solution:
def minOperations(self, grid: List[List[int]], x: int) -> int:
li = []
# convert matrix to array, we dont care about the structure itself. We just want the values
for val in grid:
li+= val
# sort the array
li.sort()
# get the middle value, which is equidistant from both sides
median = li[len(li)//2]
ops = 0
# run the loop over all the elements to calculate the number of operations needed
for val in li:
# this is the condtion which determines if our number can reach the other number with adding/subtracting k
if abs(val-median)%x != 0:
return -1
ops += abs(val-median)//x
return ops
|
minimum-operations-to-make-a-uni-value-grid
|
[Python3] Why median is optimal | Detailed Explanation
|
Apurv_Moroney
| 4
| 278
|
minimum operations to make a uni value grid
| 2,033
| 0.524
|
Medium
| 28,298
|
https://leetcode.com/problems/minimum-operations-to-make-a-uni-value-grid/discuss/1513305/Median-or-Python-or-Simple-Approach-or-Explanation-with-Comments
|
class Solution:
def minOperations(self, grid: List[List[int]], x: int) -> int:
# flatten the numbers
nums = []
for row in grid:
for num in row:
nums.append(num)
# sort and find the median
nums.sort()
n = len(nums)
median = nums[n//2]
# calculate the number of operations required
operations = 0
for num in nums:
diff = abs(median-num)
if diff%x !=0:
return -1
operations += diff//x
return operations
|
minimum-operations-to-make-a-uni-value-grid
|
Median | Python | Simple Approach | Explanation with Comments
|
CaptainX
| 2
| 163
|
minimum operations to make a uni value grid
| 2,033
| 0.524
|
Medium
| 28,299
|
Subsets and Splits
Top 2 Solutions by Upvotes
Identifies the top 2 highest upvoted Python solutions for each problem, providing insight into popular approaches.