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/move-pieces-to-obtain-a-string/discuss/2261423/Python-O(N)-solution-or-Two-pointer-approach-or-Optimized-solution
class Solution: def canChange(self, start: str, target: str) -> bool: d = {} e = {} for i in range(len(start)): if start[i] not in d: d[start[i]] = [i] e[start[i]] = i else: d[start[i]].append(i) if "L" not in e: e["L"] = -1 d["L"] = [] if "R" not in e: e["R"] = -1 d["R"] = [] a = target.count("L") b = target.count("R") if a!=len(d["L"]) or b!=len(d["R"]): return False for i in range(len(target)): if target[i]=="L": if e["L"]>=i and ((e["R"]!=-1 and e["R"]>e["L"]) or e["R"]==-1): if d["L"]: d["L"].pop(0) if d["L"]: e["L"] = d["L"][0] else: e["L"] = -1 else: return False else: return False elif target[i]=="R": if e["R"]<=i and ((e["L"]!=-1 and (e["L"]>i)) or e["L"]==-1): if d["R"]: d["R"].pop(0) if d["R"]: e["R"] = d["R"][0] else: e["R"] = -1 else: False else: return False return True
move-pieces-to-obtain-a-string
Python O(N) solution | Two pointer approach | Optimized solution
AkashHooda
0
28
move pieces to obtain a string
2,337
0.481
Medium
32,100
https://leetcode.com/problems/count-the-number-of-ideal-arrays/discuss/2261351/Python3-freq-table
class Solution: def idealArrays(self, n: int, maxValue: int) -> int: ans = maxValue freq = {x : 1 for x in range(1, maxValue+1)} for k in range(1, n): temp = Counter() for x in freq: for m in range(2, maxValue//x+1): ans += comb(n-1, k)*freq[x] temp[m*x] += freq[x] freq = temp ans %= 1_000_000_007 return ans
count-the-number-of-ideal-arrays
[Python3] freq table
ye15
26
1,500
count the number of ideal arrays
2,338
0.255
Hard
32,101
https://leetcode.com/problems/count-the-number-of-ideal-arrays/discuss/2261965/Python-Freq-Table-Solution-(by-ye15)-with-Explanations
class Solution: def idealArrays(self, n: int, maxValue: int) -> int: MOD = 10 ** 9 + 7 ans = maxValue freq = {x: 1 for x in range(1, maxValue + 1)} for k in range(1, n): if not freq: break nxt = collections.defaultdict(int) for x in freq: for m in range(2, maxValue // x + 1): ans += math.comb(n - 1, k) * freq[x] nxt[m * x] += freq[x] freq = nxt ans %= MOD return ans
count-the-number-of-ideal-arrays
[Python] Freq Table Solution (by ye15) with Explanations
xil899
3
144
count the number of ideal arrays
2,338
0.255
Hard
32,102
https://leetcode.com/problems/count-the-number-of-ideal-arrays/discuss/2346184/Runtime%3A-128-ms-or-Memory-Usage%3A-14.4-MB
class Solution: def idealArrays(self, n: int, maxValue: int) -> int: MOD = 10 ** 9 + 7 my_combs = [1, n] # my_combs[k] = n+k-1 choose k for k in range(2, 21): my_combs.append(((n + k - 1) * my_combs[-1]) // k) for x in range(len(my_combs)): my_combs[x] %= MOD primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97] fac_prods = [1] * (maxValue + 1) ans = 1 for x in primes: if x > maxValue: break mult = x ii = 1 comb_prodder = my_combs[ii] while mult <= maxValue: for nm in range(mult, mult * x, mult): if nm > maxValue: break for y in range(nm, maxValue + 1, mult * x): fac_prods[y] = fac_prods[y] * comb_prodder % MOD mult *= x ii += 1 comb_prodder = my_combs[ii] for i in range(2, maxValue + 1): if fac_prods[i] == 1 and i > 100: for y in range(i, maxValue + 1, i): fac_prods[y] *= n ans += fac_prods[i] % MOD return ans % MOD
count-the-number-of-ideal-arrays
Runtime: 128 ms | Memory Usage: 14.4 MB
vimla_kushwaha
1
80
count the number of ideal arrays
2,338
0.255
Hard
32,103
https://leetcode.com/problems/count-the-number-of-ideal-arrays/discuss/2462204/Python3-details-guide-and-math.
class Solution: def idealArrays(self, m: int, n: int) -> int: def dec(num): i = 2 ct = Counter() while i <= num//i: if num % i == 0: j = 0 while num % i == 0: num //= i j += 1 ct[i] = j i += 1 if num!=1: ct[num] += 1 return ct mod = 10**9 + 7 res = 1 for i in range(2,n+1): ctr = dec(i) p = 1 for key in ctr: ct = ctr[key] p = (p * comb(m+ct-1, m-1)) % mod res = (res + p) % mod return res
count-the-number-of-ideal-arrays
Python3 details guide and math.
liulaoye135
0
71
count the number of ideal arrays
2,338
0.255
Hard
32,104
https://leetcode.com/problems/count-the-number-of-ideal-arrays/discuss/2261404/Stars-and-Bars-Choosing-non-decreasing-subsequences-of-exponents-of-primes
class Solution: def __init__(self): self.MOD = 1000000007 self.memo = {0: 1} self.fact = [1 for i in range(10100)] def inv(self, x): if x>1: return self.inv(self.MOD%x)*(self.MOD-self.MOD//x)%self.MOD else: return x def choose(self, n, k): return ((self.fact[n] * self.inv(self.fact[n-k]) ) % self.MOD )* self.inv(self.fact[k]) %self.MOD def factors(self, x): a = [] i = 2 while x > 1: re = 0 while x % i == 0: re += 1 x //= i if re: a.append(re) i += 1 return a def h(self, v): if v in self.memo: return self.memo[v] self.memo[v] = self.choose(v+self.c, self.c) return self.memo[v] def idealArrays(self, n: int, maxValue: int) -> int: s = 0 self.c = n-1 for i in range(2,10100): self.fact[i] = self.fact[i-1] * i % self.MOD for i in range(1, maxValue+1): cur = 1 fa = self.factors(i) for f in fa: cur = (cur*self.h(f))%self.MOD s = (s+cur)%self.MOD return s
count-the-number-of-ideal-arrays
Stars & Bars - Choosing non-decreasing subsequences of exponents of primes
lukewu28
0
90
count the number of ideal arrays
2,338
0.255
Hard
32,105
https://leetcode.com/problems/maximum-number-of-pairs-in-array/discuss/2472693/Python-Elegant-and-Short-or-Two-lines-or-99.91-faster-or-Counter
class Solution: """ Time: O(n) Memory: O(n) """ def numberOfPairs(self, nums: List[int]) -> List[int]: pairs = sum(cnt // 2 for cnt in Counter(nums).values()) return [pairs, len(nums) - 2 * pairs]
maximum-number-of-pairs-in-array
Python Elegant & Short | Two lines | 99.91% faster | Counter
Kyrylo-Ktl
5
171
maximum number of pairs in array
2,341
0.766
Easy
32,106
https://leetcode.com/problems/maximum-number-of-pairs-in-array/discuss/2472693/Python-Elegant-and-Short-or-Two-lines-or-99.91-faster-or-Counter
class Solution: """ Time: O(n) Memory: O(n) """ def numberOfPairs(self, nums: List[int]) -> List[int]: pairs = 0 single = set() for num in nums: if num in single: single.remove(num) pairs += 1 else: single.add(num) return [pairs, len(single)]
maximum-number-of-pairs-in-array
Python Elegant & Short | Two lines | 99.91% faster | Counter
Kyrylo-Ktl
5
171
maximum number of pairs in array
2,341
0.766
Easy
32,107
https://leetcode.com/problems/maximum-number-of-pairs-in-array/discuss/2659753/Simple-and-Easy-to-Understand-or-Python
class Solution(object): def numberOfPairs(self, nums): hashT = {} for n in nums: if n not in hashT: hashT[n] = 1 else: hashT[n] += 1 pairs, rem = 0, 0 for n in hashT: pairs += (hashT[n] // 2) rem += (hashT[n] % 2) return [pairs, rem]
maximum-number-of-pairs-in-array
Simple and Easy to Understand | Python
its_krish_here
1
91
maximum number of pairs in array
2,341
0.766
Easy
32,108
https://leetcode.com/problems/maximum-number-of-pairs-in-array/discuss/2426696/Python-easy-solution-O(n)
class Solution: def numberOfPairs(self, nums: List[int]) -> List[int]: dict_numbers = {} for i in nums: if i not in dict_numbers: dict_numbers[i] = 1 else: dict_numbers[i] += 1 count_pairs = 0 count_leftovers = 0 result = [] for k, v in dict_numbers.items(): if v % 2 != 0: count_pairs += v // 2 count_leftovers += v % 2 else: count_pairs += v // 2 result.append(count_pairs) result.append(count_leftovers) return result
maximum-number-of-pairs-in-array
Python easy solution O(n)
samanehghafouri
1
34
maximum number of pairs in array
2,341
0.766
Easy
32,109
https://leetcode.com/problems/maximum-number-of-pairs-in-array/discuss/2350229/Python-easy-solution-or-Beginner-Friendly-or-HashMap
class Solution: def numberOfPairs(self, nums: List[int]) -> List[int]: hash_map=Counter(nums) count=0 for i in hash_map: count+=hash_map[i]%2 return [(len(nums)-count)//2,count]
maximum-number-of-pairs-in-array
Python easy solution | Beginner Friendly | HashMap
dinesh1898
1
42
maximum number of pairs in array
2,341
0.766
Easy
32,110
https://leetcode.com/problems/maximum-number-of-pairs-in-array/discuss/2292842/Python3-2-line
class Solution: def numberOfPairs(self, nums: List[int]) -> List[int]: freq = Counter(nums) return [sum(x//2 for x in freq.values()), sum(x&amp;1 for x in freq.values())]
maximum-number-of-pairs-in-array
[Python3] 2-line
ye15
1
40
maximum number of pairs in array
2,341
0.766
Easy
32,111
https://leetcode.com/problems/maximum-number-of-pairs-in-array/discuss/2822324/Python-Solution-%3A)
class Solution: def numberOfPairs(self, nums: List[int]) -> List[int]: pairs = 0 seen = set() for num in nums: if num in seen: seen.remove(num) pairs += 1 continue seen.add(num) return [pairs, len(seen)]
maximum-number-of-pairs-in-array
Python Solution :)
havvoc
0
1
maximum number of pairs in array
2,341
0.766
Easy
32,112
https://leetcode.com/problems/maximum-number-of-pairs-in-array/discuss/2783411/Simple-Python-Solution-or-Easy-and-Fast-or-Explained
class Solution(object): def numberOfPairs(self, nums): """ :type nums: List[int] :rtype: List[int] """ res = [0, 0] while len(nums) > 1: current = nums[0] if current in nums[1:]: res[0] += 1 nums = nums[1:] nums.remove(current) else: res[1] += 1 nums = nums[1:] res[1] += len(nums) return res
maximum-number-of-pairs-in-array
Simple Python Solution | Easy & Fast | Explained
dnvavinash
0
1
maximum number of pairs in array
2,341
0.766
Easy
32,113
https://leetcode.com/problems/maximum-number-of-pairs-in-array/discuss/2763780/Python-3-solution-using-dictionary
class Solution: def numberOfPairs(self, nums: List[int]) -> List[int]: pairs = {} ans = 0 left = 0 for i in range(len(nums)): pairs[nums[i]] = nums.count(nums[i]) for i in pairs: ans += pairs[i] // 2 left += pairs[i] % 2 return [ans, left]
maximum-number-of-pairs-in-array
Python 3 solution using dictionary
mr6nie
0
1
maximum number of pairs in array
2,341
0.766
Easy
32,114
https://leetcode.com/problems/maximum-number-of-pairs-in-array/discuss/2676712/Simple-Solution-using-hashmap-oror-Python-oror-Time.C-O(N)
class Solution: def numberOfPairs(self, nums: List[int]) -> List[int]: frequency={} pairs,leftover=0,0 # this 1st loop will count frequnecy of each list element using dictionary(hashmap). for value in nums: if value not in frequency: # if element not present in dictionary it will add the element and make it's frequency frequency[value]=1 else: # if element will be present then it will increase it's frequency by 1. frequency[value]+=1 if frequency[value]==2: # here is the difference from above code, as frequency will be 2 it means pairs will have to increase by 1 according to given question requirements ,so it will be increase by 1 and then we will simply remove that element so next time it will start from 0 and as it will be 2 again and same process will be occur, other wise in last 1 frequency of any element will remain, so next , in return we will simply return sum() of dictionary.values() pairs+=1 del frequency[value] return [pairs,sum(frequency.values())]
maximum-number-of-pairs-in-array
Simple Solution using hashmap || Python || Time.C O(N)
Khalilullah_Nohri
0
18
maximum number of pairs in array
2,341
0.766
Easy
32,115
https://leetcode.com/problems/maximum-number-of-pairs-in-array/discuss/2673665/Python-or-Two-lines-simple
class Solution: def numberOfPairs(self, xs: List[int]) -> List[int]: pairs = sum([v // 2 for v in Counter(xs).values()]) return [pairs, len(xs) - 2 * pairs]
maximum-number-of-pairs-in-array
Python | Two lines, simple
on_danse_encore_on_rit_encore
0
2
maximum number of pairs in array
2,341
0.766
Easy
32,116
https://leetcode.com/problems/maximum-number-of-pairs-in-array/discuss/2605659/Python-Simple-Python-Solution-Using-Dictionary-or-HashMap
class Solution: def numberOfPairs(self, nums: List[int]) -> List[int]: total_elements = len(nums) total_pairs = 0 frequency = {} for i in range(len(nums)): if nums[i] not in frequency: frequency[nums[i]] = [i] else: frequency[nums[i]].append(i) for key in frequency: if len(frequency[key]) > 1: current_pairs = len(frequency[key]) // 2 total_pairs = total_pairs + current_pairs total_elements = total_elements - current_pairs * 2 return [total_pairs, total_elements]
maximum-number-of-pairs-in-array
[ Python ] ✅✅ Simple Python Solution Using Dictionary | HashMap🥳✌👍
ASHOK_KUMAR_MEGHVANSHI
0
83
maximum number of pairs in array
2,341
0.766
Easy
32,117
https://leetcode.com/problems/maximum-number-of-pairs-in-array/discuss/2586947/SIMPLE-PYTHON3-SOLUTION
class Solution: def numberOfPairs(self, nums: List[int]) -> List[int]: ans = [0, 0] sett = list(set(nums)) paircount = 0 acount = 0 for i in sett: count1 = nums.count(i) if count1 >=2 : if count1 %2 == 0: paircount += count1 // 2 else: paircount += (count1-1)//2 acount +=1 else: if count1==1: acount += 1 ans[0], ans[1] = paircount, acount return ans
maximum-number-of-pairs-in-array
✅✔ SIMPLE PYTHON3 SOLUTION ✅✔
rajukommula
0
32
maximum number of pairs in array
2,341
0.766
Easy
32,118
https://leetcode.com/problems/maximum-number-of-pairs-in-array/discuss/2491890/Easy-and-fast-python-solution-without-Counter
class Solution: def numberOfPairs(self, nums: List[int]) -> List[int]: pair = 0 seen = set() for n in nums: if n not in seen: seen.add(n) else: pair += 1 seen.remove(n) return [pair, len(nums)-pair*2]
maximum-number-of-pairs-in-array
Easy and fast python solution without Counter
yhc22593
0
22
maximum number of pairs in array
2,341
0.766
Easy
32,119
https://leetcode.com/problems/maximum-number-of-pairs-in-array/discuss/2423607/Python-No-Counter-or-XOR
class Solution: def numberOfPairs(self, nums: List[int]) -> List[int]: leftover = [0] * 101 i = 0 while i < 0 + len(nums): target = nums[i] leftover[target] ^= 1 i += 1 remains = sum(leftover) return [(len(nums) - remains) // 2, remains]
maximum-number-of-pairs-in-array
[Python] No Counter | XOR
DG_stamper
0
17
maximum number of pairs in array
2,341
0.766
Easy
32,120
https://leetcode.com/problems/maximum-number-of-pairs-in-array/discuss/2385861/Easiest-python-solution
class Solution: def numberOfPairs(self, nums: List[int]) -> List[int]: # Create dictionary by using inbuilt dictionary i.e. Counter # Now traverse through all keys of dict , no. of pair = dict[i]//2 # and not pair is equals to remainder i.e. npair = dict[i]%2 # finally return [pair,npair] dict=Counter(nums) pair=npair=0 for i in dict.keys(): if dict[i]>=2: pair+=dict[i]//2 npair+=dict[i]%2 return [pair,npair]
maximum-number-of-pairs-in-array
Easiest python solution
Aniket_liar07
0
42
maximum number of pairs in array
2,341
0.766
Easy
32,121
https://leetcode.com/problems/maximum-number-of-pairs-in-array/discuss/2381585/Python-easy-solution-for-beginners-using-Counter
class Solution: def numberOfPairs(self, nums: List[int]) -> List[int]: freq = Counter(nums) count_pairs = 0 count_arr_len = 0 for i in freq: if freq[i] % 2 == 0: count_pairs += freq[i] / 2 else: count_pairs += freq[i] // 2 count_arr_len += freq[i] % 2 return [int(count_pairs), count_arr_len]
maximum-number-of-pairs-in-array
Python easy solution for beginners using Counter
alishak1999
0
24
maximum number of pairs in array
2,341
0.766
Easy
32,122
https://leetcode.com/problems/maximum-number-of-pairs-in-array/discuss/2367689/easy-python-solution
class Solution: def numberOfPairs(self, nums: List[int]) -> List[int]: counter, left_over = 0, 0 unique = [] for num in nums : if num not in unique : if nums.count(num) > 1 : counter += nums.count(num)//2 left_over += nums.count(num)%2 else : left_over += 1 unique.append(num) return [counter, left_over]
maximum-number-of-pairs-in-array
easy python solution
sghorai
0
36
maximum number of pairs in array
2,341
0.766
Easy
32,123
https://leetcode.com/problems/maximum-number-of-pairs-in-array/discuss/2362139/Python-in-Easy-way-or-O(N)-or-faster-than-94.55
class Solution: def numberOfPairs(self, nums: List[int]) -> List[int]: cur = [] count = 0 for i in nums: if i in cur: count += 1 cur.remove(i) continue cur.append(i) res = [count, len(cur)] return res
maximum-number-of-pairs-in-array
Python in Easy way | O(N) | faster than 94.55%
YangJenHao
0
26
maximum number of pairs in array
2,341
0.766
Easy
32,124
https://leetcode.com/problems/maximum-number-of-pairs-in-array/discuss/2360038/Python-Solution
class Solution: def numberOfPairs(self, nums: List[int]) -> List[int]: result = [0, 0] for v in Counter(nums).values(): x, y = divmod(v, 2) result[1] += y result[0] += x return result
maximum-number-of-pairs-in-array
Python Solution
hgalytoby
0
18
maximum number of pairs in array
2,341
0.766
Easy
32,125
https://leetcode.com/problems/maximum-number-of-pairs-in-array/discuss/2347176/Python-Solution
class Solution: def numberOfPairs(self, nums: List[int]) -> List[int]: A = collections.Counter(nums) leftOver = 0 pairformed = 0 for num in A.keys(): if A[num] % 2 == 0: pairformed += (A[num]//2) else: leftOver += 1 pairformed += ((A[num]-1)//2) return [pairformed, leftOver]
maximum-number-of-pairs-in-array
Python Solution
yash921
0
27
maximum number of pairs in array
2,341
0.766
Easy
32,126
https://leetcode.com/problems/maximum-number-of-pairs-in-array/discuss/2345530/62-Faster-oror-Easy-Python-Solution
class Solution: def numberOfPairs(self, nums: List[int]) -> List[int]: pairs=0 left=0 l=list(set(nums)) for i in l: c=nums.count(i) if c%2==0: pairs=pairs+(c//2) else: pairs=pairs+((c-1)//2) left=left+1 return [pairs,left]
maximum-number-of-pairs-in-array
62% Faster || Easy Python Solution
keertika27
0
32
maximum number of pairs in array
2,341
0.766
Easy
32,127
https://leetcode.com/problems/maximum-number-of-pairs-in-array/discuss/2324388/Simple-counter
class Solution: def numberOfPairs(self, nums: List[int]) -> List[int]: counter = {} for i in nums: if i in counter: counter[i]+=1 else: counter[i]=1 pair,single=0,0 for i in counter.values(): pair+=i//2 single+=i%2 return [pair,single]
maximum-number-of-pairs-in-array
Simple counter
sunakshi132
0
39
maximum number of pairs in array
2,341
0.766
Easy
32,128
https://leetcode.com/problems/maximum-number-of-pairs-in-array/discuss/2314516/Python-simple-solution
class Solution: def numberOfPairs(self, nums: List[int]) -> List[int]: ans = [0,0] for i in set(nums): if nums.count(i)%2 == 0: ans[0] += nums.count(i)//2 else: ans[0] += nums.count(i)//2 ans[1] += nums.count(i)%2 return ans
maximum-number-of-pairs-in-array
Python simple solution
StikS32
0
19
maximum number of pairs in array
2,341
0.766
Easy
32,129
https://leetcode.com/problems/maximum-number-of-pairs-in-array/discuss/2309663/oror-MY-EASY-PYTHON-SOLUTION-oror
class Solution: def numberOfPairs(self, nums: List[int]) -> List[int]: dic = {} ans = [0,0] for i in nums : if i in dic : dic[i] += 1 else : dic[i] = 1 for i in dic.values() : ans[0] += i//2 ans[1] += i&amp;1 #or --> i % 2 return ans
maximum-number-of-pairs-in-array
|| MY EASY PYTHON SOLUTION ||
rohitkhairnar
0
27
maximum number of pairs in array
2,341
0.766
Easy
32,130
https://leetcode.com/problems/maximum-number-of-pairs-in-array/discuss/2299484/Python-2-lines
class Solution: def numberOfPairs(self, nums: List[int]) -> List[int]: c = Counter(nums).values() return [ sum(v // 2 for v in c), sum(v % 2 for v in c) ]
maximum-number-of-pairs-in-array
Python 2 lines
SmittyWerbenjagermanjensen
0
8
maximum number of pairs in array
2,341
0.766
Easy
32,131
https://leetcode.com/problems/maximum-number-of-pairs-in-array/discuss/2297331/Python-Solution-6-lines
class Solution: def numberOfPairs(self, nums: List[int]) -> List[int]: hmap, result = collections.Counter(nums), [0,0] for k,v in hmap.items(): if v % 2 != 0: result[1] += 1 result[0] += (v//2) return result
maximum-number-of-pairs-in-array
Python Solution [6 lines]
parthberk
0
11
maximum number of pairs in array
2,341
0.766
Easy
32,132
https://leetcode.com/problems/maximum-number-of-pairs-in-array/discuss/2296620/Simple-Python-Solution
class Solution: def numberOfPairs(self, nums: List[int]) -> List[int]: dict, pair, leftover={}, 0, 0 for n in nums: if n in dict: dict[n]+=1 else: dict[n]=1 for d in dict: if dict[d]%2==0: pair+=dict[d]/2 else: leftover+=1 pair+=dict[d]//2 return [int(pair), leftover]
maximum-number-of-pairs-in-array
Simple Python Solution
HadaEn
0
5
maximum number of pairs in array
2,341
0.766
Easy
32,133
https://leetcode.com/problems/maximum-number-of-pairs-in-array/discuss/2295467/One-pass-and-set-for-met-nums-92-speed
class Solution: def numberOfPairs(self, nums: List[int]) -> List[int]: pairs, stack = 0, set() for n in nums: if n in stack: pairs += 1 stack.remove(n) else: stack.add(n) return [pairs, len(stack)]
maximum-number-of-pairs-in-array
One pass and set for met nums, 92% speed
EvgenySH
0
9
maximum number of pairs in array
2,341
0.766
Easy
32,134
https://leetcode.com/problems/maximum-number-of-pairs-in-array/discuss/2294783/Python3-Simple-Solution
class Solution: def numberOfPairs(self, nums: List[int]) -> List[int]: d = {} c1 = 0 c2 = 0 for num in nums: d[num] = d.get(num, 0) + 1 if d[num] == 2: c1 += 1 d[num] = 0 for val in d.values(): if val != 0: c2 += 1 return [c1, c2]
maximum-number-of-pairs-in-array
Python3 Simple Solution
mediocre-coder
0
8
maximum number of pairs in array
2,341
0.766
Easy
32,135
https://leetcode.com/problems/maximum-number-of-pairs-in-array/discuss/2293611/Python-Using-Counter-and-divmod
class Solution: def numberOfPairs(self, nums: List[int]) -> List[int]: tmp = Counter(nums) res = 0 left = 0 for key in tmp: i, j = divmod(tmp[key], 2) res += i left += j return [res, left]
maximum-number-of-pairs-in-array
Python Using Counter and divmod
blazers08
0
5
maximum number of pairs in array
2,341
0.766
Easy
32,136
https://leetcode.com/problems/maximum-number-of-pairs-in-array/discuss/2293386/PYTHON-EASY-TO-UNDERSTAND-SOLUTION
class Solution: def numberOfPairs(self, nums: List[int]) -> List[int]: C1 = Counter(nums) pairs = 0 ans = [0, 0] for k,v in C1.items(): if v > 1: pairs += v // 2 ans[0] = pairs if (2 * pairs) == len(nums): ans[1] = 0 else: ans[1] = len(nums) - (2 * pairs) return ans
maximum-number-of-pairs-in-array
PYTHON EASY TO UNDERSTAND SOLUTION
varunshrivastava2706
0
8
maximum number of pairs in array
2,341
0.766
Easy
32,137
https://leetcode.com/problems/maximum-number-of-pairs-in-array/discuss/2293292/Python-oror-Easy-Approach
class Solution: def numberOfPairs(self, nums: List[int]) -> List[int]: diction = {} for key in nums: diction[key] = diction.get(key, 0) + 1 pairs = 0 left = 0 for key in diction: if diction[key] % 2 == 0: pairs += diction[key] // 2 else: pairs += diction[key] // 2 left += 1 ans = [pairs, left] return ans
maximum-number-of-pairs-in-array
✅Python || Easy Approach
chuhonghao01
0
15
maximum number of pairs in array
2,341
0.766
Easy
32,138
https://leetcode.com/problems/maximum-number-of-pairs-in-array/discuss/2292711/Python3-Solution
class Solution: def numberOfPairs(self, nums: List[int]) -> List[int]: answer = [0, 0] mydict = defaultdict(int) for num in nums: mydict[num] += 1 for key in mydict: answer[0] += mydict[key] // 2 answer[1] += mydict[key] % 2 return answer
maximum-number-of-pairs-in-array
Python3 Solution
Skirocer
0
24
maximum number of pairs in array
2,341
0.766
Easy
32,139
https://leetcode.com/problems/max-sum-of-a-pair-with-equal-sum-of-digits/discuss/2297244/Python3-oror-dict(heaps)-8-lines-w-explanation-oror-TM%3A-1300ms27MB
class Solution: # The plan here is to: # # • sort the elements of nums into a dict of maxheaps, # according to sum-of-digits. # # • For each key, determine whether there are at least two # elements in that key's values, and if so, compute the # product of the greatest two elements. # # • return the the greatest such product as the answer. # For example: # nums = [6,15,13,12,24,21] –> {3:[12,21], 4:[13], 6:[6,15,24]} # Only two keys qualify, 3 and 6, for which the greatest two elements # are 12,21 and 15,24, respectively. 12+21 = 33 and 15+24 = 39, # so the answer is 39. def maximumSum(self, nums: List[int]) -> int: d, mx = defaultdict(list), -1 digits = lambda x: sum(map(int, list(str(x)))) # <-- sum-of-digits function for n in nums: # <-- construct max-heaps heappush(d[digits(n)],-n) # (note "-n") for i in d: # <-- pop the two greatest values off if len(d[i]) > 1: # each maxheap (when possible) and mx= max(mx, -heappop(d[i])-heappop(d[i])) # compare with current max value. return mx
max-sum-of-a-pair-with-equal-sum-of-digits
Python3 || dict(heaps), 8 lines, w/ explanation || T/M: 1300ms/27MB
warrenruud
3
111
max sum of a pair with equal sum of digits
2,342
0.532
Medium
32,140
https://leetcode.com/problems/max-sum-of-a-pair-with-equal-sum-of-digits/discuss/2292673/Python-two-sum
class Solution: def maximumSum(self, nums: List[int]) -> int: dict_map = {} res = -1 for num in nums: temp = num new_num = 0 while temp: new_num += temp % 10 temp = temp // 10 if new_num in dict_map: new_res = num + dict_map[new_num] res = max(res, new_res) dict_map[new_num] = max(num, dict_map[new_num]) else: dict_map[new_num] = num return res
max-sum-of-a-pair-with-equal-sum-of-digits
[Python] two sum
zonda_yang
3
155
max sum of a pair with equal sum of digits
2,342
0.532
Medium
32,141
https://leetcode.com/problems/max-sum-of-a-pair-with-equal-sum-of-digits/discuss/2293305/Python-oror-One-pass-Hash-Table-oror-Easy-Approach-oror-beats-100.00-Both-Runtime-and-Memory-oror-Remainder
class Solution: def maximumSum(self, nums: List[int]) -> int: def getSum(n): sum = 0 for digit in str(n): sum += int(digit) return sum hashmap = {} sumMax = -1 for i in range(len(nums)): complement = getSum(nums[i]) if complement in hashmap: sumMax = max(sumMax, nums[i] + hashmap[complement]) if nums[i] > hashmap[complement]: hashmap[complement] = nums[i] else: hashmap[complement] = nums[i] return sumMax
max-sum-of-a-pair-with-equal-sum-of-digits
✅Python || One-pass Hash Table || Easy Approach || beats 100.00% Both Runtime & Memory || Remainder
chuhonghao01
2
71
max sum of a pair with equal sum of digits
2,342
0.532
Medium
32,142
https://leetcode.com/problems/max-sum-of-a-pair-with-equal-sum-of-digits/discuss/2292882/Python3-hash-table
class Solution: def maximumSum(self, nums: List[int]) -> int: ans = -1 seen = {} for x in nums: sm = sum(int(d) for d in str(x)) if sm in seen: ans = max(ans, seen[sm] + x) seen[sm] = max(seen[sm], x) else: seen[sm] = x return ans
max-sum-of-a-pair-with-equal-sum-of-digits
[Python3] hash table
ye15
2
39
max sum of a pair with equal sum of digits
2,342
0.532
Medium
32,143
https://leetcode.com/problems/max-sum-of-a-pair-with-equal-sum-of-digits/discuss/2847625/Py-Hash-O(N)
class Solution: def maximumSum(self, arr: List[int]) -> int: arr_dict = defaultdict(int) ans = -1 for num in arr: num_sum = sum(int(num) for num in str(num)) if num_sum in arr_dict: ans = max(ans, num + arr_dict[num_sum]) arr_dict[num_sum] = max(arr_dict[num_sum], num) return ans
max-sum-of-a-pair-with-equal-sum-of-digits
Py Hash O(N)
haly-leshchuk
0
2
max sum of a pair with equal sum of digits
2,342
0.532
Medium
32,144
https://leetcode.com/problems/max-sum-of-a-pair-with-equal-sum-of-digits/discuss/2754204/easy-python-solution
class Solution: def maximumSum(self, nums: List[int]) -> int: digitSum = {} for num in nums : dSum = sum([int(i) for i in str(num)]) if dSum not in digitSum.keys() : digitSum[dSum] = [num] else : digitSum[dSum].append(num) maxValue = 0 for key in digitSum.keys() : arr = digitSum[key] if len(arr) >= 2 : arr.sort() if arr[-1] + arr[-2] > maxValue : maxValue = arr[-1] + arr[-2] if maxValue != 0 : return maxValue else : return -1
max-sum-of-a-pair-with-equal-sum-of-digits
easy python solution
sghorai
0
9
max sum of a pair with equal sum of digits
2,342
0.532
Medium
32,145
https://leetcode.com/problems/max-sum-of-a-pair-with-equal-sum-of-digits/discuss/2732883/Python-using-dictionary
class Solution: def maximumSum(self, nums: List[int]) -> int: dic = {} for i in nums : sumOfDigits = 0 for digit in str(i) : sumOfDigits += int (digit) if sumOfDigits in dic : dic[sumOfDigits] += [i] else : dic[sumOfDigits] = [i] res = -1 for i in dic.values() : if len(i) >= 2: res = max( res , sum(sorted(i,reverse=True)[0:2]) ) return res
max-sum-of-a-pair-with-equal-sum-of-digits
Python using dictionary
mohamedWalid
0
7
max sum of a pair with equal sum of digits
2,342
0.532
Medium
32,146
https://leetcode.com/problems/max-sum-of-a-pair-with-equal-sum-of-digits/discuss/2333094/oror-EASY-PYTHON-SOLUTION-oror
class Solution: def maximumSum(self, nums: List[int]) -> int: dic = defaultdict(list) for i,v in enumerate(nums) : summ = 0 while v : summ += v%10 v //= 10 dic[s].append(nums[i]) if len(dic[s]) > 2 : dic[s].sort(reverse=True) dic[s].pop() res = -1 for i in dic.values() : if len(i) == 2 : res = max(res,sum(i)) return res
max-sum-of-a-pair-with-equal-sum-of-digits
|| EASY PYTHON SOLUTION ||
rohitkhairnar
0
35
max sum of a pair with equal sum of digits
2,342
0.532
Medium
32,147
https://leetcode.com/problems/max-sum-of-a-pair-with-equal-sum-of-digits/discuss/2326925/Python-easy-to-read-and-understand-or-map
class Solution: def maximumSum(self, nums: List[int]) -> int: d = collections.defaultdict(list) for num in nums: sums = sum([int(i) for i in str(num)]) d[sums].append(num) ans = [] for key in d: ans.append(sorted(d[key])) res = -1 for val in ans: if len(val) > 1: res = max(res, val[-1]+val[-2]) return res
max-sum-of-a-pair-with-equal-sum-of-digits
Python easy to read and understand | map
sanial2001
0
29
max sum of a pair with equal sum of digits
2,342
0.532
Medium
32,148
https://leetcode.com/problems/max-sum-of-a-pair-with-equal-sum-of-digits/discuss/2301251/Python3-simple-solution
class Solution: def maximumSum(self, nums: List[int]) -> int: numMap = {} maxSum = -1 for num in nums: tmp = num digit_sum = 0 while tmp > 0: digit_sum += tmp % 10 tmp = tmp // 10 if digit_sum in numMap: numMap[digit_sum].append(num) else: numMap[digit_sum] = [num] for key, val in numMap.items(): if len(val) > 1: val.sort() sum = val[-1] + val[-2] maxSum = max(maxSum, sum) return maxSum
max-sum-of-a-pair-with-equal-sum-of-digits
Python3 simple solution
konarkg
0
6
max sum of a pair with equal sum of digits
2,342
0.532
Medium
32,149
https://leetcode.com/problems/max-sum-of-a-pair-with-equal-sum-of-digits/discuss/2298609/Python-100-faster-easy-python-solution-O(N)
class Solution: def maximumSum(self, nums: List[int]) -> int: def solve(num): ans=0 for i in str(num): ans+=int(i) return ans arr=[] for i in range(len(nums)): cur=solve(nums[i]) arr.append([nums[i],cur]) maxi=-1 arr.sort(key=lambda x:(x[1],x[0])) for i in range(len(arr)-1): if arr[i][1]==arr[i+1][1]: maxi=max(maxi,arr[i][0]+arr[i+1][0]) return maxi
max-sum-of-a-pair-with-equal-sum-of-digits
Python 100% faster easy python solution O(N)
narendrakummara_9
0
6
max sum of a pair with equal sum of digits
2,342
0.532
Medium
32,150
https://leetcode.com/problems/max-sum-of-a-pair-with-equal-sum-of-digits/discuss/2297823/Python-Save-Digit-Sum-in-a-Hashmap
class Solution: def maximumSum(self, nums: List[int]) -> int: res = -1 table = defaultdict(list) # add the digit sum to the dictionary # # sum(map(int,str(num))) -> First cast 'num' into a string so that you can turn it individually into an int with the map() function. # The map() function essentially turns each of the digit in num into a iterator then we pass that iterator into the sum() function. # for num in nums: table[sum(map(int,str(num)))].append(num) # look through each digit sum # for num, val in table.items(): # no need to check since we can't make a pair # if len(val) <= 1: continue # sort the current list and sum the last two digit to get the largest sum # val.sort() res = max(res, sum(val[-2:])) return res
max-sum-of-a-pair-with-equal-sum-of-digits
Python Save Digit Sum in a Hashmap
M-Phuykong
0
13
max sum of a pair with equal sum of digits
2,342
0.532
Medium
32,151
https://leetcode.com/problems/max-sum-of-a-pair-with-equal-sum-of-digits/discuss/2296419/Defaultdict-to-group-nums-in-heapq-100-speed
class Solution: def maximumSum(self, nums: List[int]) -> int: ans = -1 groups = defaultdict(list) for n in nums: heappush(groups[sum(map(int, str(n)))], -n) for lst in groups.values(): if len(lst) > 1: two_sum = -heappop(lst) two_sum -= heappop(lst) ans = max(ans, two_sum) return ans
max-sum-of-a-pair-with-equal-sum-of-digits
Defaultdict to group nums in heapq, 100% speed
EvgenySH
0
12
max sum of a pair with equal sum of digits
2,342
0.532
Medium
32,152
https://leetcode.com/problems/max-sum-of-a-pair-with-equal-sum-of-digits/discuss/2294979/python3%3A-Easy-to-understand-or-using-hash-map-and-sort
class Solution: def maximumSum(self, nums: List[int]) -> int: # sort the list in reverse as we need the maxmimum of nums[i],nums[j]. # In below for loop, We can stop comparing once we found two numbers with same digit sum after sorting. nums.sort(reverse=True) # use hash map to quickly find duplicates . # key = sum of digits # value = list of lenght 2 ,containg largest two nums[x] with same digit sum (key) sum_digits = {} ans = -1 for num in nums: # compute the sum of digits for num s = 0 n = num while n: s, n = s + n % 10, n // 10 if s in sum_digits: # do not proceed if we found first two numbers with same sum already. # As nums is reverse sorted the future numbers will always less than first two match if len(sum_digits[s]) < 2: sum_digits[s].append(num) ans = max( ans, sum_digits[s][0] + sum_digits[s][1]) else: sum_digits[s] = [ num ] # create a list and store the num in hash map return ans
max-sum-of-a-pair-with-equal-sum-of-digits
python3: Easy to understand | using hash map and sort
nkrishk
0
3
max sum of a pair with equal sum of digits
2,342
0.532
Medium
32,153
https://leetcode.com/problems/max-sum-of-a-pair-with-equal-sum-of-digits/discuss/2293024/Python-hashmap-Solution
class Solution(object): def maximumSum(self, nums): """ :type nums: List[int] :rtype: int """ # Python Program to implement # the above approach # Function to find sum of digits def digitSum(n): sum = 0 while (n): sum += (n % 10) n = n // 10 return sum map = {} nums.sort() for i in nums: sum = digitSum(i) if sum not in map: map[sum] = [i] else: map[sum].append(i) max_sum = 0 print(map) for i in map: n = len(map[i]) if n>1: v = map[i][-2:] max_sum = max(max_sum,(v[0]+v[1])) return -1 if max_sum==0 else max_sum
max-sum-of-a-pair-with-equal-sum-of-digits
Python hashmap Solution
Abhi_009
0
26
max sum of a pair with equal sum of digits
2,342
0.532
Medium
32,154
https://leetcode.com/problems/max-sum-of-a-pair-with-equal-sum-of-digits/discuss/2292961/heaps-and-hashmap-or-Python3-or-Explained
class Solution: def maximumSum(self, nums: List[int]) -> int: def sumDigits(n): n_str = str(n) res = 0 for c in n_str: res += int(c) return res mapping = defaultdict(list) for n in nums: heapq.heappush(mapping[sumDigits(n)], -n) res = -1 for s in mapping: if len(mapping[s]) >= 2: res = max(res, -1*(heapq.heappop(mapping[s]) + heapq.heappop(mapping[s]))) return res
max-sum-of-a-pair-with-equal-sum-of-digits
heaps and hashmap | Python3 | Explained
Tanayk
0
6
max sum of a pair with equal sum of digits
2,342
0.532
Medium
32,155
https://leetcode.com/problems/max-sum-of-a-pair-with-equal-sum-of-digits/discuss/2292903/Hashmap-of-Sum-of-digits-or-Python3
class Solution: def maximumSum(self, nums: List[int]) -> int: hashmap = {} nums.sort() for i in range(len(nums)): y = str(nums[i]) z = [int(i) for i in y] Sum = sum(z) if Sum not in hashmap.keys(): hashmap[Sum] = [nums[i],-1] else: x,y = hashmap[Sum] if min(x,y) == x: x = nums[i] hashmap[Sum] = [x,y] elif min(x,y) == y: y = nums[i] hashmap[Sum] = [x,y] res = -1 for a,b in hashmap.items(): if b[1]!=-1: Sum = b[0] + b[1] res = max(res,Sum) return res
max-sum-of-a-pair-with-equal-sum-of-digits
Hashmap of Sum of digits | Python3
user7457RV
0
5
max sum of a pair with equal sum of digits
2,342
0.532
Medium
32,156
https://leetcode.com/problems/max-sum-of-a-pair-with-equal-sum-of-digits/discuss/2292810/Python3-Solution
class Solution: def maximumSum(self, nums: List[int]) -> int: answer = -1 mydict = defaultdict(list) for num in nums: cur = 0 num = str(num) for digit in num: cur += int(digit) mydict[cur].append(int(num)) for key in mydict: if len(mydict[key]) >= 2: mydict[key].sort(reverse=True) answer = max((mydict[key][0] + mydict[key][1]), answer) return answer
max-sum-of-a-pair-with-equal-sum-of-digits
Python3 Solution
Skirocer
0
5
max sum of a pair with equal sum of digits
2,342
0.532
Medium
32,157
https://leetcode.com/problems/max-sum-of-a-pair-with-equal-sum-of-digits/discuss/2292687/Python-Sorting-Solution
class Solution: def maximumSum(self, nums: List[int]) -> int: hmap = collections.defaultdict(list) for n in nums: total = sum([int(i) for i in str(n)]) hmap[total] = hmap[total] +[n] hmap[total] = sorted(hmap[total], reverse=True)[:2] result = -1 for k, v in hmap.items(): if len(v) == 2: result = max(result, sum(v)) return result
max-sum-of-a-pair-with-equal-sum-of-digits
[Python] Sorting Solution
tejeshreddy111
0
22
max sum of a pair with equal sum of digits
2,342
0.532
Medium
32,158
https://leetcode.com/problems/query-kth-smallest-trimmed-number/discuss/2296143/Python-O(m-*-n)-solution-based-on-O(m)-counting-sort
class Solution: def smallestTrimmedNumbers(self, nums: List[str], queries: List[List[int]]) -> List[int]: def countingSort(indices, pos): count = [0] * 10 for idx in indices: count[ord(nums[idx][pos]) - ord('0')] += 1 start_pos = list(accumulate([0] + count, add)) result = [None] * len(indices) for idx in indices: digit = ord(nums[idx][pos]) - ord('0') result[start_pos[digit]] = idx start_pos[digit] += 1 return result n = len(nums) m = len(nums[0]) suffix_ordered = [list(range(n))] for i in range(m - 1, -1, -1): suffix_ordered.append(countingSort(suffix_ordered[-1], i)) return [suffix_ordered[t][k-1] for k, t in queries]
query-kth-smallest-trimmed-number
Python O(m * n) solution based on O(m) counting sort
lifuh
2
99
query kth smallest trimmed number
2,343
0.408
Medium
32,159
https://leetcode.com/problems/query-kth-smallest-trimmed-number/discuss/2292808/Python-Commented-Code-(-Insertion-%2B-Customization-for-storing-index)
class Solution: def smallestTrimmedNumbers(self, nums: List[str], queries: List[List[int]]) -> List[int]: a=[] #to store answer of queries for q in queries: ia=q[0] #kth smallest value to be returned t=q[1] #trim index temp=[] for n in nums: temp.append(int(n[-1*t:])) #using slicing just take last t elements temp1=[[temp[0],0]] #another list that will store sorted elements along with index for i in range(1,len(temp)): key=temp[i] j=len(temp1)-1 while j>=0 and key<temp1[j][0]: #using insertion sort, insert elements to new list also store index j-=1 temp1.insert(j+1,[key,i]) a.append(temp1[ia-1][1]) #append required index element return a
query-kth-smallest-trimmed-number
Python Commented Code ( Insertion + Customization for storing index)
shreyasjain0912
2
29
query kth smallest trimmed number
2,343
0.408
Medium
32,160
https://leetcode.com/problems/query-kth-smallest-trimmed-number/discuss/2292899/Python3-simulation
class Solution: def smallestTrimmedNumbers(self, nums: List[str], queries: List[List[int]]) -> List[int]: ans = [] for k, trim in queries: cand = [x[-trim:] for x in nums] _, v = sorted(zip(cand, range(len(cand))))[k-1] ans.append(v) return ans
query-kth-smallest-trimmed-number
[Python3] simulation
ye15
1
21
query kth smallest trimmed number
2,343
0.408
Medium
32,161
https://leetcode.com/problems/query-kth-smallest-trimmed-number/discuss/2658485/Two-solutions-greater-Radix-Sort-in-Python-Solution-Explained-%2B-Fastest-Python-Solution
class Solution: # Radix Sort Solution # MAKE a mapper for the queries # Write the good old count sort algorithm # For each time you go over a placeval iteration for the radix sort # Check if that iteration/trim is present in the mapper you made earlier # If yes then for that query item update the res # Edge case is when the new sorted array is same as the OG given nums # This could also mean that there are some repeated elements # So instead offinding the index in the OG nums just update res with the position asked # as that will be the answer for that query def smallestTrimmedNumbers(self, nums: List[str], queries: List[List[int]]) -> List[int]: def countsort(placeval, k = 10): counts = [0] * k for elem in nums: digit = (elem // placeval) % 10 counts[digit] += 1 s = 0 for i, count in enumerate(counts): counts[i] = s s += count sorted_list = [0] * len(nums) for elem in nums: digit = (elem // placeval) % 10 sorted_list[counts[digit]] = elem counts[digit] += 1 nums[:] = list(sorted_list) mapper = defaultdict(list) for i, (k, trim) in enumerate(queries): mapper[trim].append((k, i)) nums[:] = [int(num) for num in nums] og = list(nums) #Radix sort starts maxi = max(nums) res = [0] * len(queries) placeval, trim = 1, 1 while placeval <= maxi: countsort(placeval) if trim in mapper: for k, pos in mapper[trim]: if nums == og: res[pos] = k - 1 else: res[pos] = og.index(nums[k - 1]) placeval *= 10 trim += 1 return res
query-kth-smallest-trimmed-number
🥶 Two solutions -> Radix Sort in Python Solution 🏑 Explained + Fastest Python Solution
shiv-codes
0
13
query kth smallest trimmed number
2,343
0.408
Medium
32,162
https://leetcode.com/problems/query-kth-smallest-trimmed-number/discuss/2658485/Two-solutions-greater-Radix-Sort-in-Python-Solution-Explained-%2B-Fastest-Python-Solution
class Solution: # Extremely Fast O(K * N * logN) Solution k -> Maximum Digits, n -> numbers in nums # Prepare a defaultdict cache for each trim length # Since each num is given as a string you can slice the string till trim from last # Now store this sliced string with the original index of it in nums # Sort this list using sort of python (nlogn) # Append the result to the res def smallestTrimmedNumbers(self, nums: List[str], queries: List[List[int]]) -> List[int]: trim_length_cache = defaultdict(list) res = [0] * len(queries) for i, (k, trim) in enumerate(queries): if trim not in trim_length_cache: trim_length_cache[trim] = [(num[-trim:], index) for index, num in enumerate(nums)] trim_length_cache[trim].sort() res[i] = trim_length_cache[trim][k - 1][1] return res
query-kth-smallest-trimmed-number
🥶 Two solutions -> Radix Sort in Python Solution 🏑 Explained + Fastest Python Solution
shiv-codes
0
13
query kth smallest trimmed number
2,343
0.408
Medium
32,163
https://leetcode.com/problems/query-kth-smallest-trimmed-number/discuss/2295435/Python3-Abusing-the-fact-that-a-python3-int-value-is-unbound
class Solution: def smallestTrimmedNumbers(self, nums: List[str], queries: List[List[int]]) -> List[int]: n, m = len(nums), len(nums[0]) memo = [] current_val_list = [0] * n for i in reversed(range(m)): for j in range(n): current_val_list[j] = current_val_list[j] + int(nums[j][i]) * (10**(m-1-i)) memo.append(sorted(enumerate(current_val_list), key=lambda x: x[1]*100+x[0])) return [memo[trimmed-1][k-1][0] for k, trimmed in queries]
query-kth-smallest-trimmed-number
[Python3] Abusing the fact that a python3 int value is unbound
CuriousJianXu
0
7
query kth smallest trimmed number
2,343
0.408
Medium
32,164
https://leetcode.com/problems/query-kth-smallest-trimmed-number/discuss/2294359/Python-easy-and-simple-solution-using-enumerate-and-sort
class Solution: def smallestTrimmedNumbers(self, nums: List[str], queries: List[List[int]]) -> List[int]: res = [] for k, trims in queries: tmp = [[item[-trims:], i] for i, item in enumerate(nums)] tmp.sort(key=lambda x:x[0]) res.append(tmp[k - 1][1]) return res
query-kth-smallest-trimmed-number
Python easy and simple solution using enumerate and sort
blazers08
0
5
query kth smallest trimmed number
2,343
0.408
Medium
32,165
https://leetcode.com/problems/query-kth-smallest-trimmed-number/discuss/2293968/python3-simple-solutions
class Solution: def smallestTrimmedNumbers(self, nums: List[str], queries: List[List[int]]) -> List[int]: def trim(t): out = [] for s in nums: n = s[len(s)-t:] out.append(int(n)) return out def smallest(arr, k): arr = [(x,i) for i,x in enumerate(arr)] arr.sort(key = lambda x: x[0]) return arr[k][1] out = [] for q in queries: k, t = q new_nums = trim(t) i = smallest(new_nums, k-1) out.append(i) return out
query-kth-smallest-trimmed-number
python3 simple solutions
pradyumna04
0
7
query kth smallest trimmed number
2,343
0.408
Medium
32,166
https://leetcode.com/problems/query-kth-smallest-trimmed-number/discuss/2293968/python3-simple-solutions
class Solution: def smallestTrimmedNumbers(self, nums: List[str], queries: List[List[int]]) -> List[int]: def trim(t): return [x[len(x)-t:] for x in nums] def smallest(arr, k): arr = [(x,i) for i,x in enumerate(arr)] arr.sort(key = lambda x: x[0]) return arr[k][1] out = [] for q in queries: k, t = q new_nums = trim(t) i = smallest(new_nums, k-1) out.append(i) return out
query-kth-smallest-trimmed-number
python3 simple solutions
pradyumna04
0
7
query kth smallest trimmed number
2,343
0.408
Medium
32,167
https://leetcode.com/problems/query-kth-smallest-trimmed-number/discuss/2293895/Python-Solution
class Solution: def smallestTrimmedNumbers(self, nums: List[str], queries: List[List[int]]) -> List[int]: answer = [] for i,j in queries: temp = [] for n in nums: temp.append(int(n[-j:])) answer.append(temp) for i in range(len(answer)): res = sorted(range(len(answer[i])), key = lambda x: answer[i][x])[:queries[i][0]] answer[i] = res[-1] return answer
query-kth-smallest-trimmed-number
Python Solution
aakarshvermaofficial
0
9
query kth smallest trimmed number
2,343
0.408
Medium
32,168
https://leetcode.com/problems/query-kth-smallest-trimmed-number/discuss/2293173/My-python3-solution
class Solution: def smallestTrimmedNumbers(self, nums: List[str], queries: List[List[int]]) -> List[int]: lists = [] for i in range(1, len(nums[0])+1): lists.append(sorted([(x[-i:], j) for j,x in enumerate(nums)])) ret = [] for k, trim in queries: ret.append(lists[trim-1][k-1][1]) return ret
query-kth-smallest-trimmed-number
My python3 solution
emmy_matt
0
9
query kth smallest trimmed number
2,343
0.408
Medium
32,169
https://leetcode.com/problems/query-kth-smallest-trimmed-number/discuss/2293152/Simple-Brute-Force-or-Python
class Solution: def smallestTrimmedNumbers(self, nums: List[str], queries: List[List[int]]) -> List[int]: d = {} res = [] N = len(nums[0]) for a, b in queries: if b not in d: vals = [int(n[N - b: ]) for n in nums] d[b] = vals else: vals = d[b] sorted_vals = sorted(list(enumerate(vals)), key=lambda x: x[1]) res.append(sorted_vals[a - 1][0]) return res
query-kth-smallest-trimmed-number
Simple Brute-Force | Python
GigaMoksh
0
20
query kth smallest trimmed number
2,343
0.408
Medium
32,170
https://leetcode.com/problems/query-kth-smallest-trimmed-number/discuss/2293001/Python-Easy-Understanding
class Solution: def smallestTrimmedNumbers(self, nums: List[str], queries: List[List[int]]) -> List[int]: res = [] for k, s in queries: temp = nums[:] for i in range(len(temp)): temp[i] = [int(temp[i][-s:]),i] temp.sort() res.append(temp[k-1][1]) return res
query-kth-smallest-trimmed-number
Python Easy Understanding
S_Nishanth
0
13
query kth smallest trimmed number
2,343
0.408
Medium
32,171
https://leetcode.com/problems/query-kth-smallest-trimmed-number/discuss/2292957/Python3-Solution-using-priority-queue
class Solution: def smallestTrimmedNumbers(self, nums: List[str], queries: List[List[int]]) -> List[int]: answer = [] length = len(nums[0]) for query in queries: cur = [] for i in range(len(nums)): if len(cur) < query[0]: heapq.heappush(cur, (-int((nums[i][length - query[1]:])), -i)) else: heapq.heappushpop(cur, (-int((nums[i][length - query[1]:])), -i)) answer.append(-cur[0][1]) return answer
query-kth-smallest-trimmed-number
Python3 Solution using priority queue
Skirocer
0
5
query kth smallest trimmed number
2,343
0.408
Medium
32,172
https://leetcode.com/problems/query-kth-smallest-trimmed-number/discuss/2292867/Sorting-and-hashmap-solution-or-Python3-or-Explained
class Solution: def smallestTrimmedNumbers(self, nums: List[str], queries: List[List[int]]) -> List[int]: m = defaultdict(list) n = len(nums[0]) for j in range(n): key = n - j for i, num in enumerate(nums): num = int(num[-key:] if num[-key:] else 0) m[key].append([num, i]) res = [] for k, t in queries: l = sorted(m[t]) res.append(l[k-1][1]) return res
query-kth-smallest-trimmed-number
Sorting and hashmap solution | Python3 | Explained
Tanayk
0
5
query kth smallest trimmed number
2,343
0.408
Medium
32,173
https://leetcode.com/problems/query-kth-smallest-trimmed-number/discuss/2292727/Python-Easy-Solution-or-Caching-Values-or-HashMap-or-Easy-Understanding
class Solution: def smallestTrimmedNumbers(self, nums: List[str], queries: List[List[int]]) -> List[int]: N = len(nums[0]) hmap = collections.defaultdict(list) result = [] for k, trim in queries: if trim not in hmap: trimmed_values = [int(n[N - trim: ]) for n in nums] hmap[trim] = trimmed_values else: trimmed_values = hmap[trim] positions = [(v, k) for k, v in enumerate(trimmed_values)] positions = sorted(positions, key=lambda x: x[0]) result.append(positions[k - 1][1]) return result
query-kth-smallest-trimmed-number
[Python] Easy Solution | Caching Values | HashMap | Easy Understanding
tejeshreddy111
0
16
query kth smallest trimmed number
2,343
0.408
Medium
32,174
https://leetcode.com/problems/query-kth-smallest-trimmed-number/discuss/2292640/Python-hash-map
class Solution: def smallestTrimmedNumbers(self, nums: List[str], queries: List[List[int]]) -> List[int]: dict_map = {} res = [] for k, trim in queries: if not trim in dict_map: q = [] for (index, num) in enumerate(nums): new_num = int(num[-trim:]) item = (new_num, index) q.append(item) q.sort(key=lambda tup: tup[0]) dict_map[trim] = q res.append(dict_map[trim][k-1][1]) return res
query-kth-smallest-trimmed-number
[Python] hash map
zonda_yang
0
9
query kth smallest trimmed number
2,343
0.408
Medium
32,175
https://leetcode.com/problems/query-kth-smallest-trimmed-number/discuss/2292607/Python3-Simple-In-Place-Sort
class Solution: def smallestTrimmedNumbers(self, nums: List[str], queries: List[List[int]]) -> List[int]: A = list(enumerate(nums)) # (1) res = [] for k, t in queries: A.sort(key=lambda x: (int(x[1][len(x[1]) - t:]), x[0])) # (2) res.append(A[k - 1][0]) # (3) return res
query-kth-smallest-trimmed-number
[Python3] Simple In-Place Sort
Unwise
0
11
query kth smallest trimmed number
2,343
0.408
Medium
32,176
https://leetcode.com/problems/minimum-deletions-to-make-array-divisible/discuss/2296334/Python3-oror-GCD-and-heap-6-lines-w-explanation-oror-TM%3A-56100
class Solution: # From number theory, we know that an integer num divides each # integer in a list if and only if num divides the list's gcd. # # Our plan here is to: # • find the gcd of numDivide # • heapify(nums) and count the popped elements that do not # divide the gcd. # • return that count when and if a popped element eventually # divides the gcd. If that never happens, return -1 def minOperations(self, nums: List[int], numsDivide: List[int]) -> int: g, ans = gcd(*numsDivide), 0 # <-- find gcd (using * operator) heapify(nums) # <-- create heap while nums: # <-- pop and count if not g%heappop(nums): return ans # <-- found a divisor? return count else: ans+= 1 # <-- if not, increment the count return -1 # <-- no divisors found #-------------------------------------------------- class Solution: # version w/o heap. Seems to run slower def minOperations(self, nums: List[int], numsDivide: List[int]) -> int: g = gcd(*numsDivide) nums.sort() for i,num in enumerate(nums): if not g%num: return i return -1
minimum-deletions-to-make-array-divisible
Python3 || GCD and heap, 6 lines, w/ explanation || T/M: 56%/100%
warrenruud
3
37
minimum deletions to make array divisible
2,344
0.57
Hard
32,177
https://leetcode.com/problems/minimum-deletions-to-make-array-divisible/discuss/2294885/Python3-solution
class Solution: def minOperations(self, nums: List[int], numsDivide: List[int]) -> int: counter = Counter(nums) setDivide = set(numsDivide) result = 0 minimum = float("inf") for i in sorted(set(nums)): flag = True for k in setDivide: if k % i != 0: flag = False break if flag == False: result+=counter[i] else: return result return -1
minimum-deletions-to-make-array-divisible
📌 Python3 solution
Dark_wolf_jss
1
9
minimum deletions to make array divisible
2,344
0.57
Hard
32,178
https://leetcode.com/problems/minimum-deletions-to-make-array-divisible/discuss/2292922/Python3-2-line
class Solution: def minOperations(self, nums: List[int], numsDivide: List[int]) -> int: g = reduce(gcd, numsDivide) return next((i for i, x in enumerate(sorted(nums)) if g % x == 0), -1)
minimum-deletions-to-make-array-divisible
[Python3] 2-line
ye15
1
8
minimum deletions to make array divisible
2,344
0.57
Hard
32,179
https://leetcode.com/problems/minimum-deletions-to-make-array-divisible/discuss/2826778/python-simple
class Solution: def minOperations(self, nums: List[int], numsDivide: List[int]) -> int: #define function to find gcd of array def gcd_of_array(a): #b is first element of array b = a[0] #loop thru rest of the array for j in range(1, len(a)): #if there's a new gcd, update b to it b=math.gcd(b,a[j]) return b #find gcd of array numsDivide val = gcd_of_array(numsDivide) #use this to turn nums into a heap heapq.heapify(nums) #start count at zero count=0 #loop while there are vals in nums #NB val%nums[0] - python sees 0 as false, so loop will stop when the % == 0 while len(nums) > 0 and val%nums[0]: #increase count by 1 count+=1 #remove the smallest item from the heap heapq.heappop(nums) #if all items have been removed from nums if len(nums) > 0: #you know what this does return count #if there are still items in nums else: #as per question return -1
minimum-deletions-to-make-array-divisible
python simple
ATHBuys
0
1
minimum deletions to make array divisible
2,344
0.57
Hard
32,180
https://leetcode.com/problems/minimum-deletions-to-make-array-divisible/discuss/2295007/Python-gcd-heap
class Solution: def minOperations(self, nums: List[int], numsDivide: List[int]) -> int: counts = list(Counter(nums).items()) heapq.heapify(counts) g = reduce(math.gcd, numsDivide) result = 0 while counts: if g % counts[0][0] == 0: return result _, cnt = heapq.heappop(counts) result += cnt return -1
minimum-deletions-to-make-array-divisible
Python, gcd, heap
blue_sky5
0
5
minimum deletions to make array divisible
2,344
0.57
Hard
32,181
https://leetcode.com/problems/minimum-deletions-to-make-array-divisible/discuss/2294089/Python-100-memory-efficient
class Solution: def minOperations(self, nums: List[int], numsDivide: List[int]) -> int: nums.sort() g = numsDivide[0] for x in numsDivide[1:]: g = gcd(g,x) count = 0 for x in nums: if g%x!= 0: count+=1 else: return count if count == len(nums): return -1
minimum-deletions-to-make-array-divisible
Python 100% memory efficient
Abhi_009
0
7
minimum deletions to make array divisible
2,344
0.57
Hard
32,182
https://leetcode.com/problems/minimum-deletions-to-make-array-divisible/discuss/2293003/Python3-non-gcd
class Solution: def minOperations(self, nums: List[int], numsDivide: List[int]) -> int: nums.sort() index = 0 def divisible(cur:int) -> bool: for num in numsDivide: if num % cur != 0: return False return True while index < len(nums): if divisible(nums[index]): return index while index < len(nums) - 1 and nums[index] == nums[index + 1]: index += 1 index += 1 return -1
minimum-deletions-to-make-array-divisible
Python3 non-gcd
Skirocer
0
8
minimum deletions to make array divisible
2,344
0.57
Hard
32,183
https://leetcode.com/problems/minimum-deletions-to-make-array-divisible/discuss/2292778/GCD-and-heaps-or-Python3-or-Explained
class Solution: def minOperations(self, nums: List[int], numsDivide: List[int]) -> int: def GcdOfArray(arr, idx): if idx == len(arr)-1: return arr[idx] a = arr[idx] b = GcdOfArray(arr,idx+1) return math.gcd(a, b) c = GcdOfArray(numsDivide, 0) heapq.heapify(nums) res = 0 while nums and (c % nums[0] != 0): res += 1 heapq.heappop(nums) return res if len(nums) else -1
minimum-deletions-to-make-array-divisible
GCD and heaps | Python3 | Explained
Tanayk
0
14
minimum deletions to make array divisible
2,344
0.57
Hard
32,184
https://leetcode.com/problems/minimum-deletions-to-make-array-divisible/discuss/2292644/Beginner-friendly-and-way-too-comprehensive-explanation-Python3
class Solution: def minOperations(self, nums: List[int], numsDivide: List[int]) -> int: # Step 1 st, mini = set(), min(numsDivide) for i in range(1, int(sqrt(mini + 1)) + 1): if mini % i == 0: st.add(i) st.add(mini // i) # Step 2 targets = set() for x in st: for y in numsDivide: if y % x != 0: break else: targets.add(x) # Step 3 nums.sort() for i, x in enumerate(nums): if x in targets: return i return -1
minimum-deletions-to-make-array-divisible
Beginner-friendly and way too comprehensive explanation - Python3
WoodlandXander
0
7
minimum deletions to make array divisible
2,344
0.57
Hard
32,185
https://leetcode.com/problems/minimum-deletions-to-make-array-divisible/discuss/2292639/Python3-Simple-GCD-Method
class Solution: def minOperations(self, nums: List[int], numsDivide: List[int]) -> int: g = numsDivide[0] for n in numsDivide[1:]: g = gcd(g, n) res = 0 # Tracks the number of deletions nums.sort() for n in nums: if g % n == 0: # If n divides the GCD, return the number of deletions return res elif n > g: # If n is greater than the GCD, no future numbers will work return -1 else: res += 1 # Otherwise, we need to delete n, so we inc the number of deletions return -1
minimum-deletions-to-make-array-divisible
[Python3] Simple GCD Method
Unwise
0
7
minimum deletions to make array divisible
2,344
0.57
Hard
32,186
https://leetcode.com/problems/minimum-deletions-to-make-array-divisible/discuss/2292556/GCD-and-sort-the-nums
class Solution: def minOperations(self, nums: List[int], numsDivide: List[int]) -> int: GCD = reduce(lambda x,y: gcd(x,y), numsDivide) nums.sort() for idx, num in enumerate(nums): if(GCD % num == 0): return idx return -1
minimum-deletions-to-make-array-divisible
GCD and sort the nums
torocholazzz
0
8
minimum deletions to make array divisible
2,344
0.57
Hard
32,187
https://leetcode.com/problems/best-poker-hand/discuss/2322411/Python-oror-Easy-Approach
class Solution: def bestHand(self, ranks: List[int], suits: List[str]) -> str: dictRanks = {} dictSuits = {} for key in ranks: dictRanks[key] = dictRanks.get(key, 0) + 1 for key in suits: dictSuits[key] = dictSuits.get(key, 0) + 1 maxRanks = max(dictRanks.values()) maxSuits = max(dictSuits.values()) if maxSuits == 5: return "Flush" if maxRanks >= 3: return "Three of a Kind" if maxRanks >= 2: return "Pair" return "High Card"
best-poker-hand
✅Python || Easy Approach
chuhonghao01
3
116
best poker hand
2,347
0.606
Easy
32,188
https://leetcode.com/problems/best-poker-hand/discuss/2380710/Python-simple-hashmap
class Solution: def bestHand(self, ranks: List[int], suits: List[str]) -> str: s={} for i in suits: if i in s: s[i]+=1 if s[i]==5: return 'Flush' else: s[i]=1 r={} max_ = 0 for i in ranks: if i in r: r[i]+=1 max_=max(max_,r[i]) else: r[i]=1 if max_>=3: return "Three of a Kind" elif max_==2: return "Pair" else: return "High Card"
best-poker-hand
Python simple hashmap
sunakshi132
1
53
best poker hand
2,347
0.606
Easy
32,189
https://leetcode.com/problems/best-poker-hand/discuss/2377771/Python-oror-easy-colution
class Solution: def bestHand(self, ranks: List[int], suits: List[str]) -> str: N = len(ranks) statistic = defaultdict(int) letter_freq = 0 number_freq = 0 for i in range(N): statistic[ranks[i]] += 1 statistic[suits[i]] += 1 letter_freq = max(letter_freq, statistic[suits[i]]) number_freq = max(number_freq, statistic[ranks[i]]) if letter_freq >=5: return "Flush" if number_freq >=3: return "Three of a Kind" if number_freq >= 2: return "Pair" return "High Card"
best-poker-hand
Python || easy colution
pivovar3al
1
27
best poker hand
2,347
0.606
Easy
32,190
https://leetcode.com/problems/best-poker-hand/discuss/2377771/Python-oror-easy-colution
class Solution: def bestHand(self, ranks: List[int], suits: List[str]) -> str: N = len(ranks) statistic = defaultdict(int) letter_freq = Counter(suits).most_common(1) number_freq = Counter(ranks).most_common(1) if letter_freq[0][1] >=5: return "Flush" if number_freq[0][1] >=3: return "Three of a Kind" if number_freq[0][1] >= 2: return "Pair" return "High Card"
best-poker-hand
Python || easy colution
pivovar3al
1
27
best poker hand
2,347
0.606
Easy
32,191
https://leetcode.com/problems/best-poker-hand/discuss/2323361/Python-or-Easy-and-Understanding-Solution
class Solution: def bestHand(self, ranks: List[int], suits: List[str]) -> str: if(len(set(suits))==1): return "Flush" mp={} for i in range(5): if(ranks[i] not in mp): mp[ranks[i]]=1 else: mp[ranks[i]]+=1 for val in mp: if(mp[val]>=3): return "Three of a Kind" elif(mp[val]==2): return "Pair" return "High Card"
best-poker-hand
Python | Easy & Understanding Solution
backpropagator
1
72
best poker hand
2,347
0.606
Easy
32,192
https://leetcode.com/problems/best-poker-hand/discuss/2841034/Python3-4-liner-Beats-95.56-use-Counter
class Solution: def bestHand(self, ranks, suits): # if all suits are the same, return Flush if len(set(suits))==1: return "Flush" # otherwise, set m to the maximum amount of times a rank appears c = Counter(ranks) m = max(c[x] for x in c) # if m>=3, it's three of a kind. if m==2, its a pair. otherwise, it is a high card. return "Three of a Kind" if m>=3 else "Pair" if m==2 else "High Card"
best-poker-hand
[Python3 4-liner] Beats 95.56%, use Counter
U753L
0
1
best poker hand
2,347
0.606
Easy
32,193
https://leetcode.com/problems/best-poker-hand/discuss/2714083/Python3-Commented-and-easy-solution
class Solution: def bestHand(self, ranks: List[int], suits: List[str]) -> str: # check the suits if len(set(suits)) == 1: return "Flush" # count the ranks cn = collections.defaultdict(int) max_cn = 0 # go through the ranks for rank in ranks: # increase the amount cn[rank] += 1 # check for maximum max_cn = max(max_cn, cn[rank]) # return the result if max_cn >= 3: return "Three of a Kind" elif max_cn == 2: return "Pair" else: return "High Card"
best-poker-hand
[Python3] - Commented and easy solution
Lucew
0
1
best poker hand
2,347
0.606
Easy
32,194
https://leetcode.com/problems/best-poker-hand/discuss/2389108/Simple-Python-Solution
class Solution: def bestHand(self, ranks: List[int], suits: List[str]) -> str: n = max([ranks.count(x) for x in ranks]) l = len(set(suits)) if l == 1: return "Flush" elif n >= 3: return "Three of a Kind" elif n >= 2: return "Pair" else: return "High Card"
best-poker-hand
Simple Python Solution
zip_demons
0
24
best poker hand
2,347
0.606
Easy
32,195
https://leetcode.com/problems/best-poker-hand/discuss/2375684/Python-simple-solution
class Solution: def bestHand(self, ranks: List[int], suits: List[str]) -> str: if len(set(suits)) == 1: return "Flush" elif max([ranks.count(x) for x in ranks]) >= 3: return "Three of a Kind" elif max([ranks.count(x) for x in ranks]) >= 2: return "Pair" else: return "High Card"
best-poker-hand
Python simple solution
StikS32
0
21
best poker hand
2,347
0.606
Easy
32,196
https://leetcode.com/problems/best-poker-hand/discuss/2332197/Python-easy-solution-for-beginners-using-logic
class Solution: def bestHand(self, ranks: List[int], suits: List[str]) -> str: if len(set(suits)) == 1: return "Flush" else: rank_freq = Counter(ranks).most_common() res = "High Card" for i in rank_freq: if i[1] >= 3 and (res == "High Card" or res == "Pair"): res = "Three of a Kind" elif i[1] == 2 and res == "High Card": res = "Pair" return res
best-poker-hand
Python easy solution for beginners using logic
alishak1999
0
23
best poker hand
2,347
0.606
Easy
32,197
https://leetcode.com/problems/best-poker-hand/discuss/2324364/Python3-match-case
class Solution: def bestHand(self, r: List[int], s: List[str]) -> str: if len(set(s)) == 1: return "Flush" match m := max(Counter(r).values()): case _ if m >= 3: return "Three of a Kind" case 2: return "Pair" case _: return "High Card"
best-poker-hand
[Python3] match-case
ye15
0
3
best poker hand
2,347
0.606
Easy
32,198
https://leetcode.com/problems/best-poker-hand/discuss/2323484/Check-combos-sequentially
class Solution: def bestHand(self, ranks: List[int], suits: List[str]) -> str: if len(set(suits)) == 1: return "Flush" cnt = set(Counter(ranks).values()) if 3 in cnt or 4 in cnt: return "Three of a Kind" if 2 in cnt: return "Pair" return "High Card"
best-poker-hand
Check combos sequentially
EvgenySH
0
8
best poker hand
2,347
0.606
Easy
32,199