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/bitwise-and-of-numbers-range/discuss/1513669/For-Beginners-oror-Well-Explained-oror-94-faster | class Solution:
def rangeBitwiseAnd(self, left: int, right: int) -> int:
k = 0
while left!=right:
left>>=1
right>>=1
k+=1
return left<<k | bitwise-and-of-numbers-range | ๐๐ For-Beginners || Well-Explained || 94% faster ๐ | abhi9Rai | -1 | 114 | bitwise and of numbers range | 201 | 0.423 | Medium | 3,300 |
https://leetcode.com/problems/happy-number/discuss/2383810/Very-Easy-0-ms-100(Fully-Explained)(C%2B%2B-Java-Python-JS-C-Python3) | class Solution(object):
def isHappy(self, n):
hset = set()
while n != 1:
if n in hset: return False
hset.add(n)
n = sum([int(i) ** 2 for i in str(n)])
else:
return True | happy-number | Very Easy 0 ms 100%(Fully Explained)(C++, Java, Python, JS, C, Python3) | PratikSen07 | 18 | 1,700 | happy number | 202 | 0.545 | Easy | 3,301 |
https://leetcode.com/problems/happy-number/discuss/2383810/Very-Easy-0-ms-100(Fully-Explained)(C%2B%2B-Java-Python-JS-C-Python3) | class Solution:
def isHappy(self, n: int) -> bool:
hset = set()
while n != 1:
if n in hset: return False
hset.add(n)
n = sum([int(i) ** 2 for i in str(n)])
else:
return True | happy-number | Very Easy 0 ms 100%(Fully Explained)(C++, Java, Python, JS, C, Python3) | PratikSen07 | 18 | 1,700 | happy number | 202 | 0.545 | Easy | 3,302 |
https://leetcode.com/problems/happy-number/discuss/1422398/Python-oror-Easy-Solution-oror-beat-~-95 | class Solution:
def isHappy(self, n: int) -> bool:
if n == 1:
return True
s = set()
s.add(n)
while True:
count = 0
for i in str(n):
count += int(i) ** 2
if count == 1:
return True
if count in s:
break
s.add(count)
n = count
return False | happy-number | Python || Easy Solution || beat ~ 95% | naveenrathore | 9 | 580 | happy number | 202 | 0.545 | Easy | 3,303 |
https://leetcode.com/problems/happy-number/discuss/1001494/Easy-Python-Solution | class Solution:
def isHappy(self, n: int) -> bool:
if n == 1: return True
l = []
def calculate(n):
c = 0
for i in str(n):
c += int(i) ** 2
return c
while n != 1:
n = calculate(n)
if n in l:
return False
l.append(n)
return True | happy-number | Easy Python Solution | vanigupta20024 | 8 | 1,100 | happy number | 202 | 0.545 | Easy | 3,304 |
https://leetcode.com/problems/happy-number/discuss/1085061/Easy-and-Quick-to-understand-in-python3-Took-me-1-Hr-to-construct-the-logic | class Solution:
def isHappy(self, n: int) -> bool:
if n == 1:
return True
seen = {}
while n != 1:
sqa_summed = sum([(int(i) ** 2) for i in str(n)])
if sqa_summed not in seen:
seen[sqa_summed] = sqa_summed
n = sqa_summed
else:
return False
return True | happy-number | Easy and Quick to understand in python3 - Took me 1 Hr to construct the logic | user3912v | 7 | 616 | happy number | 202 | 0.545 | Easy | 3,305 |
https://leetcode.com/problems/happy-number/discuss/2793331/PYTHON-easiest-with-comments | class Solution:
def isHappy(self, n: int) -> bool:
set_of_no=set()
while n!=1:
n=sum([int(i)**2 for i in str(n)]) #squaring the digits of no
if n in set_of_no: #checking whether the no is present in set_of_no
return False #if present that means it will repeat the terms(or in endless loop)
set_of_no.add(n) #if not present add it to set
return True | happy-number | [PYTHON]-\ \-easiest -\ \- with comments | user9516zM | 6 | 617 | happy number | 202 | 0.545 | Easy | 3,306 |
https://leetcode.com/problems/happy-number/discuss/1323085/Python-3-or-Simple-Solution | class Solution:
def isHappy(self, n: int) -> bool:
seen=[]
while n not in seen:
seen.append(n)
n = sum([int(x)**2 for x in str(n)])
if n==1:
return True
return False | happy-number | Python 3 | Simple Solution | nishikantsinha | 4 | 255 | happy number | 202 | 0.545 | Easy | 3,307 |
https://leetcode.com/problems/happy-number/discuss/1091808/Python-or-Two-pointers-or-O(N)-Time-or-O(1)-Space | class Solution:
def isHappy(self, n: int) -> bool:
def sum_of_squares(num):
_sum = 0
while num > 0:
rem = num%10
_sum += rem*rem
num //= 10
return _sum
fast, slow = n, n
while True:
slow = sum_of_squares(slow)
fast = sum_of_squares(sum_of_squares(fast))
if slow == fast:
break
return slow == 1 | happy-number | Python | Two pointers | O(N) Time | O(1) Space | Rakesh301 | 4 | 442 | happy number | 202 | 0.545 | Easy | 3,308 |
https://leetcode.com/problems/happy-number/discuss/1372684/Python%3A-Approach-1-explanation | class Solution:
def isHappy(self, n: int) -> bool:
# GIVEN NUMBER 'n' -> WHAT IS THE NEXT NUMBER?
def get_next(n):
# reset sum value
total_sum = 0
# 0 = null
while n > 0:
# divmod(dividend/divisor) -> returns (quotient,remainder)
# ((n/10),(n%10))
n, digit = divmod(n, 10)
# n = quotient
# digit = remainder
# only sqauring remainder until it becomes '1'
total_sum += digit ** 2
return total_sum
seen = set()
while n != 1 and n not in seen:
# will add last round of '1' or already parsed value
# next round will then clean it out
seen.add(n)
n = get_next(n)
return n ==1 | happy-number | Python: Approach 1 explanation | bdanny | 3 | 241 | happy number | 202 | 0.545 | Easy | 3,309 |
https://leetcode.com/problems/happy-number/discuss/2344743/Python-Easy-Two-Line-Solution | class Solution:
def isHappy(self, n: int) -> bool:
while n > 5: n = sum((int(i))**2 for i in str(n))
return True if n==1 else False | happy-number | Python Easy Two Line Solution | warrensteel7 | 2 | 232 | happy number | 202 | 0.545 | Easy | 3,310 |
https://leetcode.com/problems/happy-number/discuss/2195074/Easy-python-solution | class Solution:
def isHappy(self, n: int) -> bool:
curr = n
s = set()
while curr not in s:
s.add(curr)
string = str(curr)
acc = 0
for char in string:
acc += int(char) ** 2
if acc == 1:
return True
curr = acc
return False | happy-number | Easy python solution | knishiji | 2 | 159 | happy number | 202 | 0.545 | Easy | 3,311 |
https://leetcode.com/problems/happy-number/discuss/381832/Python-solutions-using-set-and-Floyd | class Solution:
def isHappy(self, n: int) -> bool:
cache = set()
while n not in cache:
cache.add(n)
tmp = 0
while n:
n, remainder = divmod(n, 10)
tmp += remainder**2
if tmp == 1:
return True
n = tmp
return False | happy-number | Python solutions using set and Floyd | amchoukir | 2 | 327 | happy number | 202 | 0.545 | Easy | 3,312 |
https://leetcode.com/problems/happy-number/discuss/381832/Python-solutions-using-set-and-Floyd | class Solution:
def square_digit(self, n):
tmp = 0
while n:
n, remainder = divmod(n, 10)
tmp += remainder**2
return tmp
def isHappy(self, n: int) -> bool:
slow , fast = n, self.square_digit(n)
while slow != fast:
slow = self.square_digit(slow)
fast = self.square_digit(fast)
fast = self.square_digit(fast)
return fast == 1 | happy-number | Python solutions using set and Floyd | amchoukir | 2 | 327 | happy number | 202 | 0.545 | Easy | 3,313 |
https://leetcode.com/problems/happy-number/discuss/2433174/Python-easy-solution-for-beginners-using-sets | class Solution:
def isHappy(self, n: int) -> bool:
seen = set()
while True:
n = sum([int(x)**2 for x in str(n)])
if n in seen:
return False
seen.add(n)
if n == 1:
return True | happy-number | Python easy solution for beginners using sets | alishak1999 | 1 | 156 | happy number | 202 | 0.545 | Easy | 3,314 |
https://leetcode.com/problems/happy-number/discuss/2086250/Python3-O(LogN)-O(1)-space | class Solution:
def isHappy(self, n: int) -> bool:
return self.solOne(n)
return self.solTwo(n)
# O(logN) || O(1) 51ms 42.35%
def solOne(self, n):
while n not in [1, 4]:
n = sum(pow(int(i), 2) for i in str(n))
return n == 1
# O(logn) || O(1) 55ms 33.44%
def solTwo(self, n):
while n not in [1, 4]:
n = self.splitHelper(n)
return n == 1
def splitHelper(self, n):
square = 0
while n > 0:
square += pow(n % 10, 2)
n //= 10
return square | happy-number | Python3 O(LogN) O(1) space | arshergon | 1 | 173 | happy number | 202 | 0.545 | Easy | 3,315 |
https://leetcode.com/problems/happy-number/discuss/2049009/Python-Walrus-Operator-*Very-Interesting-Solution* | class Solution:
def isHappy(self, n: int) -> bool:
hmap = []
while (n := sum(int(num)**2 for num in str(n))) not in hmap:
hmap.append(n)
if n == 1: return True
return False | happy-number | Python Walrus Operator *Very Interesting Solution* | kedeman | 1 | 64 | happy number | 202 | 0.545 | Easy | 3,316 |
https://leetcode.com/problems/happy-number/discuss/1760095/Python3-or-I-don't-know-how-it-worked-or-if-you've-any-idea-please-explain. | class Solution:
def isHappy(self, n: int) -> bool:
b=[]
for i in range(7):
if n==1:
return True
a=list(str(n))
n=sum(pow(int(i),2) for i in a)
b.append(n)
if len(set(b))!=len(b):
return False | happy-number | โPython3 | I don't know how it worked ๐ | if you've any idea, please explain. | Anilchouhan181 | 1 | 330 | happy number | 202 | 0.545 | Easy | 3,317 |
https://leetcode.com/problems/happy-number/discuss/1588215/Python-Easy-Solution-or-O(logn)-Time | class Solution:
def isHappy(self, n: int) -> bool:
# Time and Space: O(logn), O(logn)
def sumi(n):
res = 0
while n:
res += (n % 10)**2
n //= 10
return res
res = set()
while n != 1 and n not in res:
res.add(n)
n = sumi(n)
return n == 1 | happy-number | Python Easy Solution | O(logn) Time | leet_satyam | 1 | 381 | happy number | 202 | 0.545 | Easy | 3,318 |
https://leetcode.com/problems/happy-number/discuss/1490028/Compact-python-solution | class Solution:
def isHappy(self, n: int) -> bool:
numset = {n}
while True:
n = sum([int(x) ** 2 for x in str(n)])
if n == 1:
return True
if n in numset:
return False
numset.add(n) | happy-number | Compact python solution | Skaiir | 1 | 155 | happy number | 202 | 0.545 | Easy | 3,319 |
https://leetcode.com/problems/happy-number/discuss/1454758/Easy-Python-Solution | class Solution:
def isHappy(self, n: int) -> bool:
visited = []
while True:
total = 0
while n != 0:
num = n % 10
total = total + num**2
n = n // 10
n = total
if total in visited:
return False
elif total == 1:
return True
visited.append(total) | happy-number | Easy Python Solution | farhan_kapadia | 1 | 281 | happy number | 202 | 0.545 | Easy | 3,320 |
https://leetcode.com/problems/happy-number/discuss/1326898/Simple-Python-Soln-for-Happy-Number | class Solution:
def isHappy(self, n: int) -> bool:
def func(num):
rem = sum = 0;
#Calculates the sum of squares of digits
while(num > 0):
rem = num%10;
sum = sum + (rem*rem);
num = num//10;
return sum;
result = n;
while(result != 1 and result != 4):
result = func(result);
#Happy number always ends with 1
if(result == 1):
return True
#Unhappy number ends in a cycle of repeating numbers which contain 4
elif(result == 4):
return False | happy-number | Simple Python Soln for Happy Number | sakshikhandare2527 | 1 | 353 | happy number | 202 | 0.545 | Easy | 3,321 |
https://leetcode.com/problems/happy-number/discuss/1242882/Easy-Math-oror-Python-Clean-Recursive | class Solution:
def help(self,n):
s =0
r = 0
while n!=0:
r = n%10
s += r*r
n = n//10
return s
def isHappy(self, n: int) -> bool:
while True:
if(self.help(n) == 1):
return True
n = self.help(n)
if n < 10 and n!= 7:
return False | happy-number | Easy Math || Python Clean Recursive | suvoo | 1 | 239 | happy number | 202 | 0.545 | Easy | 3,322 |
https://leetcode.com/problems/happy-number/discuss/977802/Python-solution-maximum-8-operations | class Solution:
def isHappy(self, n: int) -> bool:
counter = 0
while counter <= 8:
counter += 1
digits = []
while n:
digits.append(n % 10)
n = n // 10
n = sum([digit ** 2 for digit in digits])
if n == 1:
return True
return False | happy-number | Python solution - maximum 8 operations | r_tokashev | 1 | 201 | happy number | 202 | 0.545 | Easy | 3,323 |
https://leetcode.com/problems/happy-number/discuss/811205/Using-while-loops | class Solution:
def isHappy(self, n: int) -> bool:
k=0
while n!=1 and k<6:
l=[int(x)**2 for x in str(n)]
k+=1
n=sum(l)
return True if n==1 else False | happy-number | Using while loops | thisisakshat | 1 | 177 | happy number | 202 | 0.545 | Easy | 3,324 |
https://leetcode.com/problems/happy-number/discuss/493842/Python-sol.-by-pattern-and-cycle-detection.-90%2B-With-explanation | class Solution:
def digit_sum(self, n:int) -> int:
sum_digit_square = 0
while n > 0:
digit = n % 10
sum_digit_square += int( digit ** 2 )
n = n // 10
return sum_digit_square
# non-happy number will fall in dead cycle somewhere:
# (4, 16, 37, 58, 89, 145, 42, 20 ,4 , ...)
def isHappy(self, n: int) -> bool:
cur = n
while True:
cur = self.digit_sum( cur )
if cur == 1:
# stop condition for happy number:
return True
if cur in (4, 20, 37, 89):
# prune and early return for non-happy number
return False | happy-number | Python sol. by pattern and cycle detection. 90%+ [ With explanation ] | brianchiang_tw | 1 | 512 | happy number | 202 | 0.545 | Easy | 3,325 |
https://leetcode.com/problems/happy-number/discuss/493842/Python-sol.-by-pattern-and-cycle-detection.-90%2B-With-explanation | class Solution:
def digit_sum(self, n:int) -> int:
sum_digit_square = 0
while n > 0:
digit = n % 10
sum_digit_square += int( digit ** 2 )
n = n // 10
return sum_digit_square
def isHappy(self, n: int) -> bool:
slow, fast = n, n
while True:
slow = self.digit_sum( slow )
fast = self.digit_sum( fast )
fast = self.digit_sum( fast )
if slow == 1 or fast == 1:
# happy number
return True
if slow == fast:
# non-happy number, fall in dead cycle.
return False | happy-number | Python sol. by pattern and cycle detection. 90%+ [ With explanation ] | brianchiang_tw | 1 | 512 | happy number | 202 | 0.545 | Easy | 3,326 |
https://leetcode.com/problems/happy-number/discuss/2843453/Very-Easy-Beginner-Level-Solution-without-using-sum() | class Solution:
def isHappy(self, n: int) -> bool:
count = 0
while n!=1 and count<50:
d = []
n = str(n)
k = [int(i) for i in n]
sum = 0
for i in range(len(k)):
c = k[i] ** 2
d.append(c)
for j in range(len(d)):
sum += d[j]
n = sum
count+=1
if n == 1:
return True
else:
return False | happy-number | Very Easy Beginner Level Solution - without using sum() | bharatvishwa | 0 | 2 | happy number | 202 | 0.545 | Easy | 3,327 |
https://leetcode.com/problems/happy-number/discuss/2831431/python-oror-simple-solution-oror-recursion-%2B-memoization | class Solution:
def isHappy(self, n: int) -> bool:
def f(n: int, d: dict) -> bool:
# if we've been here already, it's an infinite loop
if n in d:
return False
# else add it to d
else:
d[n] = True
ans = 0
k = 1 # denominator to get each digit in n
# for every digit in n
while k <= n:
x = (n // k) % 10 # cur digit
# add cur digit squared
ans += x ** 2
# next digit
k *= 10
# if ans equals 1, true, else run again on ans
return True if ans == 1 else f(ans, d)
return f(n, {}) | happy-number | python || simple solution || recursion + memoization | wduf | 0 | 4 | happy number | 202 | 0.545 | Easy | 3,328 |
https://leetcode.com/problems/happy-number/discuss/2830956/Python3-or-Single-Pass-w-(End-on-True-or-Duplicate) | class Solution:
def isHappy(self, n: int) -> bool:
def getVal(m):
val = 0
mstr = "" + str(m)
for s in mstr:
val += pow(int(s),2)
return val
dct = {}
val = n
while val not in dct:
if val == 1:
return True
else:
dct[val] = -1
val = getVal(val)
return False | happy-number | Python3 | Single Pass w/ (End on True or Duplicate) | vmb004 | 0 | 2 | happy number | 202 | 0.545 | Easy | 3,329 |
https://leetcode.com/problems/happy-number/discuss/2827725/easy-to-understand | class Solution:
def isHappy(self, n: int, s = None) -> bool:
s = 0
while n != 0 :
s += (n % 10)**2
n //= 10
n = s
if len(str(n)) == 1 and n != 1 and n!=7:
return False
elif n == 1 or n == 7:
return True
return self.isHappy(n, s) | happy-number | easy to understand | bladdeee | 0 | 3 | happy number | 202 | 0.545 | Easy | 3,330 |
https://leetcode.com/problems/happy-number/discuss/2825765/Python-Solution-Using-Set | class Solution:
def isHappy(self, n: int) -> bool:
results = set()
while n != 1:
s = str(n)
n=0
for c in s:
n += int(c) ** 2
print(n)
if n in results:
return False
results.add(n)
return True | happy-number | Python Solution Using Set | dmccormick | 0 | 3 | happy number | 202 | 0.545 | Easy | 3,331 |
https://leetcode.com/problems/happy-number/discuss/2817181/Simple-Solution-with-Mathmatical-Theory | class Solution:
def isHappy(self, n: int) -> bool:
result = []
while True:
temp = 0
for i in range(len(str(n))):
j = n % 10
n = n // 10
#print(j, n)
temp += int(pow(j,2))
n = int(temp)
if(n in result):
return False
result.append(n)
print(n)
if(n==1):
return True | happy-number | Simple Solution with Mathmatical Theory | zning1994 | 0 | 4 | happy number | 202 | 0.545 | Easy | 3,332 |
https://leetcode.com/problems/happy-number/discuss/2815508/Beats-95-Python | class Solution:
def isHappy(self, n: int) -> bool:
st = str(n)
lst = list()
lgc = True
while lgc:
hap = 0
for c in st:
hap += int(c)*int(c)
if hap == 1:
return True
break
else:
strhap = str(hap)
lgc = strhap not in lst
st = strhap
if not lgc:
return False
break
lst.append(strhap) | happy-number | Beats 95% - Python | alishahamiri | 0 | 7 | happy number | 202 | 0.545 | Easy | 3,333 |
https://leetcode.com/problems/happy-number/discuss/2815464/Python-BFS | class Solution:
def isHappy(self, n: int) -> bool:
st = list(str(n))
lst = list()
lgc = True
while lgc:
hap = 0
for c in st:
hap += int(c)*int(c)
if hap == 1:
return True
break
else:
strhap = str(hap)
lgc = strhap not in lst
st = list(strhap)
if not lgc:
return False
break
lst.append(strhap) | happy-number | Python - BFS | alishahamiri | 0 | 2 | happy number | 202 | 0.545 | Easy | 3,334 |
https://leetcode.com/problems/happy-number/discuss/2814080/Python-Simple-and-clean-solution | class Solution:
def isHappy(self, n: int) -> bool:
seen = set()
while n not in seen:
seen.add(n)
n = sum([int(val)**2 for val in str(n)])
return 1 in seen | happy-number | [Python] Simple & clean solution | qtBlonded | 0 | 3 | happy number | 202 | 0.545 | Easy | 3,335 |
https://leetcode.com/problems/happy-number/discuss/2813208/Easy-Understanding-Python-Code | class Solution:
def isHappy(self, n: int) -> bool:
def checker(n):
res = 0
for i in str(n):
res += (int(i)) ** 2
return res
dp = set()
while(n != 1):
n = checker(n)
if(n in dp):
return False
dp.add(n)
# print(n)
return True | happy-number | Easy Understanding Python Code | abh1jith | 0 | 4 | happy number | 202 | 0.545 | Easy | 3,336 |
https://leetcode.com/problems/happy-number/discuss/2807973/Different-approach-for-where-to-stop-the-recursion-**naive-approach | class Solution:
def isHappy(self, n: int) -> bool:
def sendHappiness(n,c):
print(n,c)
if c>100:
return False
if n==1:
return True
arr=[i for i in str(n)]
sum=0
for i in arr:
sum+=pow(int(i),2)
return sendHappiness(sum,c+1)
return(sendHappiness(n,0)) | happy-number | Different approach for where to stop the recursion **naive approach | anmolsahu9906 | 0 | 2 | happy number | 202 | 0.545 | Easy | 3,337 |
https://leetcode.com/problems/happy-number/discuss/2806916/Python-Short-recursion-solution | class Solution:
def isHappy(self, n: int) -> bool:
visited = set()
@cache
def dfs(n):
if n == 1: return True
sum_square = sum(int(x) ** 2 for x in str(n))
if n in visited: return False
visited.add(n)
return dfs(sum_square)
return dfs(n) | happy-number | [Python] Short recursion solution | Nezuko-NoBamboo | 0 | 4 | happy number | 202 | 0.545 | Easy | 3,338 |
https://leetcode.com/problems/happy-number/discuss/2805974/Easy-approach-using-python | class Solution:
def isHappy(self, n: int) -> bool:
sum = 0
temp_number = n
while (temp_number>0):
sum= sum+((temp_number%10)**2)
temp_number = temp_number//10
if sum == 1 and temp_number == 0:
return True
if sum == 89:
return False
if temp_number == 0:
temp_number = sum
sum = 0 | happy-number | Easy approach using python | user8539if | 0 | 1 | happy number | 202 | 0.545 | Easy | 3,339 |
https://leetcode.com/problems/happy-number/discuss/2797730/simple-solution | class Solution:
def isHappy(self, n: int) -> bool:
string_n=str(n)
rep=0
while rep<100:
result_sum=0
for i in string_n:
result_sum+=int(i)**2
string_n=str(result_sum)
if string_n=='1':
return True
rep+=1
return False | happy-number | simple solution | althrun | 0 | 2 | happy number | 202 | 0.545 | Easy | 3,340 |
https://leetcode.com/problems/happy-number/discuss/2787846/Python-Compact-solution. | class Solution:
def isHappy(self, n: int) -> bool:
while True:
sqList = list(map(self.squareStr, str(n)))
n = sum(sqList)
if n // 10 == 0:
if n in {1, 7}:
return True
else:
return False
def squareStr(self, x: str) -> int:
return int(x) ** 2 | happy-number | Python Compact solution. | raghupalash | 0 | 3 | happy number | 202 | 0.545 | Easy | 3,341 |
https://leetcode.com/problems/happy-number/discuss/2781049/memory-beats-98-users | class Solution:
def isHappy(self, n: int) -> bool:
visited = []
while n != 1:
sum = 0
n = str(n)
for i in range(len(n)):
sum+= int(n[i])**2
n = sum
if n not in visited:
visited.append(n)
print(n, visited)
else:
return False
return True | happy-number | memory beats 98% users | MayuD | 0 | 3 | happy number | 202 | 0.545 | Easy | 3,342 |
https://leetcode.com/problems/happy-number/discuss/2776940/Python-easy-to-understand-solution | class Solution:
def isHappy(self, n: int) -> bool:
visited = set()
while n not in visited:
visited.add(n) # add n to the visited list of numbers
# calculate the squared sum
squared_sum = 0
while n > 0:
squared_sum += (n%10)**2
n //= 10
if squared_sum == 1: # happy number case
return True
n = squared_sum
return False | happy-number | Python easy to understand solution | remenraj | 0 | 2 | happy number | 202 | 0.545 | Easy | 3,343 |
https://leetcode.com/problems/happy-number/discuss/2769988/Python-simple-straightforward-solution | class Solution:
def isHappy(self, n: int) -> bool:
previous = set()
while n != 1:
n = sum([int(d) ** 2 for d in str(n)])
if n in previous:
return False
previous.add(n)
return True | happy-number | Python simple straightforward solution | meatcodex | 0 | 6 | happy number | 202 | 0.545 | Easy | 3,344 |
https://leetcode.com/problems/happy-number/discuss/2767424/okay-solution | class Solution:
def isHappy(self, n: int) -> bool:
s = False
c=0
t=0
while c !=1:
a = list(map(int, list(str(n))))
b = sum([i**2 for i in a])
c = sum(list(map(int, list(str(b)))))
n = b
t+=1
if c==1:
s = True
elif t==20:
break
return s | happy-number | okay solution | yanivalon512 | 0 | 3 | happy number | 202 | 0.545 | Easy | 3,345 |
https://leetcode.com/problems/happy-number/discuss/2766264/Python3%3A-Easy-Hashmap-Approach | class Solution:
def isHappy(self, n: int) -> bool:
# Maintain the additions we have done, so we know when the loop goes infinite
duplicate = {}
# Use recursion: calculate sum of digits, add to duplicates map, and re-call the method
def check(n: int) -> bool:
if n == 1:
# we return true -> since it is a happy number
return True
# Find the digits. Note: order in the list does not matter here.
res = []
while n > 0:
w = n%10
res.append(w)
n = n//10
# Since we have the digits now, add the digits
add = 0
for num in res:
add += num**2
# Return False if sum in duplicate map, or re-call the method with new sum
if add in duplicate:
# Loop detected
return False
else:
duplicate[add] = 0
return check(add)
# calling the main method
return check(n) | happy-number | Python3: Easy Hashmap Approach | sourav_ravish | 0 | 8 | happy number | 202 | 0.545 | Easy | 3,346 |
https://leetcode.com/problems/happy-number/discuss/2764743/Python3-or-Faster-than-98.23 | class Solution:
def isHappy(self, n: int) -> bool:
obs = {}
while True:
obs[n] = None
digits = [int(x) for x in str(n)]
digits_squared = [pow(d, 2) for d in digits]
n = sum(digits_squared)
if n == 1:
return True
if n in obs:
return False | happy-number | Python3 | Faster than 98.23% | thomwebb | 0 | 8 | happy number | 202 | 0.545 | Easy | 3,347 |
https://leetcode.com/problems/happy-number/discuss/2757152/easy-approach!! | class Solution:
def isHappy(self, n: int) -> bool:
while n != 1:
n = sum([int(i) ** 2 for i in str(n)])
if n == 4:
return False
return True | happy-number | easy approach!! | sanjeevpathak | 0 | 3 | happy number | 202 | 0.545 | Easy | 3,348 |
https://leetcode.com/problems/remove-linked-list-elements/discuss/158651/Simple-Python-solution-with-explanation-(single-pointer-dummy-head). | class Solution:
def removeElements(self, head, val):
"""
:type head: ListNode
:type val: int
:rtype: ListNode
"""
dummy_head = ListNode(-1)
dummy_head.next = head
current_node = dummy_head
while current_node.next != None:
if current_node.next.val == val:
current_node.next = current_node.next.next
else:
current_node = current_node.next
return dummy_head.next | remove-linked-list-elements | Simple Python solution with explanation (single pointer, dummy head). | Hai_dee | 429 | 28,900 | remove linked list elements | 203 | 0.449 | Easy | 3,349 |
https://leetcode.com/problems/remove-linked-list-elements/discuss/1572935/Python-99-One-pass-Solution-with-Explanation | class Solution:
def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]:
prev, curr = None, head
while curr:
if curr.val == val: # cases 1-3
if prev: # cases 1-2
prev.next = curr.next
else: # case 3
head = curr.next
curr = curr.next # for all cases
else: # case 4
prev, curr = curr, curr.next
return head | remove-linked-list-elements | [Python] 99% One-pass Solution with Explanation | zayne-siew | 41 | 1,800 | remove linked list elements | 203 | 0.449 | Easy | 3,350 |
https://leetcode.com/problems/remove-linked-list-elements/discuss/2454737/Very-Easy-oror-0-ms-oror-100-oror-Fully-Explained-(Java-C%2B%2B-Python-JS-C-Python3) | class Solution(object):
def removeElements(self, head, val):
# create a fake node that acts like a fake head of list pointing to the original head and it points to the original head...
fake = ListNode(None)
fake.next = head
curr = fake
# Loop till curr.next not null...
while curr.next:
# if we find the target val same as the value of curr.next...
if curr.next.val == val:
# Skip that value and keep updating curr...
curr.next = curr.next.next
# Otherwise, move curr forward...
else:
curr = curr.next
# Return the linked list...
return fake.next | remove-linked-list-elements | Very Easy || 0 ms || 100% || Fully Explained (Java, C++, Python, JS, C, Python3) | PratikSen07 | 7 | 706 | remove linked list elements | 203 | 0.449 | Easy | 3,351 |
https://leetcode.com/problems/remove-linked-list-elements/discuss/2454737/Very-Easy-oror-0-ms-oror-100-oror-Fully-Explained-(Java-C%2B%2B-Python-JS-C-Python3) | class Solution:
def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]:
# create a fake node that acts like a fake head of list pointing to the original head and it points to the original head...
fake = ListNode(None)
fake.next = head
curr = fake
# Loop till curr.next not null...
while curr.next:
# if we find the target val same as the value of curr.next...
if curr.next.val == val:
# Skip that value and keep updating curr...
curr.next = curr.next.next
# Otherwise, move curr forward...
else:
curr = curr.next
# Return the linked list...
return fake.next | remove-linked-list-elements | Very Easy || 0 ms || 100% || Fully Explained (Java, C++, Python, JS, C, Python3) | PratikSen07 | 7 | 706 | remove linked list elements | 203 | 0.449 | Easy | 3,352 |
https://leetcode.com/problems/remove-linked-list-elements/discuss/2248711/Python-Dummy-Node-Solution-Explained-Time-O(N)-or-Space-O(1) | class Solution:
def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]:
dummyNode = ListNode()
dummyNode.next = head
prev = dummyNode
current = head
while current:
if current.val == val:
prev.next = current.next
else:
prev = current
current = current.next
return dummyNode.next | remove-linked-list-elements | [Python] Dummy Node Solution Explained - Time O(N) | Space O(1) | Symbolistic | 5 | 231 | remove linked list elements | 203 | 0.449 | Easy | 3,353 |
https://leetcode.com/problems/remove-linked-list-elements/discuss/2158854/Python3-solution-using-two-pointers-approach | class Solution:
def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]:
dummy = ListNode(-1, None)
dummy.next = head
prev = dummy
curr = dummy.next
while curr:
if(curr.val == val):
prev.next = curr.next
else:
prev = curr
curr = curr.next if curr else None
return dummy.next | remove-linked-list-elements | ๐ Python3 solution using two pointers approach | Dark_wolf_jss | 4 | 44 | remove linked list elements | 203 | 0.449 | Easy | 3,354 |
https://leetcode.com/problems/remove-linked-list-elements/discuss/1161918/Python3-Iterative-solution-using-dummy-head-(with-explanation) | class Solution:
def removeElements(self, head: ListNode, val: int) -> ListNode:
# dummy_head.next is the first node of list
dummy_head = ListNode(next=head)
prev, cur = dummy_head, head
while cur:
if cur.val == val:
prev.next = cur.next
cur = cur.next
else:
prev, cur = cur, cur.next
return dummy_head.next | remove-linked-list-elements | [Python3] Iterative solution using dummy head (with explanation) | EckoTan0804 | 4 | 166 | remove linked list elements | 203 | 0.449 | Easy | 3,355 |
https://leetcode.com/problems/remove-linked-list-elements/discuss/1387149/Python3-99-One-Pass-O(1)-Memory | class Solution:
def removeElements(self, head: ListNode, val: int) -> ListNode:
prev = None
curr = head
while curr:
if curr.val != val:
prev = curr
else:
if prev:
prev.next = curr.next
else:
head = curr.next
curr = curr.next
return head | remove-linked-list-elements | [Python3] 99% One Pass O(1) Memory | whitehatbuds | 3 | 472 | remove linked list elements | 203 | 0.449 | Easy | 3,356 |
https://leetcode.com/problems/remove-linked-list-elements/discuss/1369093/Simple-Python-Recursion | class Solution:
def removeElements(self, head: ListNode, val: int) -> ListNode:
if not head:
return head
head.next = self.removeElements(head.next, val)
if head.val == val:
head = head.next
return head | remove-linked-list-elements | Simple Python Recursion | frankjzy | 3 | 282 | remove linked list elements | 203 | 0.449 | Easy | 3,357 |
https://leetcode.com/problems/remove-linked-list-elements/discuss/2157679/Easy-Python-Solution-Without-New-Node-(Without-Sentinel-Node)-203.-Remove-Linked-List-Elements | class Solution:
def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]:
prev = None
curr = head
while curr is not None:
if(curr.val == val):
if(curr == head):
head = head.next
curr = head
else:
nextNode = curr.next
prev.next = nextNode
curr = nextNode
else:
prev = curr
curr = curr.next
return head | remove-linked-list-elements | Easy Python Solution Without New Node (Without Sentinel Node) 203. Remove Linked List Elements | pradeep_rvv | 2 | 210 | remove linked list elements | 203 | 0.449 | Easy | 3,358 |
https://leetcode.com/problems/remove-linked-list-elements/discuss/1920646/Beats-82.58-oror-Python-oror-Full-explanation-oror-Clear-and-concise-oror-Iterative | class Solution:
def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]:
if head == None: #if no element in the linklist (i.e. head = [], val = 1)
return head
elif head.next == None and head.val == val: #if only one element in the list and head's value is equal to gievn value (i.e. head = [1], val = 1)
head = None
return head
while head != None and head.val == val: #while head is not None and head's value is equal to given value
#(i.e. head = [7,7,7,7] and val= 7)
head = head.next
else:
ptr = head #ptr points head of the linklsit
q = ptr #q points ptr
while ptr != None: #this while loop iterates all the values in the linklist
if ptr.val == val: #if condition checks for all the given values if ptr.value(current value) is equal to given value
q.next = ptr.next
else:
q = ptr
ptr = ptr.next
return head | remove-linked-list-elements | โ
Beats 82.58% || Python || Full explanation || Clear and concise || Iterative | Dev_Kesarwani | 2 | 120 | remove linked list elements | 203 | 0.449 | Easy | 3,359 |
https://leetcode.com/problems/remove-linked-list-elements/discuss/1758202/Python-or-90-Faster | class Solution:
def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]:
dmnode=ListNode(0)
dmnode.next=head
curr = dmnode
while curr.next!=None:
if curr.next.val == val:
curr.next=curr.next.next
else:
curr=curr.next
return dmnode.next | remove-linked-list-elements | โ Python | 90% Faster | Anilchouhan181 | 2 | 282 | remove linked list elements | 203 | 0.449 | Easy | 3,360 |
https://leetcode.com/problems/remove-linked-list-elements/discuss/2255931/95-PYTHON-SENTINEL | class Solution:
def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]:
# Pop off head nodes while val to remove
while head and head.val == val:
head = head.next
# Use head as sentinel
prev,cur = head,head
while cur:
if cur.val == val:
prev.next = cur.next
else:
prev = cur
cur = cur.next
return head | remove-linked-list-elements | ๐ 95% PYTHON SENTINEL | drblessing | 1 | 266 | remove linked list elements | 203 | 0.449 | Easy | 3,361 |
https://leetcode.com/problems/remove-linked-list-elements/discuss/2107413/Python-Simple-readable-easy-to-understand-iterative-solution-(beats-95) | class Solution:
def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]:
result = None
while head:
if not result and head.val != val:
result = head
if head.next and head.next.val == val:
head.next = head.next.next
else:
head = head.next
return result | remove-linked-list-elements | [Python] Simple, readable, easy to understand, iterative solution (beats 95%) | FedMartinez | 1 | 228 | remove linked list elements | 203 | 0.449 | Easy | 3,362 |
https://leetcode.com/problems/remove-linked-list-elements/discuss/2072243/Python3-oror-faster-60.05-oror-memory-91.67 | class Solution:
def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]:
# root = tmp = ListNode(None, head)
# while tmp and tmp.next:
# if tmp.next.val == val:
# tmp.next = tmp.next.next
# else:
# tmp = tmp.next
# return root.next
root = prev = ListNode(None, head)
cur = head
while cur:
if cur.val == val:
prev.next = cur = cur.next
else:
prev, cur = cur, cur.next
return root.next | remove-linked-list-elements | Python3 || faster 60.05% || memory 91.67% | grivabo | 1 | 88 | remove linked list elements | 203 | 0.449 | Easy | 3,363 |
https://leetcode.com/problems/remove-linked-list-elements/discuss/1961861/Python3-Simple-Solution-Faster-than-93 | class Solution:
def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]:
if not head:
return head
cur = dummy = ListNode()
a = head
while a:
if a.val == val and a.next is not None:
a = a.next
elif a.val == val and not a.next:
break
else:
cur.next = a
cur = a
a = a.next
if a and a.val == val:
cur.next = a.next
return dummy.next | remove-linked-list-elements | [Python3] Simple Solution, Faster than 93% | natscripts | 1 | 95 | remove linked list elements | 203 | 0.449 | Easy | 3,364 |
https://leetcode.com/problems/remove-linked-list-elements/discuss/1774376/Python-solution-with-comment-explanation.-Time-O(n)Space-O(1) | class Solution:
def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]:
#Edge case
if not head:
return head
# Record with the current pointer, because we don't want to modify the head pointer.
current = head
# Start compared with the second element.
while current.next:
if current.next.val == val:
current.next = current.next.next
else:
current = current.next
# The first element is not compared yet while the loop end.
if head.val == val:
head = head.next
return head | remove-linked-list-elements | Python solution with comment explanation. Time O(n)/Space O(1) | EnergyBoy | 1 | 84 | remove linked list elements | 203 | 0.449 | Easy | 3,365 |
https://leetcode.com/problems/remove-linked-list-elements/discuss/1642782/Pretty-Easy-with-a-dummy-node-Python-3 | class Solution:
def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]:
dummy = ListNode(-1, head)
curr = dummy
while curr and curr.next:
if curr.next.val == val:
curr.next = curr.next.next
else:
curr = curr.next
return dummy.next | remove-linked-list-elements | Pretty Easy with a dummy node Python 3 | neth_37 | 1 | 79 | remove linked list elements | 203 | 0.449 | Easy | 3,366 |
https://leetcode.com/problems/remove-linked-list-elements/discuss/1592528/python3-Simple-Solution-w-Video-Explanation | class Solution:
def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]:
prev = None
curr = head
while curr:
if curr.val == val:
if prev:
prev.next = curr.next
else:
head = curr.next
curr = curr.next
else:
prev = curr
curr = curr.next
return head | remove-linked-list-elements | python3 - Simple Solution w/ Video Explanation | hudsonh | 1 | 209 | remove linked list elements | 203 | 0.449 | Easy | 3,367 |
https://leetcode.com/problems/remove-linked-list-elements/discuss/1577253/Python-Iterative-Solution-in-O(n)-TC | class Solution:
def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]:
temp = head
prev = None
while(temp!=None):
if(temp.val == val):
#For skipping the current target Node
if(prev!=None):
prev.next = temp.next
#If the target value is in the first node
else:
head = temp.next
temp = temp.next
else:
prev = temp
temp = temp.next
return head | remove-linked-list-elements | Python Iterative Solution in O(n) TC | Prudhvinik1 | 1 | 31 | remove linked list elements | 203 | 0.449 | Easy | 3,368 |
https://leetcode.com/problems/remove-linked-list-elements/discuss/1068819/python-3-solution-beat-90 | class Solution:
def removeElements(self, head: ListNode, val: int) -> ListNode:
h=head
while(h):
if h.val==val and h==head:
head=head.next
elif h.val!=val:
prev=h
else:
prev.next=h.next
h=h.next
return head | remove-linked-list-elements | python 3 solution beat 90% | AchalGupta | 1 | 387 | remove linked list elements | 203 | 0.449 | Easy | 3,369 |
https://leetcode.com/problems/remove-linked-list-elements/discuss/642444/JavaPython3-dummy-head | class Solution:
def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]:
dummy = node = ListNode(next=head)
while node.next:
if node.next.val == val: node.next = node.next.next
else: node = node.next
return dummy.next | remove-linked-list-elements | [Java/Python3] dummy head | ye15 | 1 | 103 | remove linked list elements | 203 | 0.449 | Easy | 3,370 |
https://leetcode.com/problems/remove-linked-list-elements/discuss/2848379/203.-Remove-Linked-List-Elements-Python-Solution | class Solution:
def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]:
if not head: return head
dummy = ListNode(-1, head)
prev = dummy
while head:
#Checking if the Value exists
if head.val == val:
#Replacing the Link of previous Node with the Next Node, basically skipping the Node of the Element to be Deleted
prev.next = head.next
else:
#For the Elements that dont need to be deleted, keep them as it is!
prev = head
#Basic Incrementer for the While loop!
head = head.next
return dummy.next | remove-linked-list-elements | โ
203. Remove Linked List Elements - Python Solution | Brian_Daniel_Thomas | 0 | 1 | remove linked list elements | 203 | 0.449 | Easy | 3,371 |
https://leetcode.com/problems/remove-linked-list-elements/discuss/2831441/python-oror-simple-solution-oror-iterative | class Solution:
def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]:
# if linkedlist empty
if not head:
return None
# remove val from start of linkedlist
while head and (head.val == val):
head = head.next
itr, prev = head, head # iterator and previous node
# go through all nodes in the linkedlist
while itr:
if itr.val == val:
# skip over this node
prev.next = itr.next
else:
prev = itr
itr = itr.next
return head | remove-linked-list-elements | python || simple solution || iterative | wduf | 0 | 3 | remove linked list elements | 203 | 0.449 | Easy | 3,372 |
https://leetcode.com/problems/remove-linked-list-elements/discuss/2655178/Python-O(n)-time-complexity-O(1)-space-complexity. | class Solution:
def removeElements(self, head, val):
if head == None:
return head
while head.val == val: # O(n)
head = head.next
if head == None:
return head
prev = head
current = head.next
while current != None: # O(n)
if current.val == val:
prev.next = current.next
else:
prev = current
current = current.next
return head | remove-linked-list-elements | Python O(n) time complexity, O(1) space complexity. | OsamaRakanAlMraikhat | 0 | 11 | remove linked list elements | 203 | 0.449 | Easy | 3,373 |
https://leetcode.com/problems/remove-linked-list-elements/discuss/2647547/Python3-Recursive-Solution | class Solution:
def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]:
if not head:
return head
# print(head.val)
if head.val == val:
head = self.removeElements(head.next, val)
else:
head.next = self.removeElements(head.next, val)
return head | remove-linked-list-elements | Python3 Recursive Solution | jimunna150 | 0 | 30 | remove linked list elements | 203 | 0.449 | Easy | 3,374 |
https://leetcode.com/problems/count-primes/discuss/1267254/Python-3-solution-97.7-faster | class Solution:
def countPrimes(self, n: int) -> int:
if n<2:
return 0
#initialize a list of length n
prime=[1]*n
#mark 0th and 1st index as 0
prime[0]=prime[1]=0
#we will check for multiple from range 2 to sqrt(n)
for i in range(2,int(sqrt(n))+1):
if prime[i] == 1:
#mark all multiple of prime number as 0
prime[i*i:n:i] = [0] * ((n-1-i*i)//i + 1)
#return total count of prime
return sum(prime) | count-primes | Python 3 solution 97.7% faster | ritesh98 | 11 | 1,700 | count primes | 204 | 0.331 | Medium | 3,375 |
https://leetcode.com/problems/count-primes/discuss/1863213/python3-or-two-solution-or99.47-faster-and-65-faster | class Solution:
def countPrimes(self, n: int) -> int:
nums = [0, 0] + [1] * (n - 2)
for i in range(2,int(sqrt(n)+1)):
if nums[i]==1:
for j in range(i*i,n,i):
nums[j]=0
return sum(nums) | count-primes | python3 | two solution |99.47% faster and 65% faster | Anilchouhan181 | 7 | 932 | count primes | 204 | 0.331 | Medium | 3,376 |
https://leetcode.com/problems/count-primes/discuss/493555/python3%3A-Sieve-of-Eratosthenes | class Solution:
def countPrimes(self, n):
if n < 3: return 0
dp = [0, 0] + [1] * (n - 2)
for i in range(2, int(n ** 0.5) + 1):
if dp[i]: dp[i ** 2:n:i] = [0] * len(dp[i ** 2:n:i])
return sum(dp) | count-primes | [python3]: Sieve of Eratosthenes | i-i | 5 | 1,500 | count primes | 204 | 0.331 | Medium | 3,377 |
https://leetcode.com/problems/count-primes/discuss/2837840/Very-easy-solution-using-Sieve-of-Eratosthenes-in-Python | class Solution:
def countPrimes(self, n: int) -> int:
arr = [True] * n
if n == 0 or n == 1:
return 0
arr[0], arr[1] = False, False
for i in range(2, int(n ** 0.5) + 1):
if arr[i]:
for j in range(i + i, n, i):
arr[j] = False
return sum(arr) | count-primes | Very easy solution using Sieve of Eratosthenes in Python | ankurbhambri | 3 | 224 | count primes | 204 | 0.331 | Medium | 3,378 |
https://leetcode.com/problems/count-primes/discuss/1255523/Python3-simple-and-clean-solution | class Solution:
def countPrimes(self, n: int) -> int:
if n <= 2:
return 0
isPrime = [0]*n
for i in range(2,int(n**0.5)+1):
for j in range(i**2,n,i):
isPrime[j] = 1
return n - sum(isPrime) - 2 | count-primes | Python3 simple and clean solution | EklavyaJoshi | 2 | 264 | count primes | 204 | 0.331 | Medium | 3,379 |
https://leetcode.com/problems/count-primes/discuss/707941/Python3-sieve-of-Eratosthenes | class Solution:
def countPrimes(self, n: int) -> int:
"""sieve of Eratosthenes"""
if n <= 2: return 0 # no primes less than 2
primes = [False]*2 + [True]*(n-2) # 0 & 1 are not a prime
for i in range(2, int(sqrt(n))+1): # only need to check up to sqrt(n)
if primes[i]: # non-prime factors are useless
for k in range(i*i, n, i): # starting from i*i
primes[k] = False
return sum(primes) | count-primes | [Python3] sieve of Eratosthenes | ye15 | 2 | 271 | count primes | 204 | 0.331 | Medium | 3,380 |
https://leetcode.com/problems/count-primes/discuss/707941/Python3-sieve-of-Eratosthenes | class Solution:
def countPrimes(self, n: int) -> int:
if n < 2: return 0 # edge case
sieve = [True]*n
sieve[0] = sieve[1] = False
for i in range(int(sqrt(n))+1):
if sieve[i]:
for ii in range(i*i, n, i):
sieve[ii] = False
return sum(sieve) | count-primes | [Python3] sieve of Eratosthenes | ye15 | 2 | 271 | count primes | 204 | 0.331 | Medium | 3,381 |
https://leetcode.com/problems/count-primes/discuss/2334985/Python-86.03-faster-or-Simplest-solution-with-explanation-or-Beg-to-Adv-or-Prime-Number-or-Math | class Solution:
def countPrimes(self, n: int) -> int:
# Prerequisite:
# What is prime number. What are they just the starting.
truth = [True]*n # making a list of lenght n. And keep all the values as True.
if n<2: # as 0 & 1 are not prime numbers.
return 0
truth[0], truth[1] = False, False #as we added True in the truth list. So will make false for ) & 1 as they are not prime numbers.
i=2 # As we know 0 & 1 are not prime.
while i*i<n: # why we are doing it as i*i here is bcz lets say 5*2 = 10 is divisble by 2 as well as 5 so if 10 is already removed why to traverse a value which is already travered once. so in case of n=5 - 5<5. CONCLUSION : i<sqrt(n)
#why we are running the loop till n is bcz question says " prime numbers that are strictly less than n".
if truth[i] == True:
for j in range(i*i,n,i): # if we have mutiple of a number in the range of n, we have to remove them as they can be prime. i.e 2 is prime, but its multiple in n = 10 are 4,6,8 they cant be prime. So we will make them false(means not a prime).
truth[j]=False
i += 1 # increasing our iterator.
return truth.count(True) # will count true value | count-primes | Python 86.03% faster | Simplest solution with explanation | Beg to Adv | Prime Number | Math | rlakshay14 | 1 | 307 | count primes | 204 | 0.331 | Medium | 3,382 |
https://leetcode.com/problems/count-primes/discuss/1554674/Python3-Solution | class Solution:
def countPrimes(self, n):
primes = [False,False] + [True]*(n-2)
for i in range(2, int(math.sqrt(n))+1):
if primes[i]:
primes[i*i: n: i] = [False] * int((n-i*i-1)//i + 1)
return sum(primes) | count-primes | Python3 Solution | satyam2001 | 1 | 736 | count primes | 204 | 0.331 | Medium | 3,383 |
https://leetcode.com/problems/count-primes/discuss/2824729/Python-easy-code-Solution | class Solution:
def countPrimes(self, n: int) -> int:
if(n<=1):
return 0
d = [True] * n
d[0] = d[1] = False
for i in range(2,n):
if(d[i]):
for j in range(i*i,n,i):
d[j] = False
return sum(d) | count-primes | Python easy code Solution | anshu71 | 0 | 11 | count primes | 204 | 0.331 | Medium | 3,384 |
https://leetcode.com/problems/count-primes/discuss/2752464/easy-approach!! | class Solution:
def countPrimes(self, n: int) -> int:
if n<2:
return 0
isPrime = [True]*n
isPrime[0] = isPrime[1] = False
for i in range(2,math.ceil(math.sqrt(n))):
if isPrime[i]:
for multiples_of_i in range(i*i,n,i):
isPrime[multiples_of_i] = False
return sum(isPrime) | count-primes | easy approach!! | sanjeevpathak | 0 | 10 | count primes | 204 | 0.331 | Medium | 3,385 |
https://leetcode.com/problems/count-primes/discuss/2750161/Simple-Beginner-Friendly-Approach-or-Sieve-of-Eratosthenes | class Solution:
import math
def countPrimes(self, n: int) -> int:
if n <= 1:
return 0
prime_arr = [True] * n
prime_arr[0] = False
prime_arr[1] = False
for i in range(2, ceil(n ** 0.5)):
if prime_arr[i] is False:
continue
prime_arr[i*2::i] = [False] * len(prime_arr[i*2::i])
return sum(prime_arr) | count-primes | Simple Beginner Friendly Approach | Sieve of Eratosthenes | sonnylaskar | 0 | 11 | count primes | 204 | 0.331 | Medium | 3,386 |
https://leetcode.com/problems/count-primes/discuss/2731823/Sieve-but-with-improved-memory | class Solution:
# Improved Memory 100% Sieve
def countPrimes(self, n: int) -> int:
n -= 1
if n <= 0:
return 0
# If x is even, exclude x from list (-1):
sieve_size = (n // 2 - 1) if n % 2 == 0 else (n // 2)
sieve = [True for _ in range(sieve_size)] # Sieve
res = 0 # List of Primes
if n >= 2:
res += 1 # 2 is prime by default
for i in range(sieve_size):
if sieve[i]:
value_at_i = i*2 + 3
res += 1
for j in range(i, sieve_size, value_at_i):
sieve[j] = False
return res | count-primes | Sieve but with improved memory ๐ฅถ | shiv-codes | 0 | 17 | count primes | 204 | 0.331 | Medium | 3,387 |
https://leetcode.com/problems/count-primes/discuss/2663480/Python-or-Seive-of-Eratosthenes | class Solution:
def countPrimes(self, n):
if n<3:
return 0
seive=[1]*n
seive[0]=0
seive[1]=0
i=2
while(i*i<n):
if seive[i]:
seive[i*i:n:i]=[0]*((n-1-i*i)//i+1)
i+=1
return sum(seive) | count-primes | Python | Seive of Eratosthenes | Prithiviraj1927 | 0 | 53 | count primes | 204 | 0.331 | Medium | 3,388 |
https://leetcode.com/problems/count-primes/discuss/1912092/python-3-oror-simple-solution | class Solution:
def countPrimes(self, n: int) -> int:
if n <= 1:
return 0
primes = [False]*2 + [True]*(n-2)
res = n - 2
for i in range(2, math.ceil(math.sqrt(n))):
if primes[i]:
for j in range(i*i, n, i):
if primes[j]:
res -= 1
primes[j] = False
return res | count-primes | python 3 || simple solution | dereky4 | 0 | 449 | count primes | 204 | 0.331 | Medium | 3,389 |
https://leetcode.com/problems/count-primes/discuss/1821635/Easy-to-Understand-Python-Solution-Using-Sieve-of-Eratosthenes-O(nlog(logn))-Time-Complexity | class Solution:
def countPrimes(self, n: int) -> int:
if n < 3:
return 0
primes = [True] * n
primes[0] = primes[1] = False
limit = int(n ** 0.5) + 1
for i in range(2, limit):
if primes[i]:
for j in range(i*i, n, i):
primes[j] = False
return sum(primes) | count-primes | Easy to Understand Python Solution Using Sieve of Eratosthenes - O(nlog(logn)) Time Complexity | schedutron | 0 | 314 | count primes | 204 | 0.331 | Medium | 3,390 |
https://leetcode.com/problems/count-primes/discuss/1478911/Brute-Force-oror-Easy-to-understand-greater-For-beginners | class Solution:
def countPrimes(self, n: int) -> int:
#This is the Brute Force Approach of number of prime numbers from 1 till a given n
answer = 0
if n == 0 or n == 1:
return 0
for prime in range(2, n):
for divisor in range(2, prime):
if prime % divisor == 0:
break
else:
answer += 1
return answer | count-primes | Brute Force || Easy to understand --> For beginners | aarushsharmaa | 0 | 446 | count primes | 204 | 0.331 | Medium | 3,391 |
https://leetcode.com/problems/count-primes/discuss/1095020/Python-mark-number-multiples-as-%22False%22-Intuitive-explanation | class Solution:
def countPrimes(self, n: int) -> int:
# n=2 or less isn't prime (see comments if confused)
if n <= 2: return 0
# *Assume* almost all numbers are primes
is_prime = [True] * n
# Zero and one aren't primes
is_prime[0] = is_prime[1] = False
# Check every number 2..<n
for i in range(2, n):
# If we've proven something isn't a prime
# We can continue
if not is_prime[i]: continue
# Leap forward in increments of "i"
# We know these elements aren't primes
# because they're divisible by 'i', lol
# You can actually do i**2, but to me, this is more intuitive
for j in range(i*2, n, i):
is_prime[j] = False
# Return the count of the prime numbers
return sum(is_prime) | count-primes | Python - mark number multiples as "False" - Intuitive explanation | dev-josh | 0 | 525 | count primes | 204 | 0.331 | Medium | 3,392 |
https://leetcode.com/problems/count-primes/discuss/794805/python-Solution-or-SieveOfEratosthenes | class Solution:
def countPrimes(self, n: int) -> int:
if n < 3:
return 0
prime = [True for i in range(n)]
p = 2
while (p*p <= n):
if prime[p] == True:
for i in range(p*2, n, p):
prime[i] = False
p+=1
prime[0] = False
prime[1] = False
count = 0
for p in range(n):
if prime[p]:
count+=1
return count | count-primes | python Solution | SieveOfEratosthenes | yash921 | 0 | 183 | count primes | 204 | 0.331 | Medium | 3,393 |
https://leetcode.com/problems/count-primes/discuss/456003/Python3-super-simple-solutions-using-two-for()-loops | class Solution:
def countPrimes(self, n: int) -> int:
if n < 3:
return 0
primes = [1]*n
primes[0] = primes[1] = 0
for i in range(2,int(n**0.5)+1):
if primes[i] != 0:
for j in range(2*i,n,i):
primes[j] = 0
return sum(primes)
def countPrimesOptimized(self, n: int) -> int:
if n < 3:
return 0
primes = [1]*n
primes[0] = primes[1] = 0
for i in range(2,int(n**0.5)+1):
if primes[i]:
primes[i*i:n:i] = [0]*len(primes[i*i:n:i])
#print(i,primes[i*i:n:i])
return sum(primes) | count-primes | Python3 super simple solutions using two for() loops | jb07 | 0 | 388 | count primes | 204 | 0.331 | Medium | 3,394 |
https://leetcode.com/problems/isomorphic-strings/discuss/2472118/Very-Easy-oror-100-oror-Fully-Explained-oror-Java-C%2B%2B-Python-Javascript-Python3-(Using-HashMap) | class Solution:
def isIsomorphic(self, s: str, t: str) -> bool:
return [*map(s.index, s)] == [*map(t.index, t)] | isomorphic-strings | Very Easy || 100% || Fully Explained || Java, C++, Python, Javascript, Python3 (Using HashMap) | PratikSen07 | 44 | 5,500 | isomorphic strings | 205 | 0.426 | Easy | 3,395 |
https://leetcode.com/problems/isomorphic-strings/discuss/1337259/2-liner-with-99-efficiency-and-explanation. | class Solution:
def isIsomorphic(self, s: str, t: str) -> bool:
zipped_set = set(zip(s, t))
return len(zipped_set) == len(set(s)) == len(set(t)) | isomorphic-strings | 2 liner with 99% efficiency and explanation. | AmrinderKaur1 | 43 | 1,700 | isomorphic strings | 205 | 0.426 | Easy | 3,396 |
https://leetcode.com/problems/isomorphic-strings/discuss/1696800/Python-Easy-Approach | class Solution:
def isIsomorphic(self, s: str, t: str) -> bool:
if len(set(s)) != len(set(t)):
return False
hash_map = {}
for char in range(len(t)):
if t[char] not in hash_map:
hash_map[t[char]] = s[char]
elif hash_map[t[char]] != s[char]:
return False
return True | isomorphic-strings | [Python] Easy Approach โ | leet_satyam | 19 | 1,500 | isomorphic strings | 205 | 0.426 | Easy | 3,397 |
https://leetcode.com/problems/isomorphic-strings/discuss/381930/Python-multiple-solutions | class Solution:
def isIsomorphic(self, s: str, t: str) -> bool:
mapping = {}
for cs, ct in zip(s, t):
try:
if mapping[cs] != ct:
return False
except:
if ct in mapping.values():
return False
mapping[cs] = ct
return True | isomorphic-strings | Python multiple solutions | amchoukir | 7 | 1,700 | isomorphic strings | 205 | 0.426 | Easy | 3,398 |
https://leetcode.com/problems/isomorphic-strings/discuss/381930/Python-multiple-solutions | class Solution:
def isIsomorphic(self, s: str, t: str) -> bool:
mapping = {}
reverse_mapping = {}
for cs, ct in zip(s, t):
try:
if mapping[cs] != ct:
return False
except:
if ct in reverse_mapping:
return False
mapping[cs] = ct
reverse_mapping[ct] = cs
return True | isomorphic-strings | Python multiple solutions | amchoukir | 7 | 1,700 | isomorphic strings | 205 | 0.426 | Easy | 3,399 |
Subsets and Splits