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/missing-number/discuss/2137533/python-xor-explaination
class Solution: def missingNumber(self, nums: List[int]) -> int: n = len(nums) return n*(n+1) // 2 - sum(nums)
missing-number
python xor explaination
writemeom
1
102
missing number
268
0.617
Easy
4,900
https://leetcode.com/problems/missing-number/discuss/2092996/PYTHON-1-Line-Solution
class Solution: def missingNumber(self, nums: List[int]) -> int: return [el for el in set([x for x in range(0,len(nums)+1)]) ^ set(nums)][0];
missing-number
PYTHON 1 Line Solution
zeyf
1
107
missing number
268
0.617
Easy
4,901
https://leetcode.com/problems/missing-number/discuss/2081411/Python-solution-using-sum-of-n-natural-numbers
class Solution: def missingNumber(self, nums: List[int]) -> int: n = len(nums) act = (n*n + n)//2 given_sum = sum(nums) missing = act - given_sum return missing
missing-number
Python solution using sum of n natural numbers
testbugsk
1
34
missing number
268
0.617
Easy
4,902
https://leetcode.com/problems/missing-number/discuss/2025573/PYTHONor-SIMPLE-SUM-SOLUTION
class Solution: def missingNumber(self, nums: List[int]) -> int: res = len(nums) for i in range(len(nums)): res += (i - nums[i]) return res
missing-number
PYTHON| SIMPLE SUM SOLUTION
shikha_pandey
1
118
missing number
268
0.617
Easy
4,903
https://leetcode.com/problems/missing-number/discuss/1815479/Simplest-Python-Solution-oror-Beg-to-Adv
class Solution: def missingNumber(self, nums: List[int]) -> int: numofelem = len(nums) sumofnums = sum(nums) total = numofelem * (numofelem + 1) // 2 return total - sumofnums
missing-number
Simplest Python Solution || Beg to Adv
rlakshay14
1
190
missing number
268
0.617
Easy
4,904
https://leetcode.com/problems/missing-number/discuss/1642325/Python-3-oror-2-line-Solution-oror-Using-Mathemtical-calculation-oror-Self-understandable
class Solution: def missingNumber(self, nums: List[int]) -> int: return (len(nums)*(len(nums)+1))//2-sum(nums)
missing-number
Python 3 || 2-line Solution || Using Mathemtical calculation || Self understandable
bug_buster
1
79
missing number
268
0.617
Easy
4,905
https://leetcode.com/problems/missing-number/discuss/1637692/Python3-Bitwise-Solution-Easy
class Solution: def missingNumber(self, nums: List[int]) -> int: xor_of_all = 0 xor_of_arr = 0 n = len(nums) for i in range(n + 1): xor_of_all ^= i for n in nums: xor_of_arr ^= n return xor_of_all ^ xor_of_arr
missing-number
Python3 Bitwise Solution Easy
dahal_
1
112
missing number
268
0.617
Easy
4,906
https://leetcode.com/problems/missing-number/discuss/1463792/compare-both-code-python3-c%2B%2B-and-different-ways-easy-to-understand-beats-99
class Solution: def missingNumber(self, nums: List[int]) -> int: ans=0 for a,b in enumerate(nums): ans^=a+1 ans^=b return ans
missing-number
compare both code [python3 /c++] and different ways easy to understand beats 99%
sagarhparmar12345
1
65
missing number
268
0.617
Easy
4,907
https://leetcode.com/problems/missing-number/discuss/1463792/compare-both-code-python3-c%2B%2B-and-different-ways-easy-to-understand-beats-99
class Solution: def missingNumber(self, nums: List[int]) -> int: n=len(nums) return (n**2 +n)//2 - sum(nums)
missing-number
compare both code [python3 /c++] and different ways easy to understand beats 99%
sagarhparmar12345
1
65
missing number
268
0.617
Easy
4,908
https://leetcode.com/problems/missing-number/discuss/1399688/Python-or-XOR
class Solution: def missingNumber(self, nums: List[int]) -> int: xor = 0 for i in range(len(nums)): xor ^= (i+1)^nums[i] return xor
missing-number
Python | XOR
sathwickreddy
1
307
missing number
268
0.617
Easy
4,909
https://leetcode.com/problems/missing-number/discuss/1308515/Python3-faster-than-90.56-O(2n)
class Solution: def missingNumber(self, nums: List[int]) -> int: allSum = sum(nums) expect = 0 for i in range(len(nums) + 1): expect += i return expect - allSum
missing-number
Python3 - faster than 90.56%, O(2n)
CC_CheeseCake
1
58
missing number
268
0.617
Easy
4,910
https://leetcode.com/problems/missing-number/discuss/1158407/Python3-Single-Line-Solution
class Solution: def missingNumber(self, nums: List[int]) -> int: return sum(range(len(nums) + 1)) - sum(nums)
missing-number
[Python3] Single Line Solution
Lolopola
1
61
missing number
268
0.617
Easy
4,911
https://leetcode.com/problems/missing-number/discuss/1138517/One-line-python-solution
class Solution: def missingNumber(self, nums: List[int]) -> int: n=len(nums) return (n*(n+1)//2)-sum(nums)
missing-number
One line python solution
samarthnehe
1
111
missing number
268
0.617
Easy
4,912
https://leetcode.com/problems/missing-number/discuss/1092310/Python-A-couple-clean-one-liners
class Solution: def missingNumber(self, nums: List[int]) -> int: return sum(x - y for x,y in enumerate(nums, start=1))
missing-number
Python - A couple clean one liners
jep4444
1
42
missing number
268
0.617
Easy
4,913
https://leetcode.com/problems/missing-number/discuss/1092310/Python-A-couple-clean-one-liners
class Solution: def missingNumber(self, nums: List[int]) -> int: return functools.reduce(operator.xor, itertools.starmap(operator.xor, enumerate(nums, start=1)))
missing-number
Python - A couple clean one liners
jep4444
1
42
missing number
268
0.617
Easy
4,914
https://leetcode.com/problems/missing-number/discuss/1091215/Missing-NumberPython-Hints-and-easy-explanation
class Solution: def missingNumber(self, nums: List[int]) -> int: n = len(nums) sum_n = n*(n+1)//2 sum_nums = sum(nums) return sum_n - sum_nums
missing-number
[Missing Number][Python] Hints and easy explanation
sahilnishad
1
33
missing number
268
0.617
Easy
4,915
https://leetcode.com/problems/missing-number/discuss/428261/Python-simple-and-easy-to-understand
class Solution: def missingNumber(self, nums): expected = 0 actual = 0 for i,num in enumerate(nums): expected += i+1 actual += num return expected-actual
missing-number
Python - simple and easy to understand
domthedeveloper
1
114
missing number
268
0.617
Easy
4,916
https://leetcode.com/problems/missing-number/discuss/428261/Python-simple-and-easy-to-understand
class Solution: def missingNumber(self, nums): return sum(range(len(nums)+1))-sum(nums)
missing-number
Python - simple and easy to understand
domthedeveloper
1
114
missing number
268
0.617
Easy
4,917
https://leetcode.com/problems/missing-number/discuss/428261/Python-simple-and-easy-to-understand
class Solution: def missingNumber(self, nums): n,s = len(nums),sum(nums) return n*(n+1)//2-s
missing-number
Python - simple and easy to understand
domthedeveloper
1
114
missing number
268
0.617
Easy
4,918
https://leetcode.com/problems/missing-number/discuss/428261/Python-simple-and-easy-to-understand
class Solution: def missingNumber(self, nums): return (lambda n,s : n*(n+1)//2-s)(len(nums),sum(nums))
missing-number
Python - simple and easy to understand
domthedeveloper
1
114
missing number
268
0.617
Easy
4,919
https://leetcode.com/problems/missing-number/discuss/2845604/python-beats-98.68-or-beats-5
class Solution: def missingNumber(self, nums: List[int]) -> int: return sum(list(range(len(nums)+1))) - sum(nums)
missing-number
[python] - beats 98.68% | beats 5%
ceolantir
0
2
missing number
268
0.617
Easy
4,920
https://leetcode.com/problems/missing-number/discuss/2845604/python-beats-98.68-or-beats-5
class Solution: def missingNumber(self, nums: List[int]) -> int: for i in sum(len(range(len(nums)+1))): if i not in nums: return i
missing-number
[python] - beats 98.68% | beats 5%
ceolantir
0
2
missing number
268
0.617
Easy
4,921
https://leetcode.com/problems/missing-number/discuss/2841207/python-oror-simple-solution-oror-o(n)-time-o(1)-space
class Solution: def missingNumber(self, nums: List[int]) -> int: ans = 0 # answer # calculate triangle num for size of nums, then subtract every num in nums for i in range(len(nums)): ans += i + 1 - nums[i] # left with missing num return ans
missing-number
python || simple solution || o(n) time, o(1) space
wduf
0
4
missing number
268
0.617
Easy
4,922
https://leetcode.com/problems/missing-number/discuss/2840188/Super-Simple-Python-Solution
class Solution: def missingNumber(self, nums: List[int]) -> int: length = len(nums) sum_true_nums = 0 for num in range(0, length + 1): sum_true_nums += num return sum_true_nums - sum(nums)
missing-number
Super Simple Python Solution
corylynn
0
3
missing number
268
0.617
Easy
4,923
https://leetcode.com/problems/missing-number/discuss/2837363/Python-Beats-97.73-of-runtime-complexity
class Solution: def missingNumber(self, nums: List[int]) -> int: expected_nums = { n: 0 for n in range(0, len(nums)+1) } for n in nums: expected_nums[n] = 1 for n, seen in expected_nums.items(): if not seen: return n
missing-number
[Python] Beats 97.73% of runtime complexity
jyoo
0
3
missing number
268
0.617
Easy
4,924
https://leetcode.com/problems/missing-number/discuss/2837140/python-easy-solution
class Solution: def missingNumber(self, nums): a = sum(range(len(nums)+1)); b = sum(nums); return (a-b);
missing-number
python easy solution
seifsoliman
0
1
missing number
268
0.617
Easy
4,925
https://leetcode.com/problems/missing-number/discuss/2833795/Python-solution
class Solution: def missingNumber(self, nums: List[int]) -> int: #nums.sort() list1=[x for x in range(0,len(nums)+1) if x not in nums] print(list1[0]) return list1[0]
missing-number
Python solution
user1079z
0
1
missing number
268
0.617
Easy
4,926
https://leetcode.com/problems/integer-to-english-words/discuss/1990823/JavaC%2B%2BPythonJavaScriptKotlinSwiftO(n)timeBEATS-99.97-MEMORYSPEED-0ms-APRIL-2022
class Solution: def numberToWords(self, num: int) -> str: mp = {1: "One", 11: "Eleven", 10: "Ten", 2: "Two", 12: "Twelve", 20: "Twenty", 3: "Three", 13: "Thirteen", 30: "Thirty", 4: "Four", 14: "Fourteen", 40: "Forty", 5: "Five", 15: "Fifteen", 50: "Fifty", 6: "Six", 16: "Sixteen", 60: "Sixty", 7: "Seven", 17: "Seventeen", 70: "Seventy", 8: "Eight", 18: "Eighteen", 80: "Eighty", 9: "Nine", 19: "Nineteen", 90: "Ninety"} def fn(n): """Return English words of n (0-999) in array.""" if not n: return [] elif n < 20: return [mp[n]] elif n < 100: return [mp[n//10*10]] + fn(n%10) else: return [mp[n//100], "Hundred"] + fn(n%100) ans = [] for i, unit in zip((9, 6, 3, 0), ("Billion", "Million", "Thousand", "")): n, num = divmod(num, 10**i) ans.extend(fn(n)) if n and unit: ans.append(unit) return " ".join(ans) or "Zero"
integer-to-english-words
[Java/C++/Python/JavaScript/Kotlin/Swift]O(n)time/BEATS 99.97% MEMORY/SPEED 0ms APRIL 2022
cucerdariancatalin
8
677
integer to english words
273
0.299
Hard
4,927
https://leetcode.com/problems/integer-to-english-words/discuss/1939386/short-and-easy-to-understand-Python-code-using-dictionary
class Solution: def numberToWords(self, num: int) -> str: if num == 0 : return 'Zero' #if condition to handle zero d = {1000000000 : 'Billion',1000000 : 'Million',1000 : 'Thousand',100 : 'Hundred', 90:'Ninety',80:'Eighty',70:'Seventy',60:'Sixty',50: 'Fifty', 40 : 'Forty', 30 : 'Thirty', 20 : 'Twenty', 19 :'Nineteen',18 :'Eighteen',17:'Seventeen',16:'Sixteen',15:'Fifteen',14:'Fourteen',13:'Thirteen',12:'Twelve',11:'Eleven', 10:'Ten',9:'Nine',8:'Eight',7:'Seven',6:'Six',5:'Five',4:'Four',3:'Three',2:'Two',1:'One'} #initiating a dictionary to handle number to word mapping ans = "" #initialising the returnable answer variable for key, value in d.items(): #for loop to iterate through each key-value pair in dictionary if num//key>0 : #checking if number is in the range of current key x = num//key #finding the multiple of key in num if key >= 100 : #logic to add the multiple number x above as word to our answer, We say "One Hundred", "One thoushand" but we don't say "One Fifty", we simply say "Fifty" ans += self.numberToWords(x) + ' ' ans += value + " " num = num%key #preparing the number for next loop i.e removing the value from num which we have already appended the words to answer. return ans.strip() #returning answer removing the last blank space
integer-to-english-words
short & easy to understand Python code using dictionary
TheBatmanIRL
7
397
integer to english words
273
0.299
Hard
4,928
https://leetcode.com/problems/integer-to-english-words/discuss/764375/Python3-straightforward
class Solution: def numberToWords(self, num: int) -> str: mp = {1: "One", 11: "Eleven", 10: "Ten", 2: "Two", 12: "Twelve", 20: "Twenty", 3: "Three", 13: "Thirteen", 30: "Thirty", 4: "Four", 14: "Fourteen", 40: "Forty", 5: "Five", 15: "Fifteen", 50: "Fifty", 6: "Six", 16: "Sixteen", 60: "Sixty", 7: "Seven", 17: "Seventeen", 70: "Seventy", 8: "Eight", 18: "Eighteen", 80: "Eighty", 9: "Nine", 19: "Nineteen", 90: "Ninety"} def fn(n): """Return English words of n (0-999) in array.""" if not n: return [] elif n < 20: return [mp[n]] elif n < 100: return [mp[n//10*10]] + fn(n%10) else: return [mp[n//100], "Hundred"] + fn(n%100) ans = [] for i, unit in zip((9, 6, 3, 0), ("Billion", "Million", "Thousand", "")): n, num = divmod(num, 10**i) ans.extend(fn(n)) if n and unit: ans.append(unit) return " ".join(ans) or "Zero"
integer-to-english-words
[Python3] straightforward
ye15
4
211
integer to english words
273
0.299
Hard
4,929
https://leetcode.com/problems/integer-to-english-words/discuss/2021835/Easy-to-understand-recursive-python-solution
class Solution: def numberToWords(self, num: int) -> str: if not num: return 'Zero' ones = {1:' One', 2:' Two', 3:' Three', 4:' Four', 5:' Five', 6:' Six', 7:' Seven', 8:' Eight', 9:' Nine', 10:' Ten', 11:' Eleven', 12:' Twelve', 13:' Thirteen', 14:' Fourteen', 15:' Fifteen', 16:' Sixteen', 17:' Seventeen', 18:' Eighteen', 19:' Nineteen'} tens = {2:' Twenty', 3:' Thirty', 4:' Forty', 5:' Fifty', 6:' Sixty', 7:' Seventy', 8:' Eighty', 9:' Ninety'} self.output = '' def wordify(num): if num // 1000000000: wordify(num // 1000000000) self.output += ' Billion' wordify(num % 1000000000) elif num // 1000000: wordify(num // 1000000) self.output += ' Million' wordify(num % 1000000) elif num // 1000: wordify(num // 1000) self.output += ' Thousand' wordify(num % 1000) elif num // 100: wordify(num // 100) self.output += ' Hundred' wordify(num % 100) elif num // 10 - 1 > 0: self.output += tens[num // 10] wordify(num % 10) elif num: self.output += ones[num] wordify(num) return self.output[1:]
integer-to-english-words
Easy to understand recursive python solution
Kasra_G
2
214
integer to english words
273
0.299
Hard
4,930
https://leetcode.com/problems/integer-to-english-words/discuss/2167564/Elegant-Recursive-Solution-in-Python
class Solution: def numberToWords(self, num: int) -> str: if num == 0: return 'Zero' billion, million, thousand, hundred = 10 ** 9, 10 ** 6, 10 ** 3, 10 ** 2 mapping = { 0: '', 1: 'One', 2: 'Two', 3: 'Three', 4: 'Four', 5: 'Five', 6: 'Six', 7: 'Seven', 8: 'Eight', 9: 'Nine', 10: 'Ten', 11: 'Eleven', 12: 'Twelve', 13: 'Thirteen', 14: 'Fourteen', 15: 'Fifteen', 16: 'Sixteen', 17: 'Seventeen', 18: 'Eighteen', 19: 'Nineteen', 20: 'Twenty', 30: 'Thirty', 40: 'Forty', 50: 'Fifty', 60: 'Sixty', 70: 'Seventy', 80: 'Eighty', 90: 'Ninety', billion: 'Billion', million: 'Million', thousand: 'Thousand', hundred: 'Hundred', } for unit in [billion, million, thousand, hundred]: if num >= unit: if num % unit: return f"{self.numberToWords(num // unit)} {mapping[unit]} {self.numberToWords(num % unit)}" return f"{self.numberToWords(num // unit)} {mapping[unit]}" res = '' for i in range(99, 0, -1): if num // i > 0 and i in mapping: res = f"{mapping[i]} {mapping[num % i]}".strip() break return res
integer-to-english-words
Elegant Recursive Solution in Python
wangzhihao0629
1
197
integer to english words
273
0.299
Hard
4,931
https://leetcode.com/problems/integer-to-english-words/discuss/1918243/Python-Straightforward-Solution
class Solution: def numberToWords(self, num: int) -> str: if num == 0: return 'Zero' ones = {1: "One", 2: 'Two', 3: 'Three', 4: 'Four', 5: 'Five', 6: 'Six', 7: 'Seven', 8: 'Eight', 9: 'Nine', 10: 'Ten', 11: 'Eleven', 12: 'Twelve', 13: 'Thirteen', 14: 'Fourteen', 15: 'Fifteen', 16: 'Sixteen', 17: 'Seventeen', 18: 'Eighteen', 19: 'Nineteen'} tens = { 2: 'Twenty', 3: 'Thirty', 4: 'Forty', 5: 'Fifty', 6: 'Sixty', 7: 'Seventy', 8: 'Eighty', 9: 'Ninety'} def t_convert(num): result = [] if num < 20: result.append(ones[num]) else: ans = num // 10 if ans > 0: result.append(tens[ans]) ans = num % 10 if ans > 0: result.append(ones[ans]) return result def h_convert(num): result = [] ans = num // 100 if ans > 0: result.append(ones[ans] + ' Hundred') ans = num % 100 if ans > 0: result += t_convert(ans) return result result = [] divisors = [ [1_000_000_000, 'Billion'], [1_000_000, 'Million'], [1_000, 'Thousand'] ] for d, word in divisors: ans = num // d if ans > 0: if ans < 100: result += t_convert(ans) else: result += h_convert(ans) result[-1] += ' ' + word num %= d result += h_convert(num) return ' '.join(result)
integer-to-english-words
Python Straightforward Solution
zoran3
1
126
integer to english words
273
0.299
Hard
4,932
https://leetcode.com/problems/integer-to-english-words/discuss/2825187/Easy-To-Follow-Recursive-Python
class Solution: def numberToWords(self, num: int) -> str: to_19 = {0:'Zero', 1:'One',2:'Two',3:'Three',4:'Four', 5:'Five', 6:'Six', 7: 'Seven', 8: 'Eight', 9: 'Nine', 10:'Ten', 11: 'Eleven', 12: 'Twelve', 13:'Thirteen', 14:"Fourteen",15:"Fifteen",16:"Sixteen",17:"Seventeen",18:"Eighteen",19:"Nineteen"} ty = {20: 'Twenty', 30: 'Thirty', 40: 'Forty', 50: 'Fifty', 60: 'Sixty', 70: 'Seventy', 80:'Eighty', 90:'Ninety'} digs = len(str(num)) s = "" if digs<=2: #tens if num<=19: s+=to_19[num] elif 20<=num: if num%10==0: s+=ty[num] else: s+=ty[(num//10)*10]+ ' ' + to_19[num%10] elif digs == 3: #hundreds if num%100 == 0: return to_19[num//100]+' '+'Hundred' s += to_19[num//100] + ' ' + 'Hundred' + ' ' + self.numberToWords(num-(num//100)*100) elif 4<=digs<=6: #thousands if num%1000 == 0: return self.numberToWords(num//1000) + ' ' + 'Thousand' s += self.numberToWords(num//1000)+ ' ' + 'Thousand' + ' ' + self.numberToWords(num-(num//1000)*1000) elif 7<=digs<=9: #millions if num%1000000 == 0: return self.numberToWords(num//1000000)+' '+'Million' s += self.numberToWords(num//1000000)+ ' ' + 'Million' + ' ' + self.numberToWords(num-(num//1000000)*1000000) elif digs == 10: #billions if num%1000000000 == 0: return to_19[num//1000000000]+' '+'Billion' s += to_19[num//1000000000]+' '+ 'Billion' + ' '+ self.numberToWords(num-(num//1000000000)*1000000000) return s
integer-to-english-words
Easy To Follow Recursive Python
taabish_khan22
0
12
integer to english words
273
0.299
Hard
4,933
https://leetcode.com/problems/integer-to-english-words/discuss/2729086/PYTHON-Simple-Fast-Solution-Cultural-%22elibelinde%22-approach
class Solution: def numberToWords(self, num: int) -> str: tens = {11: "Eleven", 12: "Twelve", 13: "Thirteen", 14: "Fourteen", 15: "Fifteen", 16: "Sixteen", 17: "Seventeen", 18: "Eighteen", 19: "Nineteen"} o = ["Zero","One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"] t = ["Ten","Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"] t2 = ["Billion", "Million", "Thousand", "Hundred"][::-1] mynum = "" c = 0 num = str(num)[::-1] if len(num)==1: return o[int(num[0])] if int(str(num)[0])-1 != -1: if num[1] != "1": mynum = o[int(num[0])] + mynum c = 1 elif num[1] == "1": mynum = tens[int(num[:2][::-1])] + mynum c = 2 key = None for i in range(c,len(num)): if key == 0: key = None continue elif num[i] == "0": if i%3 == 0 and i//3>0: if "00" not in num[i+1:i+3] or "0" not in num[i+1:i+2]: mynum = t2[i//3] + " " + mynum continue if "1" in num[i+1:i+2] and i%3 == 0 and key == None: key = 0 mynum = tens[int(num[i+1]+num[i])] + " " + t2[i//3] + " " + mynum else: if i%3 == 2: mynum = o[int(num[i])] + " " + t2[0] + " "+ mynum elif i%3 == 1: mynum = t[int(num[i])-1] + " " + mynum elif i%3 == 0 and i//3>0: mynum = o[int(num[i])] + " " + t2[i//3] + " " + mynum return mynum.strip()
integer-to-english-words
PYTHON - Simple Fast Solution Cultural "elibelinde" approach
BladeRunner61
0
35
integer to english words
273
0.299
Hard
4,934
https://leetcode.com/problems/integer-to-english-words/discuss/2593570/Python3-Solution-still-needs-a-lot-of-refacturing-but-works
class Solution: def numberToWords(self, num: int) -> str: pairs = {0:"", 1:"One", 2:"Two", 3:"Three", 4:"Four", 5:"Five", 6:"Six", 7:"Seven", 8:"Eight", 9:"Nine",10:"Ten",11:"Eleven", 12:"Twelve", 13:"Thirteen", 14:"Fourteen", 15:"Fifteen", 16:"Sixteen", 17:"Seventeen", 18:"Eighteen", 19:"Nineteen", 20:"Twenty", 30:"Thirty", 40:"Forty", 50:"Fifty", 60:"Sixty", 70:"Seventy", 80:"Eighty", 90:"Ninety"} def hundred(n): if n[0] == '0': return "Zero" hund = [] val = int(n[0]) h = (val % 1000) // 100 t = (val % 100) // 10 u = (val % 10) if t == 1: u = 10 + u t = 0 if h: hund.append(pairs[h]) hund.append("Hundred") if t: hund.append(pairs[int(str(t)+'0')]) if u: hund.append(pairs[u]) return " ".join(hund) def thousand(n): thous = [] valth = int(n[0]) valh = [int(n[1])] hund = hundred(valh) if valth < 1: return f"{hund}" h = (valth % 1000) // 100 t = (valth % 100) // 10 u = (valth % 10) if t == 1: u = 10 + u t = 0 if h: thous.append(pairs[h]) thous.append("Hundred") if t: thous.append(pairs[int(str(t)+'0')]) if u: thous.append(pairs[u]) thous.append("Thousand") return f'{" ".join(thous)} {hund}'.strip() def million(n): mill = [] valmil = int(n[0]) valth = n[1:] thous = thousand(valth) if valmil < 1: return f"{thous}" h = (valmil % 1000) // 100 t = (valmil % 100) // 10 u = (valmil % 10) if t == 1: u = 10 + u t = 0 if h: mill.append(pairs[h]) mill.append("Hundred") if t: mill.append(pairs[int(str(t)+'0')]) if u: mill.append(pairs[u]) mill.append("Million") return f'{" ".join(mill)} {thous}'.strip() def billion(n): bill = [] valbil = int(n[0]) valmil = n[1:] mill = million(valmil) if valbil < 1: return f"{mill}" h = (valbil % 1000) // 100 t = (valbil % 100) // 10 u = (valbil % 10) if t == 1: u = 10 + u t = 0 if h: bill.append(pairs[h]) bill.append("Hundred") if t: bill.append(pairs[int(str(t)+'0')]) if u: bill.append(pairs[u]) bill.append("Billion") return f'{" ".join(bill)} {mill}'.strip() s = "{:,}".format(num) print(s) l = s.split(",") if len(l) == 1: # print(hundred(l)) return hundred(l) if len(l) == 2: # print(thousand(l)) return thousand(l) if len(l) == 3: # print(million(l)) return million(l) if len(l) == 4: # print(billion(l)) return billion(l)
integer-to-english-words
Python3 Solution- still needs a lot of refacturing but works
biobox
0
103
integer to english words
273
0.299
Hard
4,935
https://leetcode.com/problems/integer-to-english-words/discuss/2581813/Python-runtime-O(n)-memory-O(1)
class Solution: def numberToWords(self, num: int) -> str: def one(num): switcher = { 1: 'One', 2: 'Two', 3: 'Three', 4: 'Four', 5: 'Five', 6: 'Six', 7: 'Seven', 8: 'Eight', 9: 'Nine' } return switcher.get(num) def two_less_20(num): switcher = { 10: 'Ten', 11: 'Eleven', 12: 'Twelve', 13: 'Thirteen', 14: 'Fourteen', 15: 'Fifteen', 16: 'Sixteen', 17: 'Seventeen', 18: 'Eighteen', 19: 'Nineteen' } return switcher.get(num) def ten(num): switcher = { 2: 'Twenty', 3: 'Thirty', 4: 'Forty', 5: 'Fifty', 6: 'Sixty', 7: 'Seventy', 8: 'Eighty', 9: 'Ninety' } return switcher.get(num) def hundred(num): ans = "" e = num//100 num = num%100 if e > 0: ans += one(e) + " Hundred " f = num//10 num = num%10 if f > 1: ans += ten(f) + " " elif f == 1: return ans + two_less_20(f*10+num) + " " if num > 0: return ans + one(num) + " " return ans if num == 0 or not num: return "Zero" ans = "" num = str(num) length = len(num) digits = ["", "Thousand", "Million", "Billion"] threes = (length-1)//3 cur_size = length%3 for i in range(threes, -1, -1): if cur_size == 0: cur = int(num[0:3]) num = num[3:] else: cur = int(num[0:cur_size]) num = num[cur_size:] res = hundred(cur) if res: if ans and ans[-1] != " ": ans += " " ans += res + digits[i] if not num: while ans[-1] == " ": ans = ans[:-1] return ans cur_size = 0
integer-to-english-words
Python, runtime O(n), memory O(1)
tsai00150
0
137
integer to english words
273
0.299
Hard
4,936
https://leetcode.com/problems/integer-to-english-words/discuss/2546738/Python-3-or-Partial-Process-or-Keep-the-details-on-mind.-OwO
class Solution: def numberToWords(self, num: int) -> str: if num == 0: return 'Zero' base = ( '', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', ) middle_1 = ( 'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen', ) middle_2 = ( '', '', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety', ) units = ['', '', ' Thousand', ' Million', ' Billion'] left = num parts = [] while left != 0: parts.append(left % 1000) left = left // 1000 temp = [] units = units[:len(parts) + 1] parts = parts[::-1] for p in parts: results = [] s = str(p) s = '0' * (3 - len(s)) + s if s[0] != '0': results.append(base[int(s[0])] + ' Hundred') if s[1] != '0': if s[1] == '1': results.append(middle_1[int(s[2])]) else: results.append(middle_2[int(s[1])]) if s[2] != '0' and s[1] != '1': results.append(base[int(s[2])]) s = ' '.join(results) if len(s) > 2: s = s + units[len(parts) - len(temp)] temp.append(s.strip()) temp = [item for item in temp if item != ''] s = ' '.join(temp) return s.strip()
integer-to-english-words
Python 3 | Partial Process | Keep the details on mind. OwO
km4sh
0
96
integer to english words
273
0.299
Hard
4,937
https://leetcode.com/problems/integer-to-english-words/discuss/2479438/Python3-Clear-solution-with-explanation
class Solution: def numberToWords(self, num: int) -> str: # This approach handles the number in 3 digit chunks. Let's start by creating some maps of english words - ones, tens, yuck, and mult # These have aligned indecies. ones[1] = "one". tens[4] = "forty". # the 'yuck' map will help us with teen numbers that don't follow the usual pattern # and the 'mult' map will help us with multiples of thousands # First, break the input into a list. We're going to then look at that list in 3 digit chunks. This is because three hundred and forty two thousand requires # the same processing as three hundred and forty two - just with a thousand thrown on the end. The same goes for million and billion # The function thous_group will handle these 3 -digit chunks # First handle the hundreds - located at the first digit (group[0]). If the digit is 0, we add nothing, other wise we add one[digit] plus 'hundred' # Then we can check for teens. If the second digit (group[1]) is 1, we know we can just add the third digit's teen value # If not a teen, we can add the tens[at group[1]] and ones[at group[2]] directly # Finally, we can add the thousands, which is inferred from the input parameter mulitplier which we will set in our main loop later # - Note that we only add a thousands suffix if there is actually an output! The number 1,000,000 is not written One Million Zero Thousand # Once the function works (test it out with some 3 digit numbers), we can write our main loop that calls the function on different chunks of the input num # We will start at the end of the number and work our way to the front. The iterator i keeps track of our place, and the multiplier variable keeps track of which # multiple of 'thousand' we are on. # We can call our function on these three digit chunks, adding their output each time. # However, if the last chunk does not have 3 digits (ex. 12,345) then we can simply pad it out with some zeroes to make it 3 digits -> 012,345 output = '' # Handle zero case if num == 0: return 'Zero' # Create mappings to english words ones = ['', ' One', ' Two', ' Three', ' Four', ' Five', ' Six', ' Seven', ' Eight', ' Nine'] tens = ['','',' Twenty', ' Thirty', ' Forty', ' Fifty', ' Sixty', ' Seventy', ' Eighty', ' Ninety'] yuck = [' Ten', ' Eleven', ' Twelve', ' Thirteen', ' Fourteen', ' Fifteen', ' Sixteen', ' Seventeen', ' Eighteen', ' Nineteen'] mult = ['', ' Thousand', ' Million', ' Billion'] # Function that handles three digits at a time def thous_group(group, multiplier): out = '' # Handle Hundreds if group[0] != 0: out = ones[group[0]] + ' Hundred' # Handle teen numbers if group[1] == 1: out += yuck[group[2]] # Handle the tens and ones (if not teens) else: out += tens[group[1]] + ones[group[2]] # Handle multiplier (thousand, million, ...) if out: out += mult[multiplier] return out # Turn the input number into a list of integer digits num = list(str(num)) num = [int(x) for x in num] # Loop through 3 digit groups i = len(num) multiplier = 0 while i > 0: # If there are fewer than 3 digits left, add buffer 0s to it if i - 3 < 0: num = abs(i-3)*[0] + num i += abs(i-3) # Use the helper function to return the string for this group output = thous_group(num[i-3:i], multiplier) + output i -= 3 multiplier += 1 return output.strip()
integer-to-english-words
[Python3] Clear solution with explanation
connorthecrowe
0
102
integer to english words
273
0.299
Hard
4,938
https://leetcode.com/problems/integer-to-english-words/discuss/2245534/Python-table-solution
class Solution: def convert(self, rem): d = { 0: ["Zero", "", "Ten"], 1: ["One", "", "Eleven"], 2: ["Two", "Twenty", "Twelve"], 3: ["Three", "Thirty", "Thirteen"], 4: ["Four", "Forty", "Fourteen"], 5: ["Five", "Fifty", "Fifteen"], 6: ["Six", "Sixty", "Sixteen"], 7: ["Seven", "Seventy", "Seventeen"], 8: ["Eight", "Eighty", "Eighteen"], 9: ["Nine", "Ninety", "Nineteen"] } ret_arr = [] if rem >= 100: q, r = divmod(rem, 100) ret_arr.append(d[q][0] + ' Hundred') rem = r if rem >= 20: q, r = divmod(rem, 10) ret_arr.append(d[q][1]) rem = r if rem >= 10: ret_arr.append(d[rem%10][2]) rem = 0 if rem != 0: ret_arr.append(d[rem][0]) return " ".join(ret_arr) def numberToWords(self, num: int) -> str: if num == 0: return 'Zero' array = [ [10**9, 'Billion'], [10**6, 'Million'], [10**3, 'Thousand'], ] ret_arr = [] for val, symbol in array: if num >= val: q, r = divmod(num, val) ret_arr.append(self.convert(q) + ' ' + symbol) num = r if num != 0: ret_arr.append(self.convert(num)) return ' '.join(ret_arr)
integer-to-english-words
Python table solution
corvofeng
0
105
integer to english words
273
0.299
Hard
4,939
https://leetcode.com/problems/integer-to-english-words/discuss/2124014/Easy-divide-and-conquer-Python3-solution
class Solution: def __init__(self): self.words = { 1: 'One', 2: 'Two', 3: 'Three', 4: 'Four', 5: 'Five', 6: 'Six', 7: 'Seven', 8: 'Eight', 9: 'Nine', 10: 'Ten', 11: 'Eleven', 12: 'Twelve', 13: 'Thirteen', 14: 'Fourteen', 15: 'Fifteen', 16: 'Sixteen', 17: 'Seventeen', 18: 'Eighteen', 19: 'Nineteen', 20: 'Twenty', 30: 'Thirty', 40: 'Forty', 50: 'Fifty', 60: 'Sixty', 70: 'Seventy', 80: 'Eighty', 90: 'Ninety' } def convert(self, num: int) ->str: remaining = num ret = str() if remaining >= 100: q, r = divmod(remaining, 100) ret += self.words[q] + ' Hundred' remaining -= q*100 if remaining > 0: ret += ' ' if remaining >= 20: q, r = divmod(remaining, 10) ret += self.words[q*10] remaining -= q*10 if remaining > 0: ret += ' ' if remaining > 0: ret += self.words[remaining] return ret def numberToWords(self, num: int) -> str: remaining = num ret = '' if num == 0: ret = 'Zero' else: if remaining >= 1000000000: q = remaining // 1000000000 ret += ' ' + self.convert(q) + ' Billion' remaining -= q*1000000000 if remaining >= 1000000: q = remaining // 1000000 ret += ' ' + self.convert(q) + ' Million' remaining -= q*1000000 if remaining >= 1000: q = remaining // 1000 ret += ' ' + self.convert(q) + ' Thousand' remaining -= q*1000 if remaining > 0: ret += ' ' ret += self.convert(remaining) return ret.strip()
integer-to-english-words
Easy divide and conquer Python3 solution
mwgarrett9936
0
209
integer to english words
273
0.299
Hard
4,940
https://leetcode.com/problems/integer-to-english-words/discuss/1989619/Python-Ad-hoc-approach
class Solution: ones = { "1": "One", "2": "Two", "3": "Three", "4": "Four", "5": "Five", "6": "Six", "7": "Seven", "8": "Eight", "9": "Nine" } tens = { "1": "Ten", "2": "Twenty", "3": "Thirty", "4": "Forty", "5": "Fifty", "6": "Sixty", "7": "Seventy", "8": "Eighty", "9": "Ninety" } between = { 11: "Eleven", 12: "Twelve", 13: "Thirteen", 14: "Fourteen", 15: "Fifteen", 16: "Sixteen", 17: "Seventeen", 18: "Eighteen", 19: "Nineteen" } def part(self, ns, r, suffix): ans = "" all_zeroes = True for i in range(r - 2, min(len(ns), r) + 1): all_zeroes = all_zeroes and ns[len(ns) - i] == '0' if not all_zeroes: has_hundreds = False if len(ns) >= r and ns[len(ns) - r] != '0': ans += self.ones[ns[len(ns) - r]] + " Hundred" has_hundreds = True rest = 0 if len(ns) >= r - 1: rest += int(ns[len(ns) - (r - 1)]) * 10 if len(ns) >= r - 2: rest += int(ns[len(ns) - (r - 2)]) if rest > 0: if has_hundreds: ans += " " if rest >= 11 and rest <= 19: ans += self.between[rest] elif rest >= 10: rest_s = str(rest) ans += self.tens[rest_s[0]] if rest_s[1] != '0': ans += " " + self.ones[rest_s[1]] else: ans += self.ones[str(rest)] ans += suffix return ans def numberToWords(self, num: int) -> str: if num == 0: return "Zero" ns = str(num) a1 = "" if num < 1000000000 else self.ones[ns[0]] + " Billion" a2 = self.part(ns, 9, " Million") a3 = self.part(ns, 6, " Thousand") a4 = self.part(ns, 3, "") ans = [x for x in [a1, a2, a3, a4] if x] return " ".join(ans)
integer-to-english-words
Python Ad-hoc approach
SajLeet
0
116
integer to english words
273
0.299
Hard
4,941
https://leetcode.com/problems/integer-to-english-words/discuss/1976269/Python-Solution
class Solution: def numberToWords(self, num: int) -> str: word_bank = { 0: "Zero", 1: "One", 2: "Two", 3: "Three", 4: "Four", 5: "Five", 6: "Six", 7: "Seven", 8: "Eight", 9: "Nine", 10: "Ten", 11: "Eleven", 12: "Twelve", 13: "Thirteen", 14: "Fourteen", 15: "Fifteen", 16: "Sixteen", 17: "Seventeen", 18: "Eighteen", 19: "Nineteen", 20: "Twenty", 30: "Thirty", 40: "Forty", 50: "Fifty", 60: "Sixty", 70: "Seventy", 80: "Eighty", 90: "Ninety", 100: "Hundred", 1000: "Thousand", 1000000: "Million", 1000000000: "Billion", } if 0 <= num <= 20 or (num <= 90 and num % 10 == 0): return word_bank[num] retult = str(" ") numStr = str(num).zfill(10) numList = list([]) wordList = list([]) spl1 = int(0) for i, j in enumerate([9, 2, 1, 6, 2, 1, 3, 2, 1, 0]): numList.append(list([int(numStr[spl1:i+1]), 10 ** j])) spl1 = i+1 for i, j in enumerate(numList): if j[0] > 0: if j[1] > 10: wordList.extend((word_bank[j[0]], word_bank[j[1]])) elif j[0] == 1 and j[1] == 10: numList[i+1][0] += 10 else: wordList.append(word_bank[j[1] * j[0]]) elif (j[1] == 1000 or j[1] == 1000000) and (numList[i-1][0] > 0 or numList[i-2][0] > 0): wordList.append(word_bank[j[1]]) return retult.join(wordList)
integer-to-english-words
Python Solution
EddieAtari
0
125
integer to english words
273
0.299
Hard
4,942
https://leetcode.com/problems/integer-to-english-words/discuss/1962240/Python-or-Dictionary-or-Easy-Solution
class Solution: def numberToWords(self, num: int) -> str: """ English words has different names for 1 - 19 Then 20, 30, 40, 50, 60, 70, 80, 90, 100 1000 1000000 1000000 Consider them as bills, then this problem transform into a similar problem 2241. Design an ATM Machine Where we try to find number of bills given priority as Descending order of values (1 billion to 1) One gotcha here: number of each bills can also be more than 10 in this case, we just pass the value as a recursive function and evaluate it's english word For example: 234 number of million dollar bills in this case we pass 234 in numberToWords() function and get 'Two Hundred Thirty Four' as a result """ if num == 0: return 'Zero' num_dict = { 1 : 'One', 2 : 'Two', 3 : 'Three', 4 : 'Four', 5 : 'Five', 6 : 'Six', 7 : 'Seven', 8 : 'Eight', 9 : 'Nine', 10 : 'Ten', 11 : 'Eleven', 12 : 'Twelve', 13 : 'Thirteen', 14 : 'Fourteen', 15 : 'Fifteen', 16 : 'Sixteen', 17 : 'Seventeen', 18 : 'Eighteen', 19 : 'Nineteen', 20 : 'Twenty', 30 : 'Thirty', 40 : 'Forty', 50 : 'Fifty', 60 : 'Sixty', 70 : 'Seventy', 80 : 'Eighty', 90 : 'Ninety', 100 : 'Hundred', 1000 : 'Thousand', 1000000 : 'Million', 1000000000 : 'Billion' } bills = sorted(num_dict.keys(), reverse=True) num_of_bills = [0] * len(bills[:-9]) # higher number given priority for idx, bill in enumerate(bills[:-9]): # get the count num_of_bills[idx] = num // bill # get reminder num = num % bill ans = '' # now we have count of each bills for idx, val in enumerate(num_of_bills): if val > 0: if idx < 4: # num of bills can be more than single digit ans += self.numberToWords(val) + ' ' + num_dict[bills[idx]] + ' ' # anything below 100 has direct dictionary mapping else: ans += num_dict[bills[idx]] + ' ' if num: ans += num_dict[num] # strip ans as a possibility of getting extra ' ' return ans.strip()
integer-to-english-words
Python | Dictionary | Easy Solution
showing_up_each_day
0
204
integer to english words
273
0.299
Hard
4,943
https://leetcode.com/problems/integer-to-english-words/discuss/1941018/Python3-Solution
class Solution: def numberToWords(self, num: int) -> str: if num == 0: return "Zero" placeInArraySuffix = {1:"Thousand", 2:"Million", 3:"Billion"} tens = {2:"Twenty",3:"Thirty", 4:"Forty", 5:"Fifty", 6:"Sixty",7:"Seventy",8:"Eighty",9:"Ninety"} ones = {1:"One",2:"Two",3:'Three',4:"Four",5:"Five",6:"Six",7:"Seven",8:"Eight",9:"Nine",10:"Ten", 11:"Eleven",12:"Twelve",13:"Thirteen",14:"Fourteen",15:"Fifteen",16:"Sixteen",17:"Seventeen", 18:'Eighteen',19:"Nineteen"} num = str(num) cnt = 0 s = "" for i in range(len(num)-1, -1, -1): cnt += 1 s = num[i] + s if cnt == 3: cnt = 0 s = '.' + s sArr = [] sArrCpy = s.split('.') for i in sArrCpy: if i != '': sArr.append(i) sArr.reverse() finalAns = "" for i in range(len(sArr)-1, -1, -1): fa = sArr[i] if len(sArr[i]) == 3: if int(sArr[i][0]) != 0: finalAns += ones[int(sArr[i][0])] + ' ' + "Hundred" + ' ' sArr[i] = sArr[i][1:] if len(sArr[i]) == 2: if int(sArr[i]) not in ones: if int(sArr[i][0]) != 0: finalAns += tens[int(sArr[i][0])] + ' ' sArr[i] = sArr[i][1:] else: finalAns += ones[int(sArr[i])] + " " if len(sArr[i]) == 1: if sArr[i][0] == '0': pass else: finalAns += ones[int(sArr[i][0])] + ' ' if i == 0: pass else: if int(fa) != 0: finalAns += placeInArraySuffix[i] + ' ' return(finalAns.strip(' '))
integer-to-english-words
Python3 Solution
DietCoke777
0
91
integer to english words
273
0.299
Hard
4,944
https://leetcode.com/problems/integer-to-english-words/discuss/1846853/Python-Simple-Solution!-Helper-Function
class Solution(object): def numberToWords(self, num): if num == 0: return "Zero" powersOfThousand = ["", "Thousand", "Million", "Billion"] fullName, powerOfThousand = "", 0 while num: name = self.helper(num%1000) if len(name) >= 1: name = name + " " + powersOfThousand[powerOfThousand] if powerOfThousand >= 1 else name fullName = name + " " + fullName if len(fullName) >= 1 else name num //= 1000 powerOfThousand += 1 return fullName def helper(self, n): name = "" digits = ["", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"] teens = ["Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"] multiplesOfTen = ["Zero", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"] hundred = "Hundred" hundreds, tens, ones = n // 100, n // 10 % 10, n % 100 % 10 if hundreds >= 1: name = digits[hundreds] + " " + hundred if hundreds >= 1 and (tens != 0 or ones != 0): name += " " if tens == 0: name += digits[ones] elif tens == 1: name += teens[ones] elif tens > 1 and ones == 0: name += multiplesOfTen[tens] elif tens > 1 and ones >= 1: name += multiplesOfTen[tens] + " " + digits[ones] return name
integer-to-english-words
Python - Simple Solution! Helper Function
domthedeveloper
0
174
integer to english words
273
0.299
Hard
4,945
https://leetcode.com/problems/integer-to-english-words/discuss/1494424/Simple-Python-Solution
class Solution: def numberToWords(self, num: int) -> str: mapping = { 10**9: "Billion", 10**6: "Million", 10**3: "Thousand", 10**2: "Hundred", 90: "Ninety", 80: "Eighty", 70: "Seventy", 60: "Sixty", 50: "Fifty", 40: "Forty", 30: "Thirty", 20: "Twenty", 19: "Nineteen", 18: "Eighteen", 17: "Seventeen", 16: "Sixteen", 15: "Fifteen", 14: "Fourteen", 13: "Thirteen", 12: "Twelve", 11: "Eleven", 10: "Ten", 9: "Nine", 8: "Eight", 7: "Seven", 6: "Six", 5: "Five", 4: "Four", 3: "Three", 2: "Two", 1: "One", 0: "Zero" } if num <= 20: return mapping[num] result = '' orders = sorted(list(mapping.keys()), reverse=True) while num > 0: for order in orders: if num >= order: count = num // order num -= count * order if order >= 100: to_add = f"{self.numberToWords(count)} {mapping[order]}" else: to_add = str(mapping[order]) if result: result += f" {to_add}" else: result = to_add break return result
integer-to-english-words
Simple Python Solution
iahouma
0
243
integer to english words
273
0.299
Hard
4,946
https://leetcode.com/problems/integer-to-english-words/discuss/914458/Python-easy-solution-(split-by-functions)
class Solution: def numberToWords(self, num: int) -> str: def ones(num): vals = { 1: "One", 2: "Two", 3: "Three", 4: "Four", 5: "Five", 6: "Six", 7: "Seven", 8: "Eight", 9: "Nine" } return vals.get(num) def tens_until_tewenty(num): vals = { 10: "Ten", 11: "Eleven", 12: "Twelve", 13: "Thirteen", 14: "Fourteen", 15: "Fifteen", 16: "Sixteen", 17: "Seventeen", 18: "Eighteen", 19: "Nineteen" } return vals.get(num) def tens(num): vals = { 2: "Twenty", 3: "Thirty", 4: "Forty", 5: "Fifty", 6: "Sixty", 7: "Seventy", 8: "Eighty", 9: "Ninety" } return vals.get(num) def process_threes(num): r, q = divmod(num, 100) res = "" if r > 0: res += " " + ones(r) + " Hundred" if 10 <= q < 20: res += " " + tens_until_tewenty(q) elif q >= 20: cur, rem = divmod(q, 10) res += " " + tens(cur) if rem > 0: res += " " + ones(rem) elif q == 0: return res else: res += " " + ones(q) return res def process(num): billion = 10**9 million = 10**6 thousand = 10**3 res = "" if num // billion > 0: r, q = divmod(num, billion) if r > 0: res += process_threes(r) + " Billion" num = q if num // million > 0: r, q = divmod(num, million) if r > 0: res += process_threes(r) + " Million" num = q if num // thousand > 0: r, q = divmod(num, thousand) if r > 0: res += process_threes(r) + " Thousand" num = q if num > 0: res += process_threes(num) return res if num == 0: return "Zero" return process(num).strip()
integer-to-english-words
Python easy solution (split by functions)
ermolushka2
0
199
integer to english words
273
0.299
Hard
4,947
https://leetcode.com/problems/integer-to-english-words/discuss/389550/Python-Solution-(Dictionaries)
class Solution: def numberToWords(self, num: int) -> str: ones = {1:'One', 2:'Two', 3:'Three', 4:'Four', 5:'Five', 6:'Six', 7:'Seven', 8:'Eight', 9:'Nine'} teens = {10:'Ten', 11:'Eleven', 12:'Twelve', 13:'Thirteen', 14:'Fourteen', 15:'Fifteen', 16:'Sixteen', 17:'Seventeen', 18:'Eighteen', 19:'Nineteen'} tens = {2:'Twenty', 3:'Thirty', 4:'Forty', 5:'Fifty', 6:'Sixty', 7:'Seventy', 8:'Eighty', 9:'Ninety'} comas = {0:'', 1:'Thousand', 2:'Million', 3:'Billion'} def threeDigit(n): res = '' if n // 100: res += (ones[n//100]+' Hundred ') if n%100 == 0: return res n %= 100 if int(n) == 0: return res elif n < 10: res += (ones[n]+' ') elif n < 20: res += (teens[n]+' ') elif n%10 == 0: res += (tens[n//10]+' ') else: res += (tens[n//10]+' '+ones[n%10]+' ') return res if num == 0: return 'Zero' if num < 1000: return threeDigit(num).strip() numdiv, res = [], '' while num > 0: numdiv.insert(0, num%1000) num //= 1000 #num: 1234567 => [1,234,567] for i in range(len(numdiv)): part = threeDigit(numdiv[i]) if part == '': continue else: res += (part+comas[len(numdiv)-1-i]+' ') return res.rstrip()
integer-to-english-words
Python Solution (Dictionaries)
FFurus
0
184
integer to english words
273
0.299
Hard
4,948
https://leetcode.com/problems/h-index/discuss/785586/Python3-O(n)-without-sorting!
class Solution: def hIndex(self, citations: List[int]) -> int: tmp = [0] * (len(citations) + 1) for i in range(len(citations)): if citations[i] > len(citations): tmp[len(citations)] += 1 else: tmp[citations[i]] += 1 sum_ = 0 for i in range(len(tmp) - 1, -1, -1): sum_ += tmp[i] if sum_ >= i: return i
h-index
Python3 O(n) without sorting!
DebbieAlter
5
489
h index
274
0.382
Medium
4,949
https://leetcode.com/problems/h-index/discuss/1872013/O(n)-Easy-short-Python-Code-with-Explanation
class Solution: def hIndex(self, citations: List[int]) -> int: n = len(citations) + 1 arr = [0] * n for c in citations: if c >= n: arr[n-1] += 1 else: arr[c] += 1 total = 0 for i in range(n-1, -1, -1): total += arr[i] if total >= i: return i return 0
h-index
O(n) Easy short Python Code with Explanation
jlu56
1
207
h index
274
0.382
Medium
4,950
https://leetcode.com/problems/h-index/discuss/694269/Python3-four-1-liners
class Solution: def hIndex(self, citations: List[int]) -> int: return sum(i < x for i, x in enumerate(sorted(citations, reverse=True)))
h-index
[Python3] four 1-liners
ye15
1
54
h index
274
0.382
Medium
4,951
https://leetcode.com/problems/h-index/discuss/694269/Python3-four-1-liners
class Solution: def hIndex(self, citations: List[int]) -> int: return next((len(citations)-i for i, x in enumerate(sorted(citations)) if len(citations)-i <= x), 0)
h-index
[Python3] four 1-liners
ye15
1
54
h index
274
0.382
Medium
4,952
https://leetcode.com/problems/h-index/discuss/694269/Python3-four-1-liners
class Solution: def hIndex(self, citations: List[int]) -> int: return max((i+1 for i, x in enumerate(sorted(citations, reverse=True)) if i < x), default=0)
h-index
[Python3] four 1-liners
ye15
1
54
h index
274
0.382
Medium
4,953
https://leetcode.com/problems/h-index/discuss/694269/Python3-four-1-liners
class Solution: def hIndex(self, citations: List[int]) -> int: return max((min(i, x) for i, x in enumerate(sorted(citations, reverse=True), 1)), default=0)
h-index
[Python3] four 1-liners
ye15
1
54
h index
274
0.382
Medium
4,954
https://leetcode.com/problems/h-index/discuss/694269/Python3-four-1-liners
class Solution: def hIndex(self, citations: List[int]) -> int: citations.sort() n = len(citations) lo, hi = 0, n while lo < hi: mid = (lo + hi)//2 if citations[mid] >= n - mid: hi = mid else: lo = mid + 1 return n - lo
h-index
[Python3] four 1-liners
ye15
1
54
h index
274
0.382
Medium
4,955
https://leetcode.com/problems/h-index/discuss/387453/Solution-in-Python-3-(beats-~99)-(four-lines)
class Solution: def hIndex(self, c: List[int]) -> int: L = len(c) for i,j in enumerate(sorted(c)): if L - i <= j: return L - i return 0 - Junaid Mansuri (LeetCode ID)@hotmail.com
h-index
Solution in Python 3 (beats ~99%) (four lines)
junaidmansuri
1
517
h index
274
0.382
Medium
4,956
https://leetcode.com/problems/h-index/discuss/2801874/Easy-python-solution-time%3AO(nlogn)-and-space%3AO(1)
class Solution: def hIndex(self, citations: List[int]) -> int: citations.sort() ans = len(citations) for num in citations: if num < ans: ans -= 1 else: break return ans
h-index
Easy python solution, time:O(nlogn) and space:O(1)
jackie890621
0
6
h index
274
0.382
Medium
4,957
https://leetcode.com/problems/h-index/discuss/2353282/Python-implementation-using-bucketing-with-proper-explanation
class Solution: def hIndex(self, citations: List[int]) -> int: """ citations = [3,0,6,1,5] n : length of citations H - index defination: A scientist has an index h if h of their n papers have at least h citations each, and the other n − h papers have no more than h citations each. [0, 0, 0, 0, 0, 0] we define a list of size n + 1 0 1 2 3 4 5 The above list will be used as a bucket which will keep the count of papers with i(index in the list) citations. citations[0] = 3 [0, 0, 0, 1, 0, 0] 0 1 2 3 4 5 citations[1] = 0 [1, 0, 0, 1, 0, 0] 0 1 2 3 4 5 citations[2] = 6 [1, 0, 0, 1, 0, 1] when cits for a paper is > 5 then put the value in n lst index 0 1 2 3 4 5 citations[3] = 1 [1, 1, 0, 1, 0, 1] 0 1 2 3 4 5 citations[4] = 5 [1, 1, 0, 1, 0, 2] 0 1 2 3 4 5 Find suffix sum of above list: [5, 4, 3, 3, 2, 2] Find the larget index where index value(i) <= A[i] 0 1 2 3 4 5 which is 3 ans : 3 """ n = len(citations) b = [0] * (n + 1) for i in range(n): b[min(citations[i], n)] += 1 for i in range(n, -1, -1): if b[i] >= i: return i b[i - 1] += b[i] return -1
h-index
Python implementation using bucketing with proper explanation
Pratyush_Priyam_Kuanr
0
22
h index
274
0.382
Medium
4,958
https://leetcode.com/problems/h-index/discuss/1420745/binary-search-or-python-or-betterthan-92
class Solution: def hIndex(self, citations: List[int]) -> int: low=0 n=len(citations) high=min(n,max(citations)) citations.sort() def fun(mid): b=bisect.bisect_left(citations,mid) if n-b>=mid: return True return False ans=0 while(low<=high): mid=low+(high-low)//2 if fun(mid): low=mid+1 ans=max(ans,mid) else: high=mid-1 return ans
h-index
binary search | python | betterthan 92%
heisenbarg
0
173
h index
274
0.382
Medium
4,959
https://leetcode.com/problems/h-index/discuss/764403/Python3-1-line
class Solution: def hIndex(self, citations: List[int]) -> int: citations.sort(reverse=True) ans = 0 for i, c in enumerate(citations, 1): if c >= i: ans = i return ans
h-index
[Python3] 1-line
ye15
0
94
h index
274
0.382
Medium
4,960
https://leetcode.com/problems/h-index/discuss/764403/Python3-1-line
class Solution: def hIndex(self, citations: List[int]) -> int: return next((len(citations)-i for i, x in enumerate(sorted(citations)) if len(citations)-i <= x), 0)
h-index
[Python3] 1-line
ye15
0
94
h index
274
0.382
Medium
4,961
https://leetcode.com/problems/h-index/discuss/764403/Python3-1-line
class Solution: def hIndex(self, citations: List[int]) -> int: return bisect_right([i-c for i, c in enumerate(sorted(citations, reverse=True), 1)], 0)
h-index
[Python3] 1-line
ye15
0
94
h index
274
0.382
Medium
4,962
https://leetcode.com/problems/h-index/discuss/507343/Python3-4-lines-using-sort()-function
class Solution: def hIndex(self, citations: List[int]) -> int: citations.sort(reverse=True) while citations and citations[-1]<len(citations): citations.pop() return len(citations)
h-index
Python3 4-lines using sort() function
jb07
0
83
h index
274
0.382
Medium
4,963
https://leetcode.com/problems/h-index/discuss/785986/Simple-Python-Solution-Explained
class Solution: def hIndex(self, citations: List[int]) -> int: citations.sort(reverse = True) for indx, citation in enumerate(citations): if indx >= citation: return indx return len(citations)
h-index
Simple Python Solution Explained
spec_he123
-1
197
h index
274
0.382
Medium
4,964
https://leetcode.com/problems/h-index-ii/discuss/2729382/Python3-Solution-or-Binary-Search-or-O(logn)
class Solution: def hIndex(self, A): n = len(A) l, r = 0, n - 1 while l < r: m = (l + r + 1) // 2 if A[m] > n - m: r = m - 1 else: l = m return n - l - (A[l] < n - l)
h-index-ii
✔ Python3 Solution | Binary Search | O(logn)
satyam2001
2
109
h index ii
275
0.374
Medium
4,965
https://leetcode.com/problems/h-index-ii/discuss/694273/Python3-bisect_right-and-bisect_left-H-Index-II
class Solution: def hIndex(self, citations: List[int]) -> int: if not citations: return 0 n = len(citations) lo, hi = 0, n+1 while lo < hi: mid = (lo + hi)//2 if citations[-mid] < mid: hi = mid else: lo = mid + 1 return max(lo-1, 0)
h-index-ii
Python3 bisect_right and bisect_left - H-Index II
r0bertz
1
107
h index ii
275
0.374
Medium
4,966
https://leetcode.com/problems/h-index-ii/discuss/694273/Python3-bisect_right-and-bisect_left-H-Index-II
class Solution: def hIndex(self, citations: List[int]) -> int: n = len(citations) lo, hi = 0, n while lo < hi: mid = (lo + hi)//2 if citations[mid] < n - mid: lo = mid + 1 else: hi = mid return n - lo
h-index-ii
Python3 bisect_right and bisect_left - H-Index II
r0bertz
1
107
h index ii
275
0.374
Medium
4,967
https://leetcode.com/problems/h-index-ii/discuss/447298/Python-Solution-with-Binary-Search
class Solution: def hIndex(self, citations: List[int]) -> int: lo, hi = 0, len(citations) while lo < hi: mid = (lo + hi) // 2 if citations[~mid] > mid: lo = mid + 1 else: hi = mid return lo
h-index-ii
Python Solution with Binary Search
Yaxe522
1
208
h index ii
275
0.374
Medium
4,968
https://leetcode.com/problems/h-index-ii/discuss/2785536/H-index
class Solution: def hIndex(self, citations: List[int]) -> int: start=0 n=len(citations) end=len(citations)-1 while start<=end: mid=start+(end-start)//2 if citations[mid]==(n-mid): return citations[mid] elif citations[mid]>(n-mid): end=mid-1 else: start=mid+1 return (n-start)
h-index-ii
H-index
shivansh2001sri
0
4
h index ii
275
0.374
Medium
4,969
https://leetcode.com/problems/h-index-ii/discuss/2715727/Python-or-O(n)-or-94.36-Fast-85.77-Mem-or-no-div-centering
class Solution: def hIndex(self, citations: List[int]) -> int: max_h = 0 idx = -1 while idx >= -len(citations): if citations[idx] >= abs(idx): max_h = abs(idx) idx -= 1 else: break return max_h
h-index-ii
Python | O(n) | 94.36% Fast, 85.77% Mem | no div centering
lan32
0
7
h index ii
275
0.374
Medium
4,970
https://leetcode.com/problems/h-index-ii/discuss/2647931/Simple-Binary-Search
class Solution: def hIndex(self, citations: List[int]) -> int: n = len(citations) l, r = 0 , n-1 while( l <= r): mid = l + (r -l ) //2 if citations[mid]==(n-mid): return n - mid elif citations[mid] > n-mid: r = mid - 1 else: l = mid + 1 return n - (r + 1)
h-index-ii
Simple Binary Search
akshitub
0
8
h index ii
275
0.374
Medium
4,971
https://leetcode.com/problems/h-index-ii/discuss/2397393/Binary-search-solution-python3-solution
class Solution: # O(logn) time, # O(1) space, # Approach: binary search, def hIndex(self, citations: List[int]) -> int: n = len(citations) def findLowerBoundIndexToNum(lo, hi, num): while True: mid = (lo+hi)//2 curr = citations[mid] if curr == num and (mid == 0 or citations[mid-1] < num): return mid elif curr == num: hi = mid-1 elif curr > num: if mid == 0 or citations[mid-1] < num: return mid hi = mid-1 else: if lo >= hi: if citations[hi] >= num: return hi else: return n lo = mid+1 def valid(hindex): index = findLowerBoundIndexToNum(0, n-1, hindex) citation_num = n - index return citation_num >= hindex def findMaxHindex(lo, hi): while True: mid = (lo+hi)//2 validCitation = valid(mid) if validCitation and (mid == n or not valid(mid+1)): return mid elif not validCitation: hi = mid-1 else: if lo >= hi: return hi lo = mid+1 return findMaxHindex(0, n)
h-index-ii
Binary search solution python3 solution
destifo
0
15
h index ii
275
0.374
Medium
4,972
https://leetcode.com/problems/h-index-ii/discuss/1098396/Very-Short-O(n)-Python3-Solution
class Solution: def hIndex(self, citations: List[int]) -> int: for i in range(len(citations)): if citations[i]>=len(citations)-i: return len(citations)-i return 0
h-index-ii
Very Short O(n) Python3 Solution
yash2709
0
141
h index ii
275
0.374
Medium
4,973
https://leetcode.com/problems/h-index-ii/discuss/737820/Python3-solution-simple-binary-search-llessr-not-use-less
class Solution: def hIndex(self, citations: List[int]) -> int l,r=0,len(citations) while l<r: mid=(l+r-1)//2 if citations[mid]<len(citations)-mid: l=mid+1 else: r=mid return len(citations)-l
h-index-ii
Python3 solution, simple binary search l<r not use <=
ladykkk
0
71
h index ii
275
0.374
Medium
4,974
https://leetcode.com/problems/h-index-ii/discuss/694822/Both-O(n)-and-O(log-n)-solution-in-Python3
class Solution: def hIndex(self, citations: List[int]) -> int: if not citations: return 0 n = len(citations) for i in range(n): if citations[i] >= n-i: return n-i return 0
h-index-ii
Both O(n) and O(log n) solution in Python3
nobi1007
0
49
h index ii
275
0.374
Medium
4,975
https://leetcode.com/problems/h-index-ii/discuss/694822/Both-O(n)-and-O(log-n)-solution-in-Python3
class Solution: def hIndex(self, citations: List[int]) -> int: if not citations: return 0 maxi = 0 n = len(citations) left = 0 right = n-1 while left <= right: mid = ( left + right ) // 2 if citations[mid] >= n - mid: maxi = max(maxi, n - mid) right = mid - 1 else: left = mid + 1 return maxi
h-index-ii
Both O(n) and O(log n) solution in Python3
nobi1007
0
49
h index ii
275
0.374
Medium
4,976
https://leetcode.com/problems/h-index-ii/discuss/694163/Simple-Intuitive-Idiomatic-Python3-Solution-O(logn)
class Solution: def hIndex(self, citations: List[int]) -> int: low, high = 0, len(citations)-1 while low <= high: mid = (low+high) // 2 if citations[mid] >= len(citations)-mid and \ (mid == 0 or citations[mid-1] <= len(citations)-mid): return len(citations) - mid if mid > 0 and citations[mid-1] > len(citations)-mid: high = mid - 1 else: low = mid + 1 return 0
h-index-ii
Simple, Intuitive, Idiomatic Python3 Solution - O(logn)
schedutron
0
55
h index ii
275
0.374
Medium
4,977
https://leetcode.com/problems/h-index-ii/discuss/507348/Python3-super-simple-3-lines-code
class Solution: def hIndex(self, citations: List[int]) -> int: while citations and citations[0]<len(citations): citations.pop(0) return len(citations)
h-index-ii
Python3 super simple 3-lines code
jb07
0
59
h index ii
275
0.374
Medium
4,978
https://leetcode.com/problems/first-bad-version/discuss/2700688/Simple-Python-Solution-Using-Binary-Search
class Solution: def firstBadVersion(self, n: int) -> int: left = 1 right = n result = 1 while left<=right: mid = (left+right)//2 if isBadVersion(mid) == False: left = mid+1 else: right = mid-1 result = mid return result
first-bad-version
✔️ Simple Python Solution Using Binary Search 🔥
pniraj657
25
3,400
first bad version
278
0.43
Easy
4,979
https://leetcode.com/problems/first-bad-version/discuss/1743709/Python-Simple-Python-Solution-Using-Binary-Search
class Solution: def firstBadVersion(self, n: int) -> int: result = 1 low = 1 high = n while low <= high: mid = (low + high) //2 if isBadVersion(mid) == False: low = mid + 1 else: high = mid - 1 result = mid return result
first-bad-version
[ Python ] ✅✅ Simple Python Solution Using Binary Search 🔥🥳✌👍
ASHOK_KUMAR_MEGHVANSHI
15
1,200
first bad version
278
0.43
Easy
4,980
https://leetcode.com/problems/first-bad-version/discuss/2180671/Python3-clean-code-faster-than-96
class Solution: def firstBadVersion(self, n: int) -> int: low,high = 1, n while low<=high: mid=(low+high)//2 isBad = isBadVersion(mid) if(isBad): high = mid-1 else: low = mid+1 return low
first-bad-version
📌 Python3 clean code faster than 96%
Dark_wolf_jss
8
288
first bad version
278
0.43
Easy
4,981
https://leetcode.com/problems/first-bad-version/discuss/1633603/28-ms-faster-than-80.64
class Solution: def firstBadVersion(self, n): """ :type n: int :rtype: int """ L, R = 0, n if isBadVersion(1): return 1 while L<R: mid = (L+R)//2 if isBadVersion(mid): R = mid else: L = mid + 1 return L
first-bad-version
28 ms, faster than 80.64%
OAOrzz
3
475
first bad version
278
0.43
Easy
4,982
https://leetcode.com/problems/first-bad-version/discuss/1425012/Binary-search-99.9-speed
class Solution: def firstBadVersion(self, n): left, right = 1, n if isBadVersion(left): return left while left < right: middle = (left + right) // 2 if isBadVersion(middle): right = middle else: left = middle + 1 return left
first-bad-version
Binary search, 99.9% speed
EvgenySH
3
587
first bad version
278
0.43
Easy
4,983
https://leetcode.com/problems/first-bad-version/discuss/379775/Solution-in-Python-3-(beats-~98)-(six-lines)
class Solution: def firstBadVersion(self, n): if isBadVersion(1): return 1 b = [1,n] while 1: m, i, j = (b[0]+b[1])//2, b[0], b[1] b = [m,j] if isBadVersion(i) == isBadVersion(m) else [i,m] if j - i == 1: return j - Junaid Mansuri (LeetCode ID)@hotmail.com
first-bad-version
Solution in Python 3 (beats ~98%) (six lines)
junaidmansuri
3
1,200
first bad version
278
0.43
Easy
4,984
https://leetcode.com/problems/first-bad-version/discuss/606725/Python3-binary-search
class Solution: def firstBadVersion(self, n): lo, hi = 1, n while lo < hi: mid = lo + hi >> 1 if isBadVersion(mid): hi = mid else: lo = mid + 1 return lo
first-bad-version
[Python3] binary search
ye15
2
127
first bad version
278
0.43
Easy
4,985
https://leetcode.com/problems/first-bad-version/discuss/2507949/Python-Solution
class Solution: def firstBadVersion(self, n): """ :type n: int :rtype: int """ high = n low = 1 while(high>=low): mid = (low+high)//2 if isBadVersion(mid)== True: high = mid-1 else: low = mid+1 return low
first-bad-version
Python Solution
yashkumarjha
1
102
first bad version
278
0.43
Easy
4,986
https://leetcode.com/problems/first-bad-version/discuss/1952734/java-python-iterative-binary-search-(Time-Ologn-space-O1)
class Solution: def firstBadVersion(self, n: int) -> int: l = 1 while l <= n : m = (l + n)>>1 if isBadVersion(m) : n = m - 1 else : l = m + 1 return l
first-bad-version
java, python - iterative binary search (Time Ologn, space O1)
ZX007java
1
143
first bad version
278
0.43
Easy
4,987
https://leetcode.com/problems/first-bad-version/discuss/1621987/Python3-Another-solution-with-condition.-Beats-94.53
class Solution: def firstBadVersion(self, n): """ :type n: int :rtype: int """ left, right = 0, n if isBadVersion(1): return 1 while left < right: middle = (left + right) // 2 if isBadVersion(middle): right = middle else: left = middle + 1 return left
first-bad-version
[Python3] Another solution with condition. Beats 94.53%
Fyzzys
1
263
first bad version
278
0.43
Easy
4,988
https://leetcode.com/problems/first-bad-version/discuss/1378350/Easy-Python-O(log-n)-Solution-(Faster-than-99)
class Solution: def firstBadVersion(self, n): f = n l, h = 0, n+1 while l < h: m = l + (h-l)//2 if isBadVersion(m): if m < f: f = m h = m else: l = m+1 return f
first-bad-version
Easy Python O(log n) Solution (Faster than 99%)
the_sky_high
1
243
first bad version
278
0.43
Easy
4,989
https://leetcode.com/problems/first-bad-version/discuss/2842919/python-oror-simple-solution-oror-binary-search
class Solution: def firstBadVersion(self, n: int) -> int: # binary search l = 1 # left r = n # right while l <= r: m = (l + r) // 2 # mid if isBadVersion(m): r = m - 1 else: l = m + 1 return l
first-bad-version
python || simple solution || binary search
wduf
0
2
first bad version
278
0.43
Easy
4,990
https://leetcode.com/problems/first-bad-version/discuss/2830040/Python-Binary-Search-Beats-93-in-time-97-in-space
class Solution: def firstBadVersion(self, n: int) -> int: low = 1 high = n while True: mid = (low + high) // 2 if isBadVersion(mid): if not isBadVersion(mid - 1): return mid high = mid - 1 else: low = mid + 1
first-bad-version
Python Binary Search [Beats 93% in time, 97% in space]
satyam_mishra13
0
4
first bad version
278
0.43
Easy
4,991
https://leetcode.com/problems/first-bad-version/discuss/2765677/binary-searchpython-3
class Solution: def firstBadVersion(self, n: int) -> int: left = 1 while n >= left: mid = (n + left) // 2 if isBadVersion(mid) and not isBadVersion(mid-1): return mid elif not isBadVersion(mid) : left = mid + 1 else: n = mid -1
first-bad-version
[binary search][python 3]
Nyx24
0
3
first bad version
278
0.43
Easy
4,992
https://leetcode.com/problems/perfect-squares/discuss/376795/100-O(log-n)-Python3-Solution-Lagrange's-four-square-theorem
class Solution: def isSquare(self, n: int) -> bool: sq = int(math.sqrt(n)) return sq*sq == n def numSquares(self, n: int) -> int: # Lagrange's four-square theorem if self.isSquare(n): return 1 while (n &amp; 3) == 0: n >>= 2 if (n &amp; 7) == 7: return 4 sq = int(math.sqrt(n)) + 1 for i in range(1,sq): if self.isSquare(n - i*i): return 2 return 3
perfect-squares
100% O(log n) Python3 Solution - Lagrange’s four-square theorem
TCarmic
12
1,200
perfect squares
279
0.526
Medium
4,993
https://leetcode.com/problems/perfect-squares/discuss/1420219/Simple-Python-DP-or-BFS
class Solution: def numSquares(self, n: int) -> int: dp = [float("inf")]*(n+1) for i in range(len(dp)): if int(sqrt(i)) == sqrt(i): dp[i] = 1 else: for j in range(int(sqrt(i))+1): dp[i] = min(dp[i], dp[i-j*j]+1) return dp[-1]
perfect-squares
Simple Python DP or BFS
Charlesl0129
5
501
perfect squares
279
0.526
Medium
4,994
https://leetcode.com/problems/perfect-squares/discuss/622567/Python-sol-by-math.-90%2B-w-Comment
class Solution: def numSquares(self, n: int) -> int: while( n % 4 == 0 ): # Reduction by factor of 4 n //= 4 if n % 8 == 7: # Quick response for n = 8k + 7 return 4 # Check whether n = a^2 + b^2 for a in range( int(sqrt(n))+1 ): b = int( sqrt( n - a*a ) ) if ( a**2 + b ** 2 ) == n : return (a>0) + (b>0) # n = a^2 + b^2 + c^2 return 3
perfect-squares
Python sol by math. 90%+ [w/ Comment]
brianchiang_tw
5
793
perfect squares
279
0.526
Medium
4,995
https://leetcode.com/problems/perfect-squares/discuss/2491871/Python-Elegant-and-Short-or-Three-lines-or-91.28-faster-or-Top-down-DP-or-LRU-cache
class Solution: """ Time: O(n*√n) Memory: O(log(n)) """ def numSquares(self, n: int) -> int: return self._decompose(n) @classmethod @lru_cache(None) def _decompose(cls, n: int) -> int: if n < 2: return n return 1 + min(cls._decompose(n - i * i) for i in range(1, isqrt(n) + 1))
perfect-squares
Python Elegant & Short | Three lines | 91.28% faster | Top-down DP | LRU-cache
Kyrylo-Ktl
3
367
perfect squares
279
0.526
Medium
4,996
https://leetcode.com/problems/perfect-squares/discuss/1816739/Python-ll-iterative-BFS
class Solution: def numSquares(self, n): squares = [i * i for i in range(1, int(n**0.5)+1)] Q = set() Q.add((0,0)) while Q: newQ = set() for rank, vertex in Q: for sq in squares: if vertex+sq == n: return rank+1 newQ.add( (rank+1, vertex+sq) ) Q = newQ
perfect-squares
Python ll iterative BFS
morpheusdurden
2
220
perfect squares
279
0.526
Medium
4,997
https://leetcode.com/problems/perfect-squares/discuss/1031504/Solution-without-DP-and-with-comments-faster-than-99.74-Time-Complexity%3AO(n0.5)
class Solution: def numSquares(self, n: int) -> int: if int(sqrt(n))**2==n: #If number is perfect square----> return 1 return 1 while n%4==0: #From theorem, if number is of the form 4^a(8^b+1) , where a,b=non-negative integers, it is sun of four squares, hence return 4 n/=4 if n%8==7: return 4 perfect_squares=[i*i for i in range(1,int(sqrt(n))+1)] for i in perfect_squares: # If number is made of two perfect squares, we calculate the breakpoint and we see if its a perfect square or not!!! if int(sqrt(n-i))**2==n-i: return 2 return 3
perfect-squares
Solution without DP and with comments- faster than 99.74%, Time Complexity:O(n^0.5)
thisisakshat
2
329
perfect squares
279
0.526
Medium
4,998
https://leetcode.com/problems/perfect-squares/discuss/741367/Python-Recursive-DFS-and-BFS-Solutions-with-Comments!
class Solution: def numSquares(self, n: int) -> int: # Generate the squares, reverse to be in decreasing order for efficiency. sqrs = [i**2 for i in range(1, int(math.sqrt(n))+1)][::-1] mins = float('inf') def helper(t, nums, idx): nonlocal mins l = len(nums) # If the current nums we're using >= the min that lead to the target return. # If t < 0 or > n return. if l >= mins or t < 0 or t > n: return # If by this stage our t == 0 we store the l, this only gets update if l < mins. if t == 0: mins = l return else: # Recursively work through the sqrs. for i in range(idx, len(sqrs)): helper(t-sqrs[i], nums + [sqrs[i]], i) helper(n, [], 0) return mins if mins != float('inf') else -1
perfect-squares
Python Recursive DFS and BFS Solutions with Comments!
Pythagoras_the_3rd
2
550
perfect squares
279
0.526
Medium
4,999