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/sort-integers-by-the-number-of-1-bits/discuss/2210674/Python-Simple-Python-Solution-Using-Dictionary-and-Sorting
class Solution: def sortByBits(self, array: List[int]) -> List[int]: array = sorted(array) d = {} for i in array: total_one = bin(i)[2:].count('1') if total_one not in d: d[total_one] = [i] else: d[total_one].append(i) d = dict(sorted(d.items() , key = lambda x:x[0])) result = [] for key in d: result = result + d[key] return result
sort-integers-by-the-number-of-1-bits
[ Python ] ✅✅ Simple Python Solution Using Dictionary and Sorting 🥳✌👍
ASHOK_KUMAR_MEGHVANSHI
4
861
sort integers by the number of 1 bits
1,356
0.72
Easy
20,400
https://leetcode.com/problems/sort-integers-by-the-number-of-1-bits/discuss/859623/Python3-1-line
class Solution: def sortByBits(self, arr: List[int]) -> List[int]: return sorted(arr, key=lambda x: (bin(x).count("1"), x))
sort-integers-by-the-number-of-1-bits
[Python3] 1-line
ye15
4
273
sort integers by the number of 1 bits
1,356
0.72
Easy
20,401
https://leetcode.com/problems/sort-integers-by-the-number-of-1-bits/discuss/1166689/Python3-99-Faster-Solution
class Solution: def sortByBits(self, arr: List[int]) -> List[int]: ans = {} for i in arr: count_1 = bin(i)[2:].count('1') if(count_1 in ans): ans[count_1].append(i) else: ans[count_1] = [i] ans = list(sorted(ans.items() , key=lambda x: x[0])) arr = [] for i , j in ans: j.sort() arr.extend(j) return arr
sort-integers-by-the-number-of-1-bits
[Python3] 99% Faster Solution
VoidCupboard
3
436
sort integers by the number of 1 bits
1,356
0.72
Easy
20,402
https://leetcode.com/problems/sort-integers-by-the-number-of-1-bits/discuss/2466398/Python-Simple-Solution
class Solution: def sortByBits(self, arr: List[int]) -> List[int]: return sorted(sorted(arr), key=lambda x: bin(x).count('1'))
sort-integers-by-the-number-of-1-bits
Python Simple Solution
xinhuangtien
2
552
sort integers by the number of 1 bits
1,356
0.72
Easy
20,403
https://leetcode.com/problems/sort-integers-by-the-number-of-1-bits/discuss/2348643/Sort-Integers-by-The-Number-of-1-Bits
class Solution: def sortByBits(self, arr: List[int]) -> List[int]: out =[] for i in arr: out.append([i,bin(i)[2:].count("1")]) n = len(out) for i in range(n-1): swapped= False for j in range(n-i-1): if out[j][1]>out[j+1][1]: m = out[j] out[j]=out[j+1] out[j+1]=m swapped= True elif out[j][1]==out[j+1][1] and out[j][0]>out[j+1][0]: m = out[j] out[j]=out[j+1] out[j+1]=m swapped= True if not swapped: break res = [x[0] for x in out ] return res
sort-integers-by-the-number-of-1-bits
Sort Integers by The Number of 1 Bits
dhananjayaduttmishra
2
128
sort integers by the number of 1 bits
1,356
0.72
Easy
20,404
https://leetcode.com/problems/sort-integers-by-the-number-of-1-bits/discuss/2057258/Python-Solution-or-One-Liner-or-Dual-Sort-Based-or-Over-90-Faster
class Solution: def sortByBits(self, arr: List[int]) -> List[int]: return sorted(arr,key=lambda x: (bin(x).count("1"),x))
sort-integers-by-the-number-of-1-bits
Python Solution | One-Liner | Dual Sort Based | Over 90% Faster
Gautam_ProMax
2
234
sort integers by the number of 1 bits
1,356
0.72
Easy
20,405
https://leetcode.com/problems/sort-integers-by-the-number-of-1-bits/discuss/522603/Python-3-(one-line)-(beats-~100)
class Solution: def sortByBits(self, A: List[int]) -> List[int]: return sorted(A, key = lambda x: (bin(x).count('1'),x)) - Junaid Mansuri - Chicago, IL
sort-integers-by-the-number-of-1-bits
Python 3 (one line) (beats ~100%)
junaidmansuri
2
718
sort integers by the number of 1 bits
1,356
0.72
Easy
20,406
https://leetcode.com/problems/sort-integers-by-the-number-of-1-bits/discuss/2559968/Python-solution
class Solution: def sortByBits(self, arr: List[int]) -> List[int]: li_tuples_nums_binaries = [] for i in arr: binary = bin(i) li_tuples_nums_binaries.append([binary.count('1'), i]) li_tuples_nums_binaries.sort() result = [] for b, i in li_tuples_nums_binaries: result.append(i) return result
sort-integers-by-the-number-of-1-bits
Python solution
samanehghafouri
1
337
sort integers by the number of 1 bits
1,356
0.72
Easy
20,407
https://leetcode.com/problems/sort-integers-by-the-number-of-1-bits/discuss/2412193/PYTHON-using-dictionaries-with-exaplanation
class Solution: def sortByBits(self, arr: List[int]) -> List[int]: d = {} for i in arr: s = bin(i) temp = s[2:] temp = str(temp) c = temp.count("1") if c not in d: d[c]=[] d[c].append(i) else: d[c].append(i) print(list(d.values())) for i in list(d.keys()): l = d[i] l.sort() d[i] = l # print(list(d.values())) # sorting a dictionay with n dv = list(d.keys()) dv.sort() sl = [] for i in dv: sl.append(d[i]) # print(sl) ret = [i for subList in sl for i in subList] return ret
sort-integers-by-the-number-of-1-bits
[PYTHON] - using dictionaries, with exaplanation
Aravind126
1
288
sort integers by the number of 1 bits
1,356
0.72
Easy
20,408
https://leetcode.com/problems/sort-integers-by-the-number-of-1-bits/discuss/2246522/Python3-one-liner
class Solution: def sortByBits(self, A): return sorted(A, key=lambda a: [bin(a).count('1'), a])
sort-integers-by-the-number-of-1-bits
📌 Python3 one liner
Dark_wolf_jss
1
147
sort integers by the number of 1 bits
1,356
0.72
Easy
20,409
https://leetcode.com/problems/sort-integers-by-the-number-of-1-bits/discuss/1899268/1356.-Sort-Integers-by-The-Number-of-1-Bits
class Solution: def sortByBits(self, arr: List[int]) -> List[int]: r = { e: bin(e)[2:].count('1') for e in set(arr) } return sorted(arr, key=lambda a: (r[a], a))
sort-integers-by-the-number-of-1-bits
1356. Sort Integers by The Number of 1 Bits
MyGahan
1
143
sort integers by the number of 1 bits
1,356
0.72
Easy
20,410
https://leetcode.com/problems/sort-integers-by-the-number-of-1-bits/discuss/1414523/Python-One-Liner
class Solution: def sortByBits(self, arr: List[int]) -> List[int]: return sorted(arr, key=lambda x: (bin(x).count('1'), x))
sort-integers-by-the-number-of-1-bits
Python One Liner
peatear-anthony
1
196
sort integers by the number of 1 bits
1,356
0.72
Easy
20,411
https://leetcode.com/problems/sort-integers-by-the-number-of-1-bits/discuss/1216419/1-liner-python3-simple-code
class Solution: def sortByBits(self, arr: List[int]) -> List[int]: arr.sort(key=lambda k:(bin(k)[2:].count('1'),k)) return arr
sort-integers-by-the-number-of-1-bits
1 liner python3 simple code
samarthnehe
1
243
sort integers by the number of 1 bits
1,356
0.72
Easy
20,412
https://leetcode.com/problems/sort-integers-by-the-number-of-1-bits/discuss/1151947/simple-and-easy-python
class Solution: def sortByBits(self, arr: List[int]) -> List[int]: return sorted(arr, key = lambda x: (bin(x).count("1"), x))
sort-integers-by-the-number-of-1-bits
simple and easy python
pheobhe
1
193
sort integers by the number of 1 bits
1,356
0.72
Easy
20,413
https://leetcode.com/problems/sort-integers-by-the-number-of-1-bits/discuss/1040568/Python3-easy-solution-using-%22bin%22-%22int%22
class Solution: def sortByBits(self, arr: List[int]) -> List[int]: arr.sort() for i in range(len(arr)): arr[i] = bin(arr[i]).replace('0b','') arr = sorted(arr,key=lambda x: x.count('1')) for i in range(len(arr)): arr[i] = int(arr[i],2) return arr
sort-integers-by-the-number-of-1-bits
Python3 easy solution using "bin", "int",
EklavyaJoshi
1
178
sort integers by the number of 1 bits
1,356
0.72
Easy
20,414
https://leetcode.com/problems/sort-integers-by-the-number-of-1-bits/discuss/939058/Python-no-predefine-function-count-etc.-simple
class Solution: def sortByBits(self, arr: List[int]) -> List[int]: #Brian Kernighan's Algorithm for counting bits O(logn) def countbit(num): count = 0 while num: num &= (num-1) count += 1 return count mylist = [(countbit(num), num) for num in arr] return [x for _, x in sorted(mylist)]
sort-integers-by-the-number-of-1-bits
Python no predefine function, count etc. simple
serdarkuyuk
1
197
sort integers by the number of 1 bits
1,356
0.72
Easy
20,415
https://leetcode.com/problems/sort-integers-by-the-number-of-1-bits/discuss/778463/Different-python-approach-(Bucket-Sort)
class Solution: def sortByBits(self, arr: List[int]) -> List[int]: # maximum number of 1 bits for all numbers up to 10000 is 13 buckets=[[] for _ in range(14)] def count_bits(n): count = 0 while n > 0: count += n&1 == 1 n = n>>1 return count for n in sorted(arr): buckets[count_bits(n)].append(n) res = [] for x in buckets: res.extend(x) return res
sort-integers-by-the-number-of-1-bits
Different python approach (Bucket Sort)
amrmahmoud96
1
218
sort integers by the number of 1 bits
1,356
0.72
Easy
20,416
https://leetcode.com/problems/sort-integers-by-the-number-of-1-bits/discuss/2836525/easy-solution-python
class Solution: def sortByBits(self, arr: List[int]) -> List[int]: return sorted(arr, key = lambda x: (bin(x).count("1"),x))
sort-integers-by-the-number-of-1-bits
easy solution python
hudada421
0
5
sort integers by the number of 1 bits
1,356
0.72
Easy
20,417
https://leetcode.com/problems/sort-integers-by-the-number-of-1-bits/discuss/2819342/beats-99-in-time-using-lambda
class Solution: def sortByBits(self, arr: List[int]) -> List[int]: arr.sort() arr.sort(key=lambda x:format(x,'b').count('1')) return arr
sort-integers-by-the-number-of-1-bits
beats 99% in time using lambda
rama_krishna044
0
4
sort integers by the number of 1 bits
1,356
0.72
Easy
20,418
https://leetcode.com/problems/sort-integers-by-the-number-of-1-bits/discuss/2793023/Python-3-solution-easy-to-understand
class Solution: def sortByBits(self, arr: List[int]) -> List[int]: bin_dict = {} count_dict = {} for num in arr: bin_dict[num] = str(bin(num)[2:]).count('1') count_dict[num] = count_dict.get(num,0) + 1 bin_dict = dict(sorted(bin_dict.items(), key= lambda x : x[1])) final_arr = [] lst = [] last = None for key,val in bin_dict.items(): if last == None: lst = lst + [key] * count_dict.get(key) last = val elif last == val: lst = lst + [key] * count_dict.get(key) last = val else: final_arr = final_arr + sorted(lst) lst = [] lst = lst + [key] * count_dict.get(key) last = val return final_arr + sorted(lst)
sort-integers-by-the-number-of-1-bits
Python 3 solution easy to understand
user4363G
0
16
sort integers by the number of 1 bits
1,356
0.72
Easy
20,419
https://leetcode.com/problems/sort-integers-by-the-number-of-1-bits/discuss/2756013/1356.-Sort-Integers-by-The-Number-of-1-Bits-or-Python-Solution
class Solution(object): def sortByBits(self, arr): bits = {} for i in range(len(arr)): count = list("{0:b}".format(arr[i])).count("1") if not bits.get(count): bits[count] = [arr[i]] else: bits[count].append(arr[i]) temp = [] for count,values in bits.items(): values.sort() temp.extend(values) return temp ``` Please upvote if helpful!
sort-integers-by-the-number-of-1-bits
1356. Sort Integers by The Number of 1 Bits | Python Solution
ygygupta0
0
22
sort integers by the number of 1 bits
1,356
0.72
Easy
20,420
https://leetcode.com/problems/sort-integers-by-the-number-of-1-bits/discuss/2743947/Python-solution-by-Counting-bits-set-Brian-Kernighan's-way
class Solution: def sortByBits(self, arr: List[int]) -> List[int]: arr.sort() result = [] for n in arr: digit = n count_bits = 0 # Count the total number of set bits in `n` # Counting bits set, Brian Kernighan's way while n: n = n & (n - 1) # Clear the least significant bit set count_bits += 1 # print(f'{digit} == {count_bits} bits') result.append((digit, count_bits)) return [i[0] for i in sorted(result, key=lambda item: item[1])]
sort-integers-by-the-number-of-1-bits
Python solution by Counting bits set, Brian Kernighan's way
Kazila
0
18
sort integers by the number of 1 bits
1,356
0.72
Easy
20,421
https://leetcode.com/problems/sort-integers-by-the-number-of-1-bits/discuss/2702731/PYTHON3-BEST
class Solution: def sortByBits(self, arr: List[int]) -> List[int]: arr_b = [(bin(n)[2:].count('1'), len(bin(n)[2:]),n) for n in arr] arr_b.sort() return [n[2] for n in arr_b]
sort-integers-by-the-number-of-1-bits
PYTHON3 BEST
Gurugubelli_Anil
0
30
sort integers by the number of 1 bits
1,356
0.72
Easy
20,422
https://leetcode.com/problems/sort-integers-by-the-number-of-1-bits/discuss/2692323/One-line-python-code
class Solution: def sortByBits(self, arr: List[int]) -> List[int]: # both one line codes work #return sorted(arr, key=lambda x: [bin(x).count('1'), x]) return sorted(sorted(arr), key = lambda x: format(x, "b").count("1"))
sort-integers-by-the-number-of-1-bits
One line python code
Jiaming-Hu
0
12
sort integers by the number of 1 bits
1,356
0.72
Easy
20,423
https://leetcode.com/problems/sort-integers-by-the-number-of-1-bits/discuss/2682947/Sort-by-set-bits
class Solution: def sortByBits(self, arr: List[int]) -> List[int]: arr=sorted(arr) d=dict() for i in arr: onescount=bin(i)[2:].count('1') if onescount not in d: d[onescount]=[i] else: d[onescount].append(i) asc=dict(sorted(d.items(),key=lambda x:x[0])) # l=[] # for val in asc.values(): # l+=val # return l j=0 for val in asc.values(): for i in val: arr[j]=i j+=1 return arr
sort-integers-by-the-number-of-1-bits
Sort by set bits
shivansh2001sri
0
43
sort integers by the number of 1 bits
1,356
0.72
Easy
20,424
https://leetcode.com/problems/sort-integers-by-the-number-of-1-bits/discuss/2670160/Python3-oror-O(NlogN)-solution
class Solution: def sortByBits(self, arr: List[int]) -> List[int]: lst = [] arr.sort() for i in arr: total = 0 for j in range(32): if (1<<j)&amp;i: total+=1 lst.append((i,total)) lst.sort(key = lambda x:x[1]) res = [] for i in range(len(lst)): res.append(lst[i][0]) return res
sort-integers-by-the-number-of-1-bits
Python3 || O(NlogN) solution
shacid
0
107
sort integers by the number of 1 bits
1,356
0.72
Easy
20,425
https://leetcode.com/problems/sort-integers-by-the-number-of-1-bits/discuss/2662859/One-Liner-in-Python3-oror-Easy-Solution
class Solution: def sortByBits(self, arr: List[int]) -> List[int]: return sorted(sorted(arr),key=lambda x:bin(x)[2:].count('1'))
sort-integers-by-the-number-of-1-bits
One-Liner in Python3 || Easy Solution
Rage-Fox
0
55
sort integers by the number of 1 bits
1,356
0.72
Easy
20,426
https://leetcode.com/problems/sort-integers-by-the-number-of-1-bits/discuss/2613787/Python3-Easy-One-Liner%3A-sorted()-by-multiple-keys
class Solution: def sortByBits(self, arr: List[int]) -> List[int]: return sorted(arr, key=lambda num: (bin(num).count('1'), num))
sort-integers-by-the-number-of-1-bits
[Python3] Easy One-Liner: sorted() by multiple keys
ivnvalex
0
155
sort integers by the number of 1 bits
1,356
0.72
Easy
20,427
https://leetcode.com/problems/sort-integers-by-the-number-of-1-bits/discuss/2545438/Python-Simple-Clean-2-Approach
class Solution: def sortByBits(self, arr: List[int]) -> List[int]: d = {} for i in arr: f = bin(i).count('1') d[f] = d.get(f,[]) + [i] res = [] for i in sorted(d.keys()): res.extend(sorted(d[i])) return res
sort-integers-by-the-number-of-1-bits
[Python] Simple, Clean, 2-Approach
girraj_14581
0
201
sort integers by the number of 1 bits
1,356
0.72
Easy
20,428
https://leetcode.com/problems/sort-integers-by-the-number-of-1-bits/discuss/2545438/Python-Simple-Clean-2-Approach
class Solution: def sortByBits(self, arr: List[int]) -> List[int]: return sorted(arr, key=lambda x: (bin(x).count('1'),x))
sort-integers-by-the-number-of-1-bits
[Python] Simple, Clean, 2-Approach
girraj_14581
0
201
sort integers by the number of 1 bits
1,356
0.72
Easy
20,429
https://leetcode.com/problems/sort-integers-by-the-number-of-1-bits/discuss/2031615/Python3-i-think-is-not-the-best-solution-but-i-got-runtime-faster-than-96.94
class Solution: def sortByBits(self, arr: List[int]) -> List[int]: new = [] arr.sort() for n in arr: bit = list(bin(n).replace("0b", "").replace("0", "")) length = bit.count('1') new.append({ "lengthBit": length, "n": n }) def sortBy(e): return e['lengthBit'] new.sort(key=sortBy) for i in range(len(new)): new[i] = new[i]["n"] return new
sort-integers-by-the-number-of-1-bits
[Python3] i think is not the best solution, but i got runtime faster than 96.94%
Shiyinq
0
127
sort integers by the number of 1 bits
1,356
0.72
Easy
20,430
https://leetcode.com/problems/sort-integers-by-the-number-of-1-bits/discuss/1941455/easy-python-code
class Solution: def sortByBits(self, arr: List[int]) -> List[int]: d = {} output = [] d_key = [] for i in arr: x = str(bin(i)) if x.count("1") in d: d[x.count("1")].append(i) else: d[x.count("1")] = [i] for i in d.keys(): d_key.append(i) d_key.sort() for i in d_key: output += sorted(d[i]) return output
sort-integers-by-the-number-of-1-bits
easy python code
dakash682
0
138
sort integers by the number of 1 bits
1,356
0.72
Easy
20,431
https://leetcode.com/problems/sort-integers-by-the-number-of-1-bits/discuss/1898750/Python-3-Hamming-weight-with-heap-sort
class Solution: def sortByBits(self, arr: List[int]) -> List[int]: def count_bits(num): count = 0 while num > 0: num &amp;= (num-1) count += 1 return count res = [] for value in arr: heapq.heappush(res, (count_bits(value), value)) return [heapq.heappop(res)[1] for _ in range(len(res))]
sort-integers-by-the-number-of-1-bits
Python 3 Hamming weight with heap sort
think989
0
85
sort integers by the number of 1 bits
1,356
0.72
Easy
20,432
https://leetcode.com/problems/sort-integers-by-the-number-of-1-bits/discuss/1882577/Python3-2-lines-simple-lambda-sort-on-bit-summation
class Solution: def sortByBits(self, arr: List[int]) -> List[int]: # arr.sort() # arr.sort(key=lambda x: sum([int(x) for x in list(bin(x)[2:]) if x == '1'])) arr.sort(key=lambda x: (sum([int(x) for x in list(bin(x)[2:]) if x == '1']),x)) return arr
sort-integers-by-the-number-of-1-bits
Python3 2 lines simple lambda sort on bit summation
Tallicia
0
91
sort integers by the number of 1 bits
1,356
0.72
Easy
20,433
https://leetcode.com/problems/sort-integers-by-the-number-of-1-bits/discuss/1809345/1-Line-Python-Solution-oror-90-Faster-oror-Memory-less-than-92
class Solution: def sortByBits(self, arr: List[int]) -> List[int]: return [y for (x,y) in sorted([(bin(arr[i]).count('1'), arr[i]) for i in range(len(arr))])]
sort-integers-by-the-number-of-1-bits
1-Line Python Solution || 90% Faster || Memory less than 92%
Taha-C
0
120
sort integers by the number of 1 bits
1,356
0.72
Easy
20,434
https://leetcode.com/problems/sort-integers-by-the-number-of-1-bits/discuss/1800867/Simple-Python-Solution
class Solution: def sortByBits(self, arr: List[int]) -> List[int]: arr.sort() brr=[] for i in arr: brr.append([i, bin(i).replace("0b","").count("1")]) brr.sort(key = lambda x: x[1]) ans=[] for element, bit_count in brr: ans.append(element) print(ans) return ans
sort-integers-by-the-number-of-1-bits
Simple Python Solution
Siddharth_singh
0
120
sort integers by the number of 1 bits
1,356
0.72
Easy
20,435
https://leetcode.com/problems/sort-integers-by-the-number-of-1-bits/discuss/1742830/Python-dollarolution
class Solution: def sortByBits(self, arr: List[int]) -> List[int]: d, v, l = {}, [], [] arr = sorted(arr) for i in arr: if i in d: v.append(i) continue d[i] = bin(i)[2:].count('1') d = dict(sorted(d.items(), key=lambda item: item[1])) l = list(d.keys()) while v != []: i = l.index(v[0]) l.insert(i,v[0]) v.remove(v[0]) return l
sort-integers-by-the-number-of-1-bits
Python $olution
AakRay
0
132
sort integers by the number of 1 bits
1,356
0.72
Easy
20,436
https://leetcode.com/problems/sort-integers-by-the-number-of-1-bits/discuss/1555602/Python-Easy-Solution-or-Bit-Magic-and-Hash-Table
class Solution: def countBits(self, n): c = 0 while n > 0: if n &amp; 1: c += 1 n >>= 1 return c def sortByBits(self, arr: List[int]) -> List[int]: res = {} arr.sort() for i in range(len(arr)): bits = self.countBits(arr[i]) if res.get(bits): res[bits].append(arr[i]) else: res[bits] = [arr[i]] ans = [] for i in range(15): # Since we have only 14 bits (10^4) if res.get(i): ans += res[i] return ans
sort-integers-by-the-number-of-1-bits
Python Easy Solution | Bit Magic & Hash Table
leet_satyam
0
265
sort integers by the number of 1 bits
1,356
0.72
Easy
20,437
https://leetcode.com/problems/sort-integers-by-the-number-of-1-bits/discuss/882713/Python-2-lines-simple-solution
class Solution: def sortByBits(self, arr: List[int]) -> List[int]: arr.sort(key=lambda n: (bin(n).count('1'), n)) return arr
sort-integers-by-the-number-of-1-bits
Python 2 lines simple solution
stom1407
0
153
sort integers by the number of 1 bits
1,356
0.72
Easy
20,438
https://leetcode.com/problems/sort-integers-by-the-number-of-1-bits/discuss/728515/Python-easy-to-understand
class Solution: def count1s(self, num): count = 0 while num >= 1: if num%2: count += 1 num = num//2 return count def cmp(self, vals): l,r = vals return r * 10000 + l def sortByBits(self, arr: List[int]) -> List[int]: new_arr = [[arr[i], self.count1s(arr[i])] for i,_ in enumerate(arr)] sorted_new_arr = sorted(new_arr, key = self.cmp) result = [sorted_new_arr[i][0] for i,_ in enumerate(sorted_new_arr)] return result
sort-integers-by-the-number-of-1-bits
Python, easy to understand
mrpositron
0
288
sort integers by the number of 1 bits
1,356
0.72
Easy
20,439
https://leetcode.com/problems/number-of-substrings-containing-all-three-characters/discuss/851021/Python-3-or-Two-Pointers-or-Explanation
class Solution: def numberOfSubstrings(self, s: str) -> int: a = b = c = 0 # counter for letter a/b/c ans, i, n = 0, 0, len(s) # i: slow pointer for j, letter in enumerate(s): # j: fast pointer if letter == 'a': a += 1 # increment a/b/c accordingly elif letter == 'b': b += 1 else: c += 1 while a > 0 and b > 0 and c > 0: # if all of a/b/c are contained, move slow pointer ans += n-j # count possible substr, if a substr ends at j, then there are n-j substrs to the right that are containing all a/b/c if s[i] == 'a': a -= 1 # decrement counter accordingly elif s[i] == 'b': b -= 1 else: c -= 1 i += 1 # move slow pointer return ans
number-of-substrings-containing-all-three-characters
Python 3 | Two Pointers | Explanation
idontknoooo
23
1,200
number of substrings containing all three characters
1,358
0.631
Medium
20,440
https://leetcode.com/problems/number-of-substrings-containing-all-three-characters/discuss/2101802/Python-easy-to-read-and-understand-or-sliding-window
class Solution: def numberOfSubstrings(self, s: str) -> int: a, b, c = 0, 0, 0 start, ans, n = 0, 0, len(s) i = 0 while i < n: if s[i] == 'a': a += 1 elif s[i] == 'b': b += 1 else: c += 1 while a > 0 and b > 0 and c > 0: ans += (n-i) if s[start] == 'a': a -= 1 elif s[start] == 'b': b -= 1 else: c -= 1 start += 1 i += 1 return ans
number-of-substrings-containing-all-three-characters
Python easy to read and understand | sliding window
sanial2001
2
149
number of substrings containing all three characters
1,358
0.631
Medium
20,441
https://leetcode.com/problems/number-of-substrings-containing-all-three-characters/discuss/1918120/Python-Sliding-Window-Approach-or-O(N)-Time-Complexity
class Solution: def numberOfSubstrings(self, s: str) -> int: HashMap = {c :0 for c in 'abc'} countS = 0 r = 0 for l in range(len(s)): while not all(HashMap.values()) and r < len(s): HashMap[s[r]] += 1 r += 1 if all(HashMap.values()): countS += len(s) - r +1 HashMap[s[l]] -= 1 return countS
number-of-substrings-containing-all-three-characters
Python - Sliding Window Approach | O(N) Time Complexity
dayaniravi123
1
72
number of substrings containing all three characters
1,358
0.631
Medium
20,442
https://leetcode.com/problems/number-of-substrings-containing-all-three-characters/discuss/1834215/Python-Solution-oror-Sliding-Window-oror-With-Approach
class Solution: def numberOfSubstrings(self,s): windowStart = 0 maxLengthcount = 0 hash_map = dict() for windowEnd in range(len(s)): curr_char = s[windowEnd] hash_map[curr_char] = hash_map.get(curr_char,0) + 1 while(len(hash_map)==3): left_char = s[windowStart] hash_map[left_char] -= 1 if(hash_map[left_char]==0): del hash_map[left_char] maxLengthcount += len(s)-windowEnd windowStart += 1 return maxLengthcount for _ in range(int(input())): s = input() obj = Solution() answer = obj.numberOfSubstrings(s) print(answer)
number-of-substrings-containing-all-three-characters
Python Solution || Sliding Window || With Approach
aashutoshjha21022002
1
161
number of substrings containing all three characters
1,358
0.631
Medium
20,443
https://leetcode.com/problems/number-of-substrings-containing-all-three-characters/discuss/2830098/Python-Solution-SLIDING-WINDOW-APPROACH-oror-Explained-100
class Solution: def numberOfSubstrings(self, s: str) -> int: ca=0 #for count of a cb=0 #for count of b cc=0 #for count of c ans=0 #count of total substring forming with 'a' and 'b' and 'c' j=0 #index for moving forward in string s after at least 1 -> 'a','b','c' is found for i in range(len(s)): #traversing in s if s[i]=='a': # 'a' found, store count ca+=1 elif s[i]=='b': # 'b' found, store count cb+=1 else: # 'c' found, store count cc+=1 while ca>0 and cb>0 and cc>0: #means at least 1 -> 'a','b','c' is found #this telling if the a,b,c is found then after appending remaining substring of s to this chosen #string (having at least 1 -> 'a','b','c') will all be VALID (means containing a,b,c in it) #BETTER DO IT IN PEN PAPER FOR BETTER UNDERSTANDING ans+=len(s)-i #NOW THE WINDOW IS FORMED , ITS TIME TO MOVE THE INDEX FORWARD #AND CHECK IF FORWARD SUBSTRING CARRYING a,b,c or not -> will be checking from j #traversing in s after i #if s[j]=='a' or 'b' or 'c' found -> decrement the counts if s[j]=='a': ca-=1 elif s[j]=='b': cb-=1 else: cc-=1 #if any counts goes to 0, time to move the window (come out to this current while loop) j+=1 #move index if j==len(s): #j reached to end of s return ans return ans
number-of-substrings-containing-all-three-characters
Python Solution - SLIDING WINDOW APPROACH || Explained 100%✔
T1n1_B0x1
0
2
number of substrings containing all three characters
1,358
0.631
Medium
20,444
https://leetcode.com/problems/number-of-substrings-containing-all-three-characters/discuss/2771768/Python-Sliding-Window
class Solution: def numberOfSubstrings(self, s: str) -> int: def helper(s): hm = defaultdict(int) hs, l, res = set(), 0, 0 for r in range(len(s)): hm[s[r]] += 1 hs.add(s[r]) while len(hs) == 3: hm[s[l]] -= 1 if not hm[s[l]]: hs.remove(s[l]) l += 1 res += r - l + 1 return len(s) * (len(s) + 1) // 2 - res return helper(s)
number-of-substrings-containing-all-three-characters
Python Sliding Window
JSTM2022
0
4
number of substrings containing all three characters
1,358
0.631
Medium
20,445
https://leetcode.com/problems/number-of-substrings-containing-all-three-characters/discuss/2386635/Python-Solution-or-Two-Pointer-Classic-Sliding-Window-or-90-Faster
class Solution: def numberOfSubstrings(self, s: str) -> int: start = 0 end = 0 counter = 0 store = {'a' : 0, 'b' : 0, 'c' : 0} for end in range(len(s)): store[s[end]] += 1 while store['a'] > 0 and store['b'] > 0 and store['c'] > 0: counter += (len(s) - end) store[s[start]] -= 1 start += 1 return counter
number-of-substrings-containing-all-three-characters
Python Solution | Two Pointer - Classic Sliding Window | 90% Faster
Gautam_ProMax
0
90
number of substrings containing all three characters
1,358
0.631
Medium
20,446
https://leetcode.com/problems/number-of-substrings-containing-all-three-characters/discuss/2276343/Python-3-easy-and-concise
class Solution: def numberOfSubstrings(self, s: str) -> int: a,res=[-1]*3,0 for i,x in enumerate(s): a[ord(x)-ord('a')]=i res+=min(a)+1 return res
number-of-substrings-containing-all-three-characters
[Python 3] easy and concise
gabhay
0
41
number of substrings containing all three characters
1,358
0.631
Medium
20,447
https://leetcode.com/problems/number-of-substrings-containing-all-three-characters/discuss/1617541/Most-intuitive-python3-solution
class Solution: def numberOfSubstrings(self, s: str) -> int: from collections import defaultdict mydict=defaultdict(int) n=len(s) res=0 left=0 for right in range(n): mydict[s[right]]+=1 while len(mydict)==3: res+=(n-right) mydict[s[left]]-=1 if mydict[s[left]]==0: mydict.pop(s[left]) left+=1 return res
number-of-substrings-containing-all-three-characters
Most intuitive python3 solution
Karna61814
0
83
number of substrings containing all three characters
1,358
0.631
Medium
20,448
https://leetcode.com/problems/number-of-substrings-containing-all-three-characters/discuss/1302094/Python3-or-Easy
class Solution: def numberOfSubstrings(self, s: str) -> int: start = 0 seen = {} n = len(s) i = 0 ans = 0 while i<n: seen[s[i]] = seen.get(s[i], 0)+1 while len(seen) == 3: ans += (n-i) seen[s[start]] -= 1 if seen[s[start]] == 0: seen.pop(s[start]) start+=1 i+=1 return ans
number-of-substrings-containing-all-three-characters
Python3 | Easy
Sanjaychandak95
0
65
number of substrings containing all three characters
1,358
0.631
Medium
20,449
https://leetcode.com/problems/number-of-substrings-containing-all-three-characters/discuss/1107746/Python3-locations
class Solution: def numberOfSubstrings(self, s: str) -> int: ans = 0 loc = [-1]*3 for i, c in enumerate(s): loc[ord(c)-97] = i ans += max(0, min(loc)+1) return ans
number-of-substrings-containing-all-three-characters
[Python3] locations
ye15
0
72
number of substrings containing all three characters
1,358
0.631
Medium
20,450
https://leetcode.com/problems/number-of-substrings-containing-all-three-characters/discuss/1790384/Easy-Python-Sliding-Window
class Solution: def numberOfSubstrings(self, s: str) -> int: if s == None and len(s) < 3: return None n = len(s) i, j = 0, 0 result = 0 hashmap = {} for j in range(n): hashmap[s[j]] = hashmap.get(s[j], 0) + 1 while i < j and len(hashmap) == 3: result += (n - j) hashmap[s[i]] -= 1 if hashmap[s[i]] == 0: del hashmap[s[i]] i += 1 return result
number-of-substrings-containing-all-three-characters
Easy Python Sliding Window
lolapeng88
-1
73
number of substrings containing all three characters
1,358
0.631
Medium
20,451
https://leetcode.com/problems/number-of-substrings-containing-all-three-characters/discuss/772829/Python-1-liner
class Solution: def numberOfSubstrings(self, s: str) -> int: return reduce(lambda y,x:[y[0]+1+min(y[1].values()), dict(y[1],**{x[1]:x[0]})], enumerate(s+'a'),[0,defaultdict(lambda:-1)])[0]
number-of-substrings-containing-all-three-characters
Python 1-liner
ekovalyov
-4
236
number of substrings containing all three characters
1,358
0.631
Medium
20,452
https://leetcode.com/problems/count-all-valid-pickup-and-delivery-options/discuss/1825566/Python-oror-Easy-To-Understand-oror-98-Faster-oror-Maths
class Solution: def countOrders(self, n: int) -> int: n=2*n ans=1 while n>=2: ans = ans *((n*(n-1))//2) n-=2 ans=ans%1000000007 return ans
count-all-valid-pickup-and-delivery-options
✅Python || Easy To Understand || 98% Faster || Maths
rahulmittall
3
53
count all valid pickup and delivery options
1,359
0.629
Hard
20,453
https://leetcode.com/problems/count-all-valid-pickup-and-delivery-options/discuss/1825880/Python3-or-98-faster-or-one-line
class Solution: def countOrders(self, n: int) -> int: return (math.factorial(n * 2) >> n) % (10**9 + 7)
count-all-valid-pickup-and-delivery-options
Python3 | 98% faster | one line
Anilchouhan181
2
58
count all valid pickup and delivery options
1,359
0.629
Hard
20,454
https://leetcode.com/problems/count-all-valid-pickup-and-delivery-options/discuss/1464192/Intuitive-topdown-recursion
class Solution: def countOrders(self, n: int) -> int: if n == 1: return 1 # Only way to pickup and deliver 1 order return int(((2*n *(2*n-1))/2 * self.countOrders(n-1))%(10**9 + 7))
count-all-valid-pickup-and-delivery-options
Intuitive topdown recursion
worker-bee
2
228
count all valid pickup and delivery options
1,359
0.629
Hard
20,455
https://leetcode.com/problems/count-all-valid-pickup-and-delivery-options/discuss/1826302/Intuitive-solution-Detailed-Explantation
class Solution: def countOrders(self, n: int) -> int: """ Considering we know the solution for n = 1: (P1, D1), now we want to find the solution for n = 2: the idea is that: we can insert P2 at 3 positions: either before P1, between P1 and D1, or after D1. lets look at each case separately: - case (P2, P1, D1): now we can place D2 in 3 possible positions: after P2, or after P1 or after D1. - case (P1, P2, D1): we can only place D2 after P2, or after D1. - case (P1, D1, P2) the only place for D2 is right after P2. The total possible solution for n = 2 is therefore 3+2+1 = 6 Same logic now to find n = 3. the solutions for n = 2 are: (P1,P2,D1,D2), (P1,P2,D2,D1), (P1,D1,P2,D2), (P2,P1,D1,D2), (P2,P1,D2,D1), (P2,D2,P1,D1) For each of those solutions, we may place P3 at 5 different places: at position 1, or 2, or 3, or 4 or at the end. if we placed P3 at position 1, then D3 can be placed either at position 2, 3, 4, 5 or at the end. Giving us 5 possibilities. now if P3 is at position 2, then D3 can only by at 3, 4, 5, or at the end. 4 possibilities. and so on. Basically, for each of the n = 2 solution, we have 5+4+3+2+1 = 15 solutions. So the number total solutions for n = 3 is size(solution n = 2) * 15, which is here 6 * 15 = 90. Now we can use a DP table (or just a variable to optimize space) to track the number of solutions for n-1. we also need the length of each solution for layer n-1. That can be found easily (for a layer i, the length of solution is n 2*i) and we have (2i+1) + (2i) + (2i-1) + ... + (1) solutions. Which is an arithmetic sequence. That sum is (2i+1)*(2i+1 + 1)/2 Below is the implementation in Python3: """ dp = [1]*n modulo = 1e9 +7 for i in range(1, n): x = 2*i + 1 dp[i] = dp[i-1] * (x*(x+1)//2) % modulo return int(dp[-1])
count-all-valid-pickup-and-delivery-options
Intuitive solution, Detailed Explantation
dyxuki
1
23
count all valid pickup and delivery options
1,359
0.629
Hard
20,456
https://leetcode.com/problems/count-all-valid-pickup-and-delivery-options/discuss/1823573/Python-Simple-Python-Solution-Using-Permutation-Concept
class Solution: def countOrders(self, n: int) -> int: result = 1 modulo = 1000000007 for i in range(1,n+1): result = result * i result = result % modulo result = result * (2*i - 1) result = result % modulo result = result % modulo return result
count-all-valid-pickup-and-delivery-options
[ Python ] ✔✔ Simple Python Solution Using Permutation Concept 🔥✌
ASHOK_KUMAR_MEGHVANSHI
1
35
count all valid pickup and delivery options
1,359
0.629
Hard
20,457
https://leetcode.com/problems/count-all-valid-pickup-and-delivery-options/discuss/1823317/python-O(n)-solution-faster-than-93-with-explanation
class Solution: def countOrders(self, n: int) -> int: cnt = 1 MOD = 1000000007 for i in range (1, 2 * n + 1): cnt *= i if (i % 2) else (i // 2) cnt %= MOD return cnt
count-all-valid-pickup-and-delivery-options
[python] O(n) solution faster than 93% with explanation
hcet
1
114
count all valid pickup and delivery options
1,359
0.629
Hard
20,458
https://leetcode.com/problems/count-all-valid-pickup-and-delivery-options/discuss/2412945/Python-1-Line-or-The-Simplest-Solution-or-Direct-Formula
class Solution: def countOrders(self, n: int) -> int: return (factorial(2*n) // 2**n) % (10**9 + 7)
count-all-valid-pickup-and-delivery-options
[Python] 1 Line | The Simplest Solution | Direct Formula
lan32
0
47
count all valid pickup and delivery options
1,359
0.629
Hard
20,459
https://leetcode.com/problems/count-all-valid-pickup-and-delivery-options/discuss/2352427/Python3-or-DP-or-Memoization-or-Explained
class Solution: def countOrders(self, n: int) -> int: MOD = 1000000007 @cache def res(a = n, b = 0): if a == 0 and b == 0: return 1 elif a > 0 and b > 0: return (a * res(a-1, b+1) + b * res(a, b-1)) % MOD elif a > 0: return (a * res(a-1, b+1)) % MOD else: return (b * res(a, b-1)) % MOD return res()
count-all-valid-pickup-and-delivery-options
Python3 | DP | Memoization | Explained
DheerajGadwala
0
26
count all valid pickup and delivery options
1,359
0.629
Hard
20,460
https://leetcode.com/problems/count-all-valid-pickup-and-delivery-options/discuss/1826482/python-3-oror-recursion-oror-O(n)-oror-O(1)
class Solution: def countOrders(self, n: int) -> int: if n == 1: return 1 return ((2 * n ** 2 - n) * self.countOrders(n - 1)) % (10 ** 9 + 7)
count-all-valid-pickup-and-delivery-options
python 3 || recursion || O(n) || O(1)
dereky4
0
24
count all valid pickup and delivery options
1,359
0.629
Hard
20,461
https://leetcode.com/problems/count-all-valid-pickup-and-delivery-options/discuss/1826474/Python-Solution-O(n)
class Solution: def countOrders(self, n: int) -> int: mod = 10**9+7 fact, pows = 1, n for i in range(2, n*2+1): if pows > 0: i /= 2 pows -= 1 fact = (fact * i) % mod return int(fact) % mod
count-all-valid-pickup-and-delivery-options
Python Solution, O(n)
xyrolle7
0
9
count all valid pickup and delivery options
1,359
0.629
Hard
20,462
https://leetcode.com/problems/count-all-valid-pickup-and-delivery-options/discuss/1825520/Python-Solution-using-DPorT%3AO(n)orS%3AO(n)
class Solution: def countOrders(self, n: int) -> int: if n == 1: return 1 if n == 2: return 6 dp = [0, 1, 6] mod = pow(10, 9) + 7 for i in range(3, n + 1): odd_number = 2 * i - 1 permutation = odd_number * (odd_number + 1) // 2 dp.append((dp[i - 1] * permutation)%mod) return dp[-1]
count-all-valid-pickup-and-delivery-options
Python Solution using DP|T:O(n)|S:O(n)
pradeep288
0
17
count all valid pickup and delivery options
1,359
0.629
Hard
20,463
https://leetcode.com/problems/count-all-valid-pickup-and-delivery-options/discuss/1824790/Python-5-lines-DP-bottom-up-O(n)-solution
class Solution: def countOrders(self, n: int) -> int: # Formula: n * <orders in n-1> * (<steps in n-1> + 1) # - n ways to start an additional pickup order # - (<steps in n-1> + 1) ways to insert an additional delivery order # Case 1 (Base case): # - 1 order # - 2 steps # Case 2: # = n * dp(n-1) * ((n-1)*2 + 1) # = n * dp(n-1) * (2n-1) # = 2 * 1 * 3 # = 6 # Case 3: # = 3 * 6 * 5 # = 90 dp = [0] * (n+1) dp[1] = 1 for i in range(2, n+1): dp[i] = (i * dp[i-1] * (2*i - 1)) % (10 ** 9 + 7) return dp[n]
count-all-valid-pickup-and-delivery-options
Python 5 lines DP bottom up O(n) solution
slbteam08
0
51
count all valid pickup and delivery options
1,359
0.629
Hard
20,464
https://leetcode.com/problems/count-all-valid-pickup-and-delivery-options/discuss/1107749/Python3-dp
class Solution: def countOrders(self, n: int) -> int: @cache def fn(n): """Return count of valid pickup and delivery options for n orders.""" if n == 1: return 1 # boundary condition return n*(2*n-1)*fn(n-1) return fn(n) % 1_000_000_007
count-all-valid-pickup-and-delivery-options
[Python3] dp
ye15
0
167
count all valid pickup and delivery options
1,359
0.629
Hard
20,465
https://leetcode.com/problems/count-all-valid-pickup-and-delivery-options/discuss/1107749/Python3-dp
class Solution: def countOrders(self, n: int) -> int: ans = 1 for x in range(2, n+1): ans = (ans*x*(2*x-1)) % 1_000_000_007 return ans
count-all-valid-pickup-and-delivery-options
[Python3] dp
ye15
0
167
count all valid pickup and delivery options
1,359
0.629
Hard
20,466
https://leetcode.com/problems/number-of-days-between-two-dates/discuss/1814530/Python3-Solution-from-Scratch-NOT-USING-DATETIME
class Solution: def daysBetweenDates(self, date1: str, date2: str) -> int: def f_date(date): # calculates days passed since '1900-01-01' year0 = '1900' year1, month1, day1 = date.split('-') days = 0 for y in range(int(year0), int(year1)): days += 365 if y%100 == 0: if y%400 == 0: days += 1 else: if y%4 == 0: days += 1 for m in range(int(month1)): if m in [1, 3, 5, 7, 8, 10, 12]: days += 31 if m in [4, 6, 9, 11]: days += 30 if m == 2: days += 28 if int(year1)%100 == 0: if int(year1)%400 == 0: days += 1 else: if int(year1)%4 ==0: days += 1 days += int(day1) return days return abs(f_date(date1) - f_date(date2))
number-of-days-between-two-dates
Python3 Solution from Scratch - NOT USING DATETIME
rmateusc
3
617
number of days between two dates
1,360
0.476
Easy
20,467
https://leetcode.com/problems/number-of-days-between-two-dates/discuss/2584553/Python3-95-ms-Faster-Clean-commented-Solution
class Solution: def leap_year(self,year): return not(year % 400) or year % 100 and not(year % 4) # Leap year Condition def count_years_days(self,year): year_days = 0 for i in range(1971,year): # We need some reference 1971 is reference here lowest possible year in constairnts. You can take anything which will be lesser than given two dates. # To find distance between a and b. We are taking some reference which is smaller than both a and b. like if we need to find 100 - 200 we can take 0 as reference and find 0 - 100 and 0- 200 then find 100 - 200 which is -100 easily. # Directly if we try to find a - b many conditions will be there and it will end up having an headache if self.leap_year(i): year_days += 366 else: year_days += 365 return year_days def count_month_days(self,m,year): month = [0,31,28,31,30,31,30,31,31,30,31,30,31] month_days = 0 for i in range(1,m): if i==2: # i is number of month like 1 for Jan and 2 for feb # for leap year feb will have 29 days i.e. x will be 1 month_days += month[i] + int(self.leap_year(year)) else: month_days += month[i] return month_days def daysBetweenDates(self, date1: str, date2: str) -> int: year1,month1,date1 = map(int,date1.split("-")) year2,month2,date2 = map(int,date2.split("-")) return abs ((self.count_years_days(year1) + self.count_month_days(month1,year1) + date1) - (self.count_years_days(year2) + self.count_month_days(month2,year2) + date2))
number-of-days-between-two-dates
Python3 95 ms Faster Clean commented Solution
abhisheksanwal745
0
187
number of days between two dates
1,360
0.476
Easy
20,468
https://leetcode.com/problems/number-of-days-between-two-dates/discuss/2230491/python-soltuion-straight-forward
class Solution: def daysBetweenDates(self, date1: str, date2: str) -> int: # use a helper func to find out how many days from the date to the base year (1971 as constraint) def helper(y,m,d): days = 0 month_days = [31,28,31,30,31,30,31,31,30,31,30,31] # days in each month days += (y - 1971) * 365 # assume no leap yaer for _ in range(1972, y, 4): # now adding leap years, why 1972, becuze 1972 is the first leap year days += 1 # days += (y - 1971) // 4 >>>>>> I am not able ot find out a math way to calculate here, anyone help? . days += sum(month_days[:m-1]) # Jun-20, 0-indexed month_days, hence m-1 days += d # Tips: after google a bit about leap year calculate, # year 300, 700, 1800 should div by 400, not 4 only. i was thought 4 is always for leap year... if m > 2 and ((y % 4 == 0 and y % 100 != 0) or y % 400 == 0): days += 1 return days y1,m1,d1 = date1.split('-') y2,m2,d2 = date2.split('-') days1 = helper(int(y1), int(m1), int(d1)) days2 = helper(int(y2), int(m2), int(d2)) return abs(days1 - days2)
number-of-days-between-two-dates
python soltuion straight forward
hardernharder
0
144
number of days between two dates
1,360
0.476
Easy
20,469
https://leetcode.com/problems/number-of-days-between-two-dates/discuss/1985727/Python-Simple-and-Elegant-or-Multiple-Solutions!-or-From-Scratch-or-Library
class Solution: def daysBetweenDates(self, date1, date2): return abs(self.f(date1) - self.f(date2)) def f(self, date): y, m, d = map(int, date.split("-")) monthsDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] extraDay = int(m > 2 and self.isLeapYear(y)) days = 0 days += sum(map(self.daysInYear, range(1971, y))) days += sum(monthsDays[:m-1]) days += d + extraDay return days def isLeapYear(self, y): return (y % 4 == 0 and y % 100 != 0) or y % 400 == 0 def daysInYear(self, y): return 365 + self.isLeapYear(y)
number-of-days-between-two-dates
Python - Simple and Elegant | Multiple Solutions! | From Scratch | Library
domthedeveloper
0
255
number of days between two dates
1,360
0.476
Easy
20,470
https://leetcode.com/problems/number-of-days-between-two-dates/discuss/1985727/Python-Simple-and-Elegant-or-Multiple-Solutions!-or-From-Scratch-or-Library
class Solution: def daysBetweenDates(self, date1, date2): a = date(*map(int, date1.split("-"))) b = date(*map(int, date2.split("-"))) return abs((a - b).days)
number-of-days-between-two-dates
Python - Simple and Elegant | Multiple Solutions! | From Scratch | Library
domthedeveloper
0
255
number of days between two dates
1,360
0.476
Easy
20,471
https://leetcode.com/problems/number-of-days-between-two-dates/discuss/1434221/Python3-Detailed-Solution-No-Library-Faster-Than-88.22-Memory-Less-Than-83.33
class Solution: def daysBetweenDates(self, date1: str, date2: str) -> int: days_in_month = [0, 31,28,31,30,31,30,31,31,30,31,30,31] y1, y2 = int(date1[:4]), int(date2[:4]) m1, m2 = int(date1[5:7]), int(date2[5:7]) d1, d2 = int(date1[-2:]), int(date2[-2:]) def isleap(year): return 1 if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0) else 0 dist1, dist2 = 0, 0 for year in range(1971, y1): dist1 += 365 + isleap(year) for year in range(1971, y2): dist2 += 365 + isleap(year) for month in range(1, m1): if month == 2 and isleap(y1): dist1 += 1 dist1 += days_in_month[month] for month in range(1, m2): if month == 2 and isleap(y2): dist2 += 1 dist2 += days_in_month[month] dist1, dist2 = dist1 + d1, dist2 + d2 return abs(dist1 - dist2)
number-of-days-between-two-dates
Python3 Detailed Solution No Library, Faster Than 88.22%, Memory Less Than 83.33%
Hejita
0
157
number of days between two dates
1,360
0.476
Easy
20,472
https://leetcode.com/problems/number-of-days-between-two-dates/discuss/517662/Python3-a-straightforward-solution
class Solution: def daysBetweenDates(self, date1: str, date2: str) -> int: if date1 > date2: date1, date2 = date2, date1 y1, m1, d1 = [int(x) for x in date1.split("-")] y2, m2, d2 = [int(x) for x in date2.split("-")] leap = lambda y: (y%4 == 0 and y%100 != 0) or (y%400 == 0) dates = 365*(y2-y1) + sum(leap(y) for y in range(y1, y2)) days = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334] dates -= days[m1-1] + (m1 > 2 and leap(y1)) + d1 dates += days[m2-1] + (m2 > 2 and leap(y2)) + d2 return dates
number-of-days-between-two-dates
[Python3] a straightforward solution
ye15
0
115
number of days between two dates
1,360
0.476
Easy
20,473
https://leetcode.com/problems/validate-binary-tree-nodes/discuss/1393392/Diagram-Explained-Clean-4-checks-single-parents-single-root-no-cycle-all-connected
class Solution: def validateBinaryTreeNodes(self, n: int, leftChild: List[int], rightChild: List[int]) -> bool: n = len(leftChild) # tree has 2 requirements # 1. every node has a single parent # 2. single root (only one node has NO parent) # 3. no cycle # 4. all nodes connected to each other (single component) parent = [-1] * n # checking condition (1. and 2.) for idx, (left, right) in enumerate(zip(leftChild, rightChild)): if left != -1: # FAILED: condition (1.) if parent[left] != -1: return False parent[left] = idx if right != -1: # FAILED: condition (1.) if parent[right] != -1: return False parent[right] = idx # FAILED condition (2.) if parent.count(-1) != 1: return False # checking condition (3. and 4.) vis = set() def dfs_has_cycle(u): if u in vis: return True else: vis.add(u) for kid in [leftChild[u], rightChild[u]]: if kid != -1: if dfs_has_cycle(kid): return True # FAILED condition (3.) - found a cycle if dfs_has_cycle(parent.index(-1)): return False # FAILED condition (4.) - DFS did not visit all nodes! if len(vis) != n: return False # did not FAIL any condition, success ;) return True """ Tricky test case (cycle and not connected): 4 [1,-1,3,-1] [2,-1,-1,-1] """
validate-binary-tree-nodes
Diagram Explained Clean 4 checks [single parents, single root, no cycle, all connected]
yozaam
6
232
validate binary tree nodes
1,361
0.403
Medium
20,474
https://leetcode.com/problems/validate-binary-tree-nodes/discuss/639971/Python3-find-root-%2B-dfs-Validate-Binary-Tree-Nodes
class Solution: def validateBinaryTreeNodes(self, n: int, leftChild: List[int], rightChild: List[int]) -> bool: parent = {} for p, children in enumerate(zip(leftChild, rightChild)): for c in children: if c == -1: continue if c in parent: return False if p in parent and parent[p] == c: return False parent[c] = p root = set(range(n)) - set(parent.keys()) if len(root) != 1: return False def count(root): if root == -1: return 0 return 1 + count(leftChild[root]) + count(rightChild[root]) return count(root.pop()) == n
validate-binary-tree-nodes
Python3 find root + dfs - Validate Binary Tree Nodes
r0bertz
4
530
validate binary tree nodes
1,361
0.403
Medium
20,475
https://leetcode.com/problems/validate-binary-tree-nodes/discuss/2322086/Python3-or-Find-Root-and-do-BFS
class Solution: def validateBinaryTreeNodes(self, n: int, leftChild: List[int], rightChild: List[int]) -> bool: # Get all the children in the tree childs = set(leftChild + rightChild) root = 0 # The element which is not in childs set is the root element for i in range(n): if i not in childs: root = i break # Do a BFS on the tree and keep track of nodes we visit visited = [] queue = [root] while queue: ele = queue.pop(0) # If the element is already visited, it means it's not a tree if ele in visited: return False visited.append(ele) # If node has left child, add it to queue if leftChild[ele] != -1: queue.append(leftChild[ele]) # If node has right child, add it to queue if rightChild[ele] != -1: queue.append(rightChild[ele]) # At the end, if all the nodes (n) are visited, it means it's a tree return len(visited) == n
validate-binary-tree-nodes
Python3 | Find Root and do BFS
dudhediyabv
3
135
validate binary tree nodes
1,361
0.403
Medium
20,476
https://leetcode.com/problems/validate-binary-tree-nodes/discuss/517703/Python3-A-set-based-solution
class Solution: def validateBinaryTreeNodes(self, n: int, leftChild: List[int], rightChild: List[int]) -> bool: left = set(x for x in leftChild if x != -1) right = set(x for x in rightChild if x != -1) return len(left | right) == n-1 and (not left &amp; right)
validate-binary-tree-nodes
[Python3] A set-based solution
ye15
3
108
validate binary tree nodes
1,361
0.403
Medium
20,477
https://leetcode.com/problems/validate-binary-tree-nodes/discuss/2466116/Python-with-only-two-sets
class Solution: def validateBinaryTreeNodes(self, n: int, leftChild: List[int], rightChild: List[int]) -> bool: child = set() parent = set() for i in range(len(leftChild)): if (leftChild[i] != -1 and leftChild[i] in child) or (rightChild[i] != -1 and rightChild[i] in child): return False if i in child and ((leftChild[i] != -1 and leftChild[i] in parent) or (rightChild[i] != -1 and rightChild[i] in parent)): return False if leftChild[i] != -1: child.add(leftChild[i]) if rightChild[i] != -1: child.add(rightChild[i]) parent.add(i) if len(child) != len(leftChild) - 1: return False return True
validate-binary-tree-nodes
Python with only two sets
ToORu124124
1
38
validate binary tree nodes
1,361
0.403
Medium
20,478
https://leetcode.com/problems/validate-binary-tree-nodes/discuss/784747/simple-Python-o(N)-recursive-with-2-sets
class Solution(object): def validateBinaryTreeNodes(self, n, leftChild, rightChild): visited = set() roots = set() def visitChildren(node): if node == -1: return True if node in roots: roots.remove(node) return True if node in visited: return False visited.add(node) return (visitChildren(leftChild[node]) and visitChildren(rightChild[node])) for node in range(n): if node not in visited: if not visitChildren(node): return False roots.add(node) return (len(roots) == 1) """ :type n: int :type leftChild: List[int] :type rightChild: List[int] :rtype: bool """
validate-binary-tree-nodes
simple Python o(N), recursive with 2 sets
masumvotres
1
135
validate binary tree nodes
1,361
0.403
Medium
20,479
https://leetcode.com/problems/validate-binary-tree-nodes/discuss/2821406/Simple-python-queue
class Solution: def validateBinaryTreeNodes(self, n: int, L: List[int], R: List[int]) -> bool: visited = set() roots = list(range(n)) components = n for i in range(n): if i not in visited: nodes = [i] while nodes: curr = nodes.pop(0) if curr in visited: if roots[curr] != curr or roots[curr] == i: return False else: roots[curr] = i else: visited.add(curr) roots[curr] = i if L[curr] != -1: nodes.append(L[curr]) if R[curr] != -1: nodes.append(R[curr]) if roots[curr] != curr: components -= 1 return components == 1
validate-binary-tree-nodes
Simple python queue
js44lee
0
3
validate binary tree nodes
1,361
0.403
Medium
20,480
https://leetcode.com/problems/validate-binary-tree-nodes/discuss/2313580/Python3-or-Find-root-and-Cycle
class Solution: def validateBinaryTreeNodes(self, n: int, leftChild: List[int], rightChild: List[int]) -> bool: hmap=defaultdict(list) degree=[0]*n for i in range(n): if leftChild[i]!=-1: hmap[i].append(leftChild[i]) degree[leftChild[i]]+=1 if rightChild[i]!=-1: hmap[i].append(rightChild[i]) degree[rightChild[i]]+=1 parent=[ind for ind,i in enumerate(degree) if i==0] vis=set() root=parent[0] if len(parent) else 0 vis.add(root) if self.dfs(root,vis,hmap) and len(vis)==n: return True else: return False def dfs(self,node,vis,hmap): for it in hmap[node]: if it not in vis: vis.add(it) if self.dfs(it,vis,hmap): continue else: return False else: return False return True
validate-binary-tree-nodes
[Python3] | Find root and Cycle
swapnilsingh421
0
24
validate binary tree nodes
1,361
0.403
Medium
20,481
https://leetcode.com/problems/validate-binary-tree-nodes/discuss/2309816/Python3-Clean-BFS-solution-with-comments...
class Solution: def validateBinaryTreeNodes(self, n: int, leftChild: List[int], rightChild: List[int]) -> bool: # find the root of tree --> node which is not in both list root = -1 leftright = set(leftChild + rightChild) for i in range(n): if i not in leftright: root = i break # add the root to queue if root != -1: q = deque([root]) else: return False # visited checks two things # 1. No node is visited again i.e cycle in the tree # 2. All the node are visited i.e check for disconnected nodes visited = set() while q: index = q.popleft() if index != -1: # if a node has two parent if index in visited: return False visited.add(index) q.append(leftChild[index]) q.append(rightChild[index]) # If all the nodes are traversed or no disconected nodes return True if len(visited) == n else False
validate-binary-tree-nodes
[Python3] Clean BFS solution with comments...
Gp05
0
11
validate binary tree nodes
1,361
0.403
Medium
20,482
https://leetcode.com/problems/validate-binary-tree-nodes/discuss/2234405/Python-DFS!
class Solution: def validateBinaryTreeNodes(self, n: int, leftChild: List[int], rightChild: List[int]) -> bool: def dfs(node, seen): if node in seen: return False self.node_count += 1 seen.add(node) if leftChild[node] != -1: if not dfs(leftChild[node], seen): return False if rightChild[node] != -1: if not dfs(rightChild[node], seen): return False return True root_set = set(range(n)) for e in chain(leftChild, rightChild): if e != -1: if e not in root_set: return False root_set.remove(e) if len(root_set) != 1: return False self.node_count = 0 if not dfs(root_set.pop(), set()): return False return self.node_count == n
validate-binary-tree-nodes
Python, DFS!
blue_sky5
0
37
validate binary tree nodes
1,361
0.403
Medium
20,483
https://leetcode.com/problems/validate-binary-tree-nodes/discuss/2114978/Python-or-Easy-Solution-or-Beginner-Friendly
class Solution: def validateBinaryTreeNodes(self, n: int, leftChild: List[int], rightChild: List[int]) -> bool: graph = collections.defaultdict(list) # By default root value will be 0 root = 0 for node in range(n): # Building Graph if leftChild[node] != -1: graph[node].append(leftChild[node]) if rightChild[node] != -1: graph[node].append(rightChild[node]) # Finding root node while building graph if leftChild[node] == root or rightChild[node] == root: root = node # BFS queue = [root] seen = set([root]) while queue: for _ in range(len(queue)): node = queue.pop(0) if node in graph: for child in graph[node]: if child not in seen: seen.add(child) queue.append(child) else: return False return len(seen) == n
validate-binary-tree-nodes
Python | Easy Solution | Beginner Friendly
Call-Me-AJ
0
46
validate binary tree nodes
1,361
0.403
Medium
20,484
https://leetcode.com/problems/validate-binary-tree-nodes/discuss/1899675/Python3-DFS
class Solution: def validateBinaryTreeNodes(self, n: int, leftChild: List[int], rightChild: List[int]) -> bool: seen = set() def dfs(node): if node in seen: return False seen.add(node) if leftChild[node] != -1: if not dfs(leftChild[node]): return False if rightChild[node] != -1: if not dfs(rightChild[node]): return False return True roots = set(range(n)) - set(leftChild + rightChild) if len(roots) != 1: return False root = roots.pop() return dfs(root) and len(seen) == n
validate-binary-tree-nodes
Python3 DFS
yshawn
0
49
validate binary tree nodes
1,361
0.403
Medium
20,485
https://leetcode.com/problems/validate-binary-tree-nodes/discuss/1659204/Python-simple-bfs-solution-(covering-all-edge-cases)
class Solution: from collections import deque def validateBinaryTreeNodes(self, n: int, leftChild: List[int], rightChild: List[int]) -> bool: tree = defaultdict(set) allnode = {0} parents = defaultdict(list) for i in range(n): node = i allnode.add(i) left, right = leftChild[i], rightChild[i] if left >= 0: tree[i].add(left) allnode.add(left) parents[left].append(node) if len(parents[left]) >= 2: return False if right >= 0: tree[i].add(right) allnode.add(right) parents[right].append(node) if len(parents[right]) >= 2: return False counts = defaultdict(int) root = 0 rootvisit = set() while parents[root] and root not in rootvisit: rootvisit.add(root) root = parents[root][0] queue = deque([root]) while queue: node = queue.popleft() counts[node] += 1 if counts[node] >= 2: # visited more than once return False child = tree[node] for c in child: if c in tree and node in tree[c]: # bi-directional return False queue.append(c) return len(counts) == len(allnode)
validate-binary-tree-nodes
Python simple bfs solution (covering all edge cases)
byuns9334
0
87
validate binary tree nodes
1,361
0.403
Medium
20,486
https://leetcode.com/problems/validate-binary-tree-nodes/discuss/524440/Python-BFS-Solution
class Solution: def validateBinaryTreeNodes(self, n: int, leftChild: List[int], rightChild: List[int]) -> bool: visited = {} q = collections.deque() q.append(0) while len(q) > 0: node = q.popleft() if visited.get(node): return False visited[node] = True if leftChild[node] != -1: q.append(leftChild[node]) if rightChild[node] != -1: q.append(rightChild[node]) total_count = 1 + len([x for x in leftChild if x != -1]) + len([x for x in rightChild if x != -1]) return len(visited) == total_count
validate-binary-tree-nodes
Python BFS Solution
ehdwn1212
-1
160
validate binary tree nodes
1,361
0.403
Medium
20,487
https://leetcode.com/problems/validate-binary-tree-nodes/discuss/517578/Clean-Python-3-HashSet-O(N)
class Solution: def validateBinaryTreeNodes(self, n: int, leftChild: List[int], rightChild: List[int]) -> bool: children = set() for i in range(n): left, right = leftChild[i], rightChild[i] if -1 < left < i or -1 < right < i: return False if left in children or right in children: return False if left > -1: children.add(left) if right > -1: children.add(right) return len(children) == n - 1
validate-binary-tree-nodes
Clean Python 3, HashSet O(N)
lenchen1112
-1
292
validate binary tree nodes
1,361
0.403
Medium
20,488
https://leetcode.com/problems/validate-binary-tree-nodes/discuss/517578/Clean-Python-3-HashSet-O(N)
class Solution: def validateBinaryTreeNodes(self, n: int, leftChild: List[int], rightChild: List[int]) -> bool: children = 0 for i in range(n): if i > leftChild[i] > -1 or i > rightChild[i] > -1: return False children += (leftChild[i] > -1) + (rightChild[i] > -1) return children == n - 1
validate-binary-tree-nodes
Clean Python 3, HashSet O(N)
lenchen1112
-1
292
validate binary tree nodes
1,361
0.403
Medium
20,489
https://leetcode.com/problems/closest-divisors/discuss/517720/Python3-A-concise-solution
class Solution: def closestDivisors(self, num: int) -> List[int]: for i in range(int((num+2)**0.5), 0, -1): if not (num+1)%i: return (i, (num+1)//i) if not (num+2)%i: return (i, (num+2)//i)
closest-divisors
[Python3] A concise solution
ye15
1
50
closest divisors
1,362
0.599
Medium
20,490
https://leetcode.com/problems/closest-divisors/discuss/2822923/1-List-with-sort-2-Without-sort-3More-optimized
class Solution: def closestDivisors(self, num: int) -> List[int]: # Using Sort lis=[] # lis in the format of [divisor1,divisor2,difference of divisor] Note** product of divisor=dividend for i in range(1,int(sqrt(num+1))+1): if (num+1)%i==0: lis.append((i,(num+1)//i,((num+1)//i)-i)) for i in range(1,int(sqrt(num+2))+1): if (num+2)%i==0: lis.append((i,(num+2)//i,((num+2)//i)-i)) lis=sorted(lis,key=lambda x:x[2]) #print(lis) return [lis[0][0],lis[0][1]]
closest-divisors
[1] List with sort [2] Without sort [3]More optimized
mehtay037
0
2
closest divisors
1,362
0.599
Medium
20,491
https://leetcode.com/problems/closest-divisors/discuss/2822923/1-List-with-sort-2-Without-sort-3More-optimized
class Solution: def closestDivisors(self, num: int) -> List[int]: # Without Sort mini=float('inf') res=[] for i in range(1,int(sqrt(num+1))+1): if (num+1)%i==0: if ((num+1)//i)-i<mini: res=[i,(num+1)//i] mini=((num+1)//i)-i for i in range(1,int(sqrt(num+2))+1): if (num+2)%i==0: if ((num+2)//i)-i<mini: res=[i,(num+2)//i] mini=((num+2)//i)-i return res
closest-divisors
[1] List with sort [2] Without sort [3]More optimized
mehtay037
0
2
closest divisors
1,362
0.599
Medium
20,492
https://leetcode.com/problems/closest-divisors/discuss/2822923/1-List-with-sort-2-Without-sort-3More-optimized
class Solution: def closestDivisors(self, num: int) -> List[int]: for i in range(int(sqrt(num+2)),0,-1): if (num+1)%i==0: return [i,(num+1)//i] if (num+2)%i==0: return [i,(num+2)//i]
closest-divisors
[1] List with sort [2] Without sort [3]More optimized
mehtay037
0
2
closest divisors
1,362
0.599
Medium
20,493
https://leetcode.com/problems/closest-divisors/discuss/2763160/python-93-faster
class Solution: def closestDivisors(self, num: int) -> List[int]: for i in range(round((num+2)**0.5),0,-1): if (num+1)%i==0: return [i,(num+1)//i] if (num+2)%i==0: return [i,(num+2)//i] //please uprove it
closest-divisors
python 93% faster
manishx112
0
11
closest divisors
1,362
0.599
Medium
20,494
https://leetcode.com/problems/closest-divisors/discuss/2575929/Python-bruteforce
class Solution: def closestDivisors(self, num: int) -> List[int]: def get_divisors(n): for i in range(1, int(n**0.5) + 1): if n%i == 0: yield (n//i - i, i, n//i) return min(*get_divisors(num+1), *get_divisors(num+2))[1:]
closest-divisors
Python bruteforce
Vigneswar_A
0
6
closest divisors
1,362
0.599
Medium
20,495
https://leetcode.com/problems/closest-divisors/discuss/1792871/WEEB-DOES-MATH-IN-PYTHONC%2B%2B
class Solution: def closestDivisors(self, num: int) -> List[int]: for i in range(int((num+2) ** (0.5)), 0, -1): if not (num+1) % i: return [i, (num+1)//i] if not (num+2) % i: return [i, (num+2)//i] return []
closest-divisors
WEEB DOES MATH IN PYTHON/C++
Skywalker5423
0
75
closest divisors
1,362
0.599
Medium
20,496
https://leetcode.com/problems/closest-divisors/discuss/856390/Python-3-or-Math-Sqrt-or-Explanation
class Solution: def closestDivisors(self, num: int) -> List[int]: for i in range(int((num+2) ** (0.5)), 0, -1): # only check sqrt, reduce the time complexity if not (num+1) % i: return [i, (num+1)//i] # check if `i` is divisible by num+1 if not (num+2) % i: return [i, (num+2)//i] # check if `i` is divisible by num+2 return []
closest-divisors
Python 3 | Math, Sqrt | Explanation
idontknoooo
0
180
closest divisors
1,362
0.599
Medium
20,497
https://leetcode.com/problems/closest-divisors/discuss/517730/Python3-super-simple-solution
class Solution: def closestDivisors(self, num: int) -> List[int]: if num==1: return [1,2] if num==2: return [2,2] res=[-float("inf"),float("inf")] for i in range(1,int(num**0.5)+2): a,b=(num+1)//i,(num+2)//i diff_r,diff_s_r=abs(res[0]-res[1]),min(abs(res[0]*res[1]-num-1),abs(res[0]*res[1]-num-2)) diff_a,diff_s_a=abs(a-i),abs(a*i-num-1) diff_b,diff_s_b=abs(b-i),abs(b*i-num-2) if diff_s_a<diff_s_r or (diff_s_a==diff_s_r and diff_a<diff_r): res=[i,a] if diff_s_b<diff_s_r or (diff_s_b==diff_s_r and diff_b<diff_r): res=[i,b] return res
closest-divisors
Python3 super simple solution
jb07
0
67
closest divisors
1,362
0.599
Medium
20,498
https://leetcode.com/problems/largest-multiple-of-three/discuss/519005/Clean-Python-3-counting-sort-O(N)O(1)-timespace-100
class Solution: def largestMultipleOfThree(self, digits: List[int]) -> str: def dump(r: int) -> str: if r: for i in range(3): idx = 3 * i + r if counts[idx]: counts[idx] -= 1 break else: rest = 2 for j in range(3): idx = 3 * j + (-r % 3) while rest and counts[idx]: counts[idx] -= 1 rest -= 1 if not rest: break if rest: return '' if any(counts): result = '' for i in reversed(range(10)): result += str(i) * counts[i] return str(int(result)) return '' total, counts = 0, [0] * 10 for digit in digits: counts[digit] += 1 total += digit return dump(total % 3)
largest-multiple-of-three
Clean Python 3, counting sort O(N)/O(1) time/space, 100%
lenchen1112
2
268
largest multiple of three
1,363
0.333
Hard
20,499