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/describe-the-painting/discuss/1359731/Python3-sweeping-again
|
class Solution:
def splitPainting(self, segments: List[List[int]]) -> List[List[int]]:
vals = []
for start, end, color in segments:
vals.append((start, +color))
vals.append((end, -color))
ans = []
prefix = prev = 0
for x, c in sorted(vals):
if prev < x and prefix: ans.append([prev, x, prefix])
prev = x
prefix += c
return ans
|
describe-the-painting
|
[Python3] sweeping again
|
ye15
| 13
| 580
|
describe the painting
| 1,943
| 0.48
|
Medium
| 27,400
|
https://leetcode.com/problems/describe-the-painting/discuss/1395896/O(nlogn)-oror-Clean-and-Concise-oror-97-faster-oror-Well-Explained-with-Example
|
class Solution:
def splitPainting(self, segments: List[List[int]]) -> List[List[int]]:
dic = defaultdict(int)
for s,e,c in segments:
dic[s]+=c
dic[e]-=c
st=None
color=0
res = []
for p in sorted(dic):
if st is not None and color!=0:
res.append([st,p,color])
color+=dic[p]
st = p
return res
|
describe-the-painting
|
๐ O(nlogn) || Clean and Concise || 97% faster || Well-Explained with Example ๐๐
|
abhi9Rai
| 9
| 253
|
describe the painting
| 1,943
| 0.48
|
Medium
| 27,401
|
https://leetcode.com/problems/describe-the-painting/discuss/1360224/Python3-solution-nlogn-simple-code
|
class Solution:
def splitPainting(self, segment: List[List[int]]) -> List[List[int]]:
f=[]
for a,b,c in segment:
f.append([a,c])
f.append([b,-c])
f.sort()
s=0
ft=[]
n=len(f)
for i in range(n-1):
s+=f[i][1]
if(f[i][0]!=f[i+1][0] and s!=0):
ft.append([f[i][0],f[i+1][0],s])
return ft
|
describe-the-painting
|
Python3 solution nlogn simple code
|
madhukar0011
| 0
| 42
|
describe the painting
| 1,943
| 0.48
|
Medium
| 27,402
|
https://leetcode.com/problems/number-of-visible-people-in-a-queue/discuss/1359735/Python3-mono-stack
|
class Solution:
def canSeePersonsCount(self, heights: List[int]) -> List[int]:
ans = [0]*len(heights)
stack = [] # mono-stack
for i in reversed(range(len(heights))):
while stack and stack[-1] <= heights[i]:
ans[i] += 1
stack.pop()
if stack: ans[i] += 1
stack.append(heights[i])
return ans
|
number-of-visible-people-in-a-queue
|
[Python3] mono-stack
|
ye15
| 10
| 667
|
number of visible people in a queue
| 1,944
| 0.697
|
Hard
| 27,403
|
https://leetcode.com/problems/number-of-visible-people-in-a-queue/discuss/2619041/Python3-Solution-or-O(n)-or-Stack
|
class Solution:
def canSeePersonsCount(self, A):
n = len(A)
stack, res = [], [0] * n
for i in range(n - 1, -1, -1):
while stack and stack[-1] <= A[i]:
stack.pop()
res[i] += 1
if stack: res[i] += 1
stack.append(A[i])
return res
|
number-of-visible-people-in-a-queue
|
โ Python3 Solution | O(n) | Stack
|
satyam2001
| 1
| 138
|
number of visible people in a queue
| 1,944
| 0.697
|
Hard
| 27,404
|
https://leetcode.com/problems/number-of-visible-people-in-a-queue/discuss/1705906/Python-stack-solution
|
class Solution:
def canSeePersonsCount(self, heights: List[int]) -> List[int]:
res = [0] * len(heights)
popCount = 0
stack = [heights[-1]]
for i in range(len(heights) - 2, -1, -1):
while stack and stack[-1] < heights[i]:
stack.pop()
popCount += 1
totalCount = popCount + (1 if stack else 0)
res[i] = totalCount
stack.append(heights[i])
popCount = 0
return res
|
number-of-visible-people-in-a-queue
|
Python stack solution
|
swang2017
| 1
| 169
|
number of visible people in a queue
| 1,944
| 0.697
|
Hard
| 27,405
|
https://leetcode.com/problems/number-of-visible-people-in-a-queue/discuss/2823255/Python-DP-Solution
|
class Solution:
def canSeePersonsCount(self, heights: List[int]) -> List[int]:
next_max = [-1 for i in range(len(heights))]
res = [0 for i in range(len(heights))]
for i in range(len(heights)-2, -1, -1):
temp = i+1
vis = 0
while temp != -1:
if heights[i] > heights[temp]:
vis += 1
temp = next_max[temp]
else:
next_max[i] = temp
vis += 1
break
res[i] = vis
return res
|
number-of-visible-people-in-a-queue
|
Python DP Solution
|
brian-xu
| 0
| 5
|
number of visible people in a queue
| 1,944
| 0.697
|
Hard
| 27,406
|
https://leetcode.com/problems/number-of-visible-people-in-a-queue/discuss/1999935/python-3-oror-monotonic-stack-oror-O(n)O(n)
|
class Solution:
def canSeePersonsCount(self, nums: List[int]) -> List[int]:
res = [0] * len(nums)
stack = []
for i, num in enumerate(nums):
while stack and num > nums[stack[-1]]:
res[stack.pop()] += 1
if stack:
res[stack[-1]] += 1
stack.append(i)
return res
|
number-of-visible-people-in-a-queue
|
python 3 || monotonic stack || O(n)/O(n)
|
dereky4
| 0
| 115
|
number of visible people in a queue
| 1,944
| 0.697
|
Hard
| 27,407
|
https://leetcode.com/problems/number-of-visible-people-in-a-queue/discuss/1523889/Python-or-Monotonic-Stack
|
class Solution:
def canSeePersonsCount(self, heights: List[int]) -> List[int]:
stk=[heights[-1]]
ans=[0]*len(heights)
for i in range(len(heights)-2,-1,-1):
h=heights[i]
cansee=0
while stk and h>stk[0]:
cansee+=1
stk.pop(0)
ans[i]=cansee+1 if stk else cansee
stk.insert(0,h)
return ans
|
number-of-visible-people-in-a-queue
|
Python | Monotonic Stack
|
heckt27
| 0
| 67
|
number of visible people in a queue
| 1,944
| 0.697
|
Hard
| 27,408
|
https://leetcode.com/problems/sum-of-digits-of-string-after-convert/discuss/1360730/Python3-simulation
|
class Solution:
def getLucky(self, s: str, k: int) -> int:
s = "".join(str(ord(ch) - 96) for ch in s)
for _ in range(k):
x = sum(int(ch) for ch in s)
s = str(x)
return x
|
sum-of-digits-of-string-after-convert
|
[Python3] simulation
|
ye15
| 5
| 487
|
sum of digits of string after convert
| 1,945
| 0.612
|
Easy
| 27,409
|
https://leetcode.com/problems/sum-of-digits-of-string-after-convert/discuss/1360730/Python3-simulation
|
class Solution:
def getLucky(self, s: str, k: int) -> int:
s = "".join(str(ord(ch)-96) for ch in s)
for _ in range(k): s = str(sum(int(ch) for ch in s))
return int(s)
|
sum-of-digits-of-string-after-convert
|
[Python3] simulation
|
ye15
| 5
| 487
|
sum of digits of string after convert
| 1,945
| 0.612
|
Easy
| 27,410
|
https://leetcode.com/problems/sum-of-digits-of-string-after-convert/discuss/1634650/Python-short-list-comprehension-solution
|
class Solution:
def getLucky(self, s: str, k: int) -> int:
nums = [str(ord(c) - ord('a') + 1) for c in s]
for _ in range(k):
nums = str(sum(int(digit) for num in nums for digit in num))
return nums
|
sum-of-digits-of-string-after-convert
|
Python short list comprehension solution
|
user5382x
| 2
| 244
|
sum of digits of string after convert
| 1,945
| 0.612
|
Easy
| 27,411
|
https://leetcode.com/problems/sum-of-digits-of-string-after-convert/discuss/1975311/Python-solution-using-str()-and-map()
|
class Solution:
def getLucky(self, s: str, k: int) -> int:
nums = [str(ord(c) - ord('a') + 1) for c in s]
nums = ''.join(nums)
for i in range(k):
nums = str(sum(map(int, nums)))
return nums
|
sum-of-digits-of-string-after-convert
|
Python solution using str() and map()
|
iamamirhossein
| 1
| 125
|
sum of digits of string after convert
| 1,945
| 0.612
|
Easy
| 27,412
|
https://leetcode.com/problems/sum-of-digits-of-string-after-convert/discuss/1931197/Python-Solution
|
class Solution:
def getLucky(self, s: str, k: int) -> int:
s = int(''.join(map(lambda x: str(ord(x) - 96), s)))
for i in range(k):
s = reduce(lambda x, y: int(x) + int(y), str(s))
return s
|
sum-of-digits-of-string-after-convert
|
Python Solution
|
hgalytoby
| 1
| 100
|
sum of digits of string after convert
| 1,945
| 0.612
|
Easy
| 27,413
|
https://leetcode.com/problems/sum-of-digits-of-string-after-convert/discuss/1593566/Python-3-easy-fast-solution
|
class Solution:
def getLucky(self, s: str, k: int) -> int:
s = int(''.join(str(ord(c) - 96) for c in s))
for _ in range(k):
s_sum = 0
while s:
s_sum += s % 10
s //= 10
s = s_sum
return s
|
sum-of-digits-of-string-after-convert
|
Python 3 easy, fast solution
|
dereky4
| 1
| 161
|
sum of digits of string after convert
| 1,945
| 0.612
|
Easy
| 27,414
|
https://leetcode.com/problems/sum-of-digits-of-string-after-convert/discuss/1374006/Easy-simple-with-python-3
|
class Solution:
def getLucky(self, s: str, k: int) -> int:
letter = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
t = ""
for i in s:
t += str(letter.index(i)+1)
sm = 0
while k > 0 :
sm = 0
for i in t:
sm += int(i)
t = str(sm)
k -= 1
return t
|
sum-of-digits-of-string-after-convert
|
Easy , simple with python 3
|
youbou
| 1
| 205
|
sum of digits of string after convert
| 1,945
| 0.612
|
Easy
| 27,415
|
https://leetcode.com/problems/sum-of-digits-of-string-after-convert/discuss/2705081/Simple-and-Easy-to-Understand-or-Beginner's-Friendly-or-Python
|
class Solution(object):
def getLucky(self, s, k):
hashT = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5, 'f':6, 'g':7, 'h':8, 'i':9, 'j':10, 'k':11, 'l':12, 'm':13,
'n':14, 'o':15, 'p':16, 'q':17, 'r':18, 's':19, 't':20, 'u':21, 'v':22, 'w':23, 'x':24, 'y':25, 'z':26}
ans = ''
for ch in s:
ans += str(hashT[ch])
i = 0
while k > i:
temp = 0
for n in ans:
temp += int(n)
ans = str(temp)
i += 1
return int(ans)
|
sum-of-digits-of-string-after-convert
|
Simple and Easy to Understand | Beginner's Friendly | Python
|
its_krish_here
| 0
| 16
|
sum of digits of string after convert
| 1,945
| 0.612
|
Easy
| 27,416
|
https://leetcode.com/problems/sum-of-digits-of-string-after-convert/discuss/2695041/Easy-Python-solution-using-just-2-for-loops-with-explanation
|
class Solution:
def getLucky(self, s: str, k: int) -> int:
#Initiate a blank string
alpha_numeric = ""
for i in s:
# Append the ASCII code of the each string character in that string
alpha_numeric += str(ord(i) - 96)
for j in range(k):
# Convert the str elements of the string to int, Put them in a list and sum that list
alpha_numeric = sum(list(map(int, str(alpha_numeric))))
# After 'k' iterations, return that sum
return alpha_numeric
|
sum-of-digits-of-string-after-convert
|
Easy Python solution using just 2 for loops with explanation
|
code_snow
| 0
| 20
|
sum of digits of string after convert
| 1,945
| 0.612
|
Easy
| 27,417
|
https://leetcode.com/problems/sum-of-digits-of-string-after-convert/discuss/2684798/Easy-to-understand-with-99-accuracy
|
class Solution:
def getLucky(self, s: str, k: int) -> int:
a=""
for i in s:
a+=str((ord(i)-96))
for j in range(k):
ans=0
for i in a:
ans+=int(i)
a=str(ans)
return a
|
sum-of-digits-of-string-after-convert
|
Easy to understand with 99% accuracy
|
rupaksaikrishnayerramsetti
| 0
| 6
|
sum of digits of string after convert
| 1,945
| 0.612
|
Easy
| 27,418
|
https://leetcode.com/problems/sum-of-digits-of-string-after-convert/discuss/2627155/sum-of-digits-of-string-after-convert
|
class Solution:
def getLucky(self, s: str, k: int) -> int:
d={'a':1,'b':2,'c':3,'d':4,'e':5,'f':6,'g':7,'h':8,'i':9,'j':10,'k':11,'l':12,'m':13,'n':14,'o':15,'p':16,'q':17,'r':18,'s':19,'t':20,'u':21,'v':22,'w':23,'x':24,'y':25,'z':26}
l=[str(d[ele]) for ele in s]
ss=''.join(l)
for i in range(k):
val = 0
for i in ss:
val=val+int(i)
ss=str(val)
return ss #int(ss)
|
sum-of-digits-of-string-after-convert
|
sum of digits of string after convert
|
shivansh2001sri
| 0
| 7
|
sum of digits of string after convert
| 1,945
| 0.612
|
Easy
| 27,419
|
https://leetcode.com/problems/sum-of-digits-of-string-after-convert/discuss/2191388/Python3-simple-solution
|
class Solution:
def getLucky(self, s: str, k: int) -> int:
x = ''
for i in s:
x += str(ord(i) - 96)
while k > 0:
z = 0
for i in x:
z += int(i)
x = str(z)
k -= 1
return x
|
sum-of-digits-of-string-after-convert
|
Python3 simple solution
|
EklavyaJoshi
| 0
| 36
|
sum of digits of string after convert
| 1,945
| 0.612
|
Easy
| 27,420
|
https://leetcode.com/problems/sum-of-digits-of-string-after-convert/discuss/2141738/Python-Solution
|
class Solution:
def getLucky(self, s: str, k: int) -> int:
import string
letterToNumberMap = dict(zip(string.ascii_lowercase, range(1,27)))
theString = ''
for s_ in s:
theString += str(letterToNumberMap[s_])
ans = 0
for i in range(k):
ans = sum([int(theString[j]) for j in range(len(theString))])
theString = str(ans)
return ans
|
sum-of-digits-of-string-after-convert
|
Python Solution
|
suj2803
| 0
| 46
|
sum of digits of string after convert
| 1,945
| 0.612
|
Easy
| 27,421
|
https://leetcode.com/problems/sum-of-digits-of-string-after-convert/discuss/2036922/Python-Clean-and-Simple!
|
class Solution:
def getLucky(self, s, k):
return self.transform(self.convert(s), k)
def convert(self, s):
return int("".join(str(ord(c)-ord("a")+1) for c in s))
def transform(self, num, k):
return num if k == 0 else self.transform(sum(int(d) for d in str(num)), k-1)
|
sum-of-digits-of-string-after-convert
|
Python - Clean and Simple!
|
domthedeveloper
| 0
| 79
|
sum of digits of string after convert
| 1,945
| 0.612
|
Easy
| 27,422
|
https://leetcode.com/problems/sum-of-digits-of-string-after-convert/discuss/2034329/Python-simple-solution
|
class Solution:
def getLucky(self, s: str, k: int) -> int:
ans = sum(map(int,list(''.join([str(x-96) for x in list(map(ord,list(s)))]))))
for i in range(k-1):
ans = sum(map(int,list(str(ans))))
return ans
|
sum-of-digits-of-string-after-convert
|
Python simple solution
|
StikS32
| 0
| 45
|
sum of digits of string after convert
| 1,945
| 0.612
|
Easy
| 27,423
|
https://leetcode.com/problems/sum-of-digits-of-string-after-convert/discuss/1875324/Python-Solution-(Faster-than-98)
|
class Solution:
def getLucky(self, s: str, k: int) -> int:
count = 0
for i in s:
x = (ord(i) - 96)
while x != 0:
count += x%10
x //= 10
k -= 1
for i in range(k):
x = count
count = 0
while x != 0:
count += x%10
x //= 10
return count
|
sum-of-digits-of-string-after-convert
|
Python Solution (Faster than 98%)
|
AakRay
| 0
| 72
|
sum of digits of string after convert
| 1,945
| 0.612
|
Easy
| 27,424
|
https://leetcode.com/problems/sum-of-digits-of-string-after-convert/discuss/1860699/Python-solution-easy-method
|
class Solution:
def getLucky(self, s: str, k: int) -> int:
alpha_pos = [str(ord(x)-96) for x in s]
sum_str = list(''.join(alpha_pos))
for i in range(k):
sum_str = str(sum([int(x) for x in sum_str]))
return int(sum_str)
|
sum-of-digits-of-string-after-convert
|
Python solution easy method
|
alishak1999
| 0
| 48
|
sum of digits of string after convert
| 1,945
| 0.612
|
Easy
| 27,425
|
https://leetcode.com/problems/sum-of-digits-of-string-after-convert/discuss/1793797/3-Lines-Python-Solution-oror-75-Faster-(37ms)-oror-Memory-less-than-60
|
class Solution:
def getLucky(self, s: str, k: int) -> int:
ans = sum([(ord(char)-96)//10 + (ord(char)-96)%10 for char in s])
for i in range(1,k): ans = sum([int(x) for x in str(ans)])
return ans
|
sum-of-digits-of-string-after-convert
|
3-Lines Python Solution || 75% Faster (37ms) || Memory less than 60%
|
Taha-C
| 0
| 63
|
sum of digits of string after convert
| 1,945
| 0.612
|
Easy
| 27,426
|
https://leetcode.com/problems/sum-of-digits-of-string-after-convert/discuss/1643772/Python-faster-than-99-perent
|
class Solution:
def getLucky(self, s: str, k: int) -> int:
values = (ord(v)-ord('a')+1 for v in s)
n = int(''.join(map(str, values)))
for _ in range(k):
n = sum(int(d) for d in str(n))
return n
|
sum-of-digits-of-string-after-convert
|
Python, faster than 99 perent
|
emwalker
| 0
| 107
|
sum of digits of string after convert
| 1,945
| 0.612
|
Easy
| 27,427
|
https://leetcode.com/problems/sum-of-digits-of-string-after-convert/discuss/1481250/Python-Simple-Solution
|
class Solution:
def getLucky(self, s: str, k: int) -> int:
transform_1 = "".join([
str(ord(c) - ord('a') + 1)
for c in s
])
transform_n = transform_1
for _ in range(k):
transform_n = sum([int(c) for c in str(transform_n)])
return transform_n
|
sum-of-digits-of-string-after-convert
|
[Python] Simple Solution
|
dev-josh
| 0
| 127
|
sum of digits of string after convert
| 1,945
| 0.612
|
Easy
| 27,428
|
https://leetcode.com/problems/sum-of-digits-of-string-after-convert/discuss/1424278/Python-using-standard-functions
|
class Solution:
def getLucky(self, s: str, k: int) -> int:
t = "".join(map(lambda c: str(ord(c) - 96), s))
for _ in range(k):
if len(t) == 1:
break
t = str(sum(map(int, t)))
return int(t)
|
sum-of-digits-of-string-after-convert
|
Python, using standard functions
|
blue_sky5
| 0
| 77
|
sum of digits of string after convert
| 1,945
| 0.612
|
Easy
| 27,429
|
https://leetcode.com/problems/sum-of-digits-of-string-after-convert/discuss/1419408/Intuitive-approach-by-map-and-join
|
class Solution:
def getLucky(self, s: str, k: int) -> int:
cvt = ''.join(map(lambda c: str(ord(c)-96), s))
for i in range(k):
cvt = str(sum(map(lambda c:int(c), cvt)))
if len(cvt) == 1:
break
return int(cvt)
|
sum-of-digits-of-string-after-convert
|
Intuitive approach by map & join
|
puremonkey2001
| 0
| 44
|
sum of digits of string after convert
| 1,945
| 0.612
|
Easy
| 27,430
|
https://leetcode.com/problems/sum-of-digits-of-string-after-convert/discuss/1395492/python-oror-easy-oror-clean-oror-fast
|
class Solution:
def getLucky(self, s: str, k: int) -> int:
ans=0
n=""
for i in range(len(s)):
n=n+ str((ord(s[i])-96))
while(k!=0):
ans=0
for i in range (len(n)):
ans=ans+int(n[i])
n=str(ans)
k=k-1
return ans
|
sum-of-digits-of-string-after-convert
|
python || easy || clean || fast
|
minato_namikaze
| 0
| 69
|
sum of digits of string after convert
| 1,945
| 0.612
|
Easy
| 27,431
|
https://leetcode.com/problems/sum-of-digits-of-string-after-convert/discuss/1391505/Simple-Python-Solution
|
class Solution:
def getLucky(self, s: str, k: int) -> int:
sum=0
new_val=""
for i in s:
val=str(ord(i)-96)
new_val+=val
for i in range(0,k):
for j in new_val:
sum+=int(j)
new_val=str(sum)
sum=0
return new_val
|
sum-of-digits-of-string-after-convert
|
Simple Python Solution
|
sangam92
| 0
| 41
|
sum of digits of string after convert
| 1,945
| 0.612
|
Easy
| 27,432
|
https://leetcode.com/problems/sum-of-digits-of-string-after-convert/discuss/1367994/Python-3-%3A-or-99.59-or-Easy-Solution-or
|
class Solution:
def getLucky(self, s: str, k: int) -> int:
strg = ''.join(str(ord(i)-96) for i in s) # ord('a') = 97
for _ in range(k) :
strg = str(sum(int(j) for j in strg))
return strg
|
sum-of-digits-of-string-after-convert
|
Python 3 : | 99.59% | Easy Solution |
|
rohitkhairnar
| 0
| 99
|
sum of digits of string after convert
| 1,945
| 0.612
|
Easy
| 27,433
|
https://leetcode.com/problems/sum-of-digits-of-string-after-convert/discuss/1362329/Python-fast-and-pythonic
|
class Solution:
def getLucky(self, s: str, k: int) -> int:
tmp = ''
for i in s:
tmp += str(ord(i)-96)
for i in range(k):
tmp = str(sum([int(i) for i in tmp]))
return int(tmp)
|
sum-of-digits-of-string-after-convert
|
[Python] fast and pythonic
|
cruim
| 0
| 63
|
sum of digits of string after convert
| 1,945
| 0.612
|
Easy
| 27,434
|
https://leetcode.com/problems/sum-of-digits-of-string-after-convert/discuss/1361131/Python-Hash-table
|
class Solution:
def getLucky(self, s: str, k: int) -> int:
LETTERS = {letter: str(index) for index, letter in enumerate(ascii_letters, start=1)}
res = ''
for i, char in enumerate(s):
if char in LETTERS:
res+=(LETTERS[char])
for _ in range(k):
res = str(sum(int(x) for x in res))
return res
|
sum-of-digits-of-string-after-convert
|
Python Hash table
|
GasolineGuardian
| 0
| 30
|
sum of digits of string after convert
| 1,945
| 0.612
|
Easy
| 27,435
|
https://leetcode.com/problems/sum-of-digits-of-string-after-convert/discuss/1360802/Python-3-Hash-Table-Easy-understanding
|
class Solution:
def getLucky(self, s: str, k: int) -> int:
al = {"a":1,"b":2,"c":3,"d":4,"e":5,"f":6,"g":7,"h":8,"i":9,"j":1,"k":2,"l":3,"m":4,"n":5,"o":6,"p":7,"q":8,"r":9,"s":10,"t":2,"u":3,"v":4,"w":5,"x":6,"y":7,"z":8}
res, tmp = 0, 0
for c in s:
res += al[c]
for _ in range(k-1):
tmp = str(res)
res = 0
for char in tmp:
res += int(char)
return res
|
sum-of-digits-of-string-after-convert
|
Python 3, Hash Table, Easy-understanding
|
lucliu
| 0
| 60
|
sum of digits of string after convert
| 1,945
| 0.612
|
Easy
| 27,436
|
https://leetcode.com/problems/largest-number-after-mutating-substring/discuss/1360736/Python3-greedy
|
class Solution:
def maximumNumber(self, num: str, change: List[int]) -> str:
num = list(num)
on = False
for i, ch in enumerate(num):
x = int(ch)
if x < change[x]:
on = True
num[i] = str(change[x])
elif x > change[x] and on: break
return "".join(num)
|
largest-number-after-mutating-substring
|
[Python3] greedy
|
ye15
| 7
| 572
|
largest number after mutating substring
| 1,946
| 0.346
|
Medium
| 27,437
|
https://leetcode.com/problems/largest-number-after-mutating-substring/discuss/2836414/Python3-Greedy-One-Pass
|
class Solution:
def maximumNumber(self, num: str, change: List[int]) -> str:
# make a list from the string for a mutable datatype
num = list(num)
# go through the number and start mutating as soon as
# we hit a number that becomes bigger
# mark as mutating since we started mutation
# end the loop if we encounter a number that would
# get smaller by mutating
mutated = False
for idx, n in enumerate(num):
# get the current digit
n = int(n)
if change[n] > n:
num[idx] = str(change[n])
mutated = True
elif change[n] < n and mutated:
break
return "".join(num)
|
largest-number-after-mutating-substring
|
[Python3] - Greedy One-Pass
|
Lucew
| 0
| 1
|
largest number after mutating substring
| 1,946
| 0.346
|
Medium
| 27,438
|
https://leetcode.com/problems/largest-number-after-mutating-substring/discuss/2783872/python3-easy-explanation
|
class Solution:
def maximumNumber(self, num: str, change: List[int]) -> str:
temp = int(num)
num = list(num)
flag = True
for i,k in enumerate(num):
if int(k) == int(change[int(k)]):
continue
elif int(k) < int(change[int(k)]):
num[i] = str(change[int(k)])
flag = False
elif flag == False:
return ''.join(num)
return ''.join(num)
|
largest-number-after-mutating-substring
|
python3, easy explanation
|
indrakhatua23
| 0
| 5
|
largest number after mutating substring
| 1,946
| 0.346
|
Medium
| 27,439
|
https://leetcode.com/problems/largest-number-after-mutating-substring/discuss/2689552/Easy-Approach-or-Beginner's-Friendly-Solution-or-Python
|
class Solution(object):
def maximumNumber(self, num, change):
ans, flag = '', False
for i in range(len(num)):
if int(num[i]) == change[int(num[i])] and not(flag):
ans += num[i]
continue
if int(num[i]) <= change[int(num[i])]:
ans += str(change[int(num[i])])
flag = True
else:
if flag:
ans += num[i]
break
ans += num[i]
return ans + num[i+1:]
|
largest-number-after-mutating-substring
|
Easy Approach | Beginner's Friendly Solution | Python
|
its_krish_here
| 0
| 3
|
largest number after mutating substring
| 1,946
| 0.346
|
Medium
| 27,440
|
https://leetcode.com/problems/largest-number-after-mutating-substring/discuss/2616761/Python-solution-oror-Clean-code-with-comments-(Faster-than-96-solutions)
|
class Solution:
def maximumNumber(self, num: str, change: List[int]) -> str:
# Converted nums to list
nums = list(num)
updated = False
for i in range(len(nums)):
# Get value at ith index
val = int(nums[i])
# If we can change it to greater value then swap and updated is True
if(val < change[val]):
nums[i] = str(change[val])
updated = True
# If we have already updated to a greater value but that is now not valid then break
# Since, We can mutate only one substring
elif(val > change[val] and updated is True):
break
return ''.join(nums)
|
largest-number-after-mutating-substring
|
Python solution || Clean code with comments (Faster than 96% solutions)
|
vanshika_2507
| 0
| 5
|
largest number after mutating substring
| 1,946
| 0.346
|
Medium
| 27,441
|
https://leetcode.com/problems/largest-number-after-mutating-substring/discuss/2093733/python-simple-solution
|
class Solution:
def maximumNumber(self, num: str, change: List[int]) -> str:
res = ''
startChange = False
for idx,i in enumerate(num):
val = int(i)
if change[val] > val:
startChange = True
res += str(change[val])
else:
if startChange and not change[val] == val:
break
res += str(val)
return res + num[idx:] if len(res) < len(num) else res
|
largest-number-after-mutating-substring
|
python simple solution
|
Nk0311
| 0
| 58
|
largest number after mutating substring
| 1,946
| 0.346
|
Medium
| 27,442
|
https://leetcode.com/problems/maximum-compatibility-score-sum/discuss/1360746/Python3-permutations
|
class Solution:
def maxCompatibilitySum(self, students: List[List[int]], mentors: List[List[int]]) -> int:
m = len(students)
score = [[0]*m for _ in range(m)]
for i in range(m):
for j in range(m):
score[i][j] = sum(x == y for x, y in zip(students[i], mentors[j]))
ans = 0
for perm in permutations(range(m)):
ans = max(ans, sum(score[i][j] for i, j in zip(perm, range(m))))
return ans
|
maximum-compatibility-score-sum
|
[Python3] permutations
|
ye15
| 16
| 1,100
|
maximum compatibility score sum
| 1,947
| 0.609
|
Medium
| 27,443
|
https://leetcode.com/problems/maximum-compatibility-score-sum/discuss/1360746/Python3-permutations
|
class Solution:
def maxCompatibilitySum(self, students: List[List[int]], mentors: List[List[int]]) -> int:
m = len(students)
score = [[0]*m for _ in range(m)]
for i in range(m):
for j in range(m):
score[i][j] = sum(x == y for x, y in zip(students[i], mentors[j]))
@cache
def fn(mask, j):
"""Return max score of assigning students in mask to first j mentors."""
ans = 0
for i in range(m):
if not mask & (1<<i):
ans = max(ans, fn(mask^(1<<i), j-1) + score[i][j])
return ans
return fn(1<<m, m-1)
|
maximum-compatibility-score-sum
|
[Python3] permutations
|
ye15
| 16
| 1,100
|
maximum compatibility score sum
| 1,947
| 0.609
|
Medium
| 27,444
|
https://leetcode.com/problems/maximum-compatibility-score-sum/discuss/2839489/Python-(Simple-DP-%2B-Bitmasking)
|
class Solution:
def maxCompatibilitySum(self, students, mentors):
n, dict1 = len(students), defaultdict(int)
for i in range(n):
for j in range(n):
dict1[i,j] = sum(k == l for k,l in zip(students[i],mentors[j]))
@lru_cache(None)
def dfs(i,mask):
if i == n:
return 0
return max(dfs(i+1,mask-(1<<j)) + dict1[i,j] for j in range(n) if (1<<j)&mask)
return dfs(0,(1<<n)-1)
|
maximum-compatibility-score-sum
|
Python (Simple DP + Bitmasking)
|
rnotappl
| 0
| 1
|
maximum compatibility score sum
| 1,947
| 0.609
|
Medium
| 27,445
|
https://leetcode.com/problems/maximum-compatibility-score-sum/discuss/2775292/Backtracking-intuitive-solution-with-description-(beats-58-in-runtime-and-92-in-memory)
|
class Solution:
def backtrack(self, current_score, current_student, available_mentors, n, all_scores):
if current_student == n:
return current_score
return max([
self.backtrack(
current_score + all_scores[(current_student, mentor)],
current_student + 1,
available_mentors - {mentor},
n,
all_scores
)
for mentor in available_mentors
])
def maxCompatibilitySum(self, students: List[List[int]], mentors: List[List[int]]) -> int:
all_scores = {
(idx, jdx): sum([
int(student_answer == mentor_answer)
for student_answer, mentor_answer
in zip(students[idx], mentors[jdx])
])
for idx in range(len(students))
for jdx in range(len(mentors))
}
return self.backtrack(0, 0, set(range(len(students))), len(students), all_scores)
|
maximum-compatibility-score-sum
|
Backtracking intuitive solution with description (beats 58% in runtime and 92% in memory)
|
henrique
| 0
| 4
|
maximum compatibility score sum
| 1,947
| 0.609
|
Medium
| 27,446
|
https://leetcode.com/problems/maximum-compatibility-score-sum/discuss/2464597/Python3-or-Solved-Using-Recursion-%2B-Backtracking-With-Boolean-Flag-Array
|
class Solution:
#Time-Complexity: O((m ^ m) * n), since branching factor in worst case is m and worst case height is #m for rec. tree and for each rec. call, we call compat_compute, which takes linear time with respect
#to n number of questions!
#Space-Complexity:O(m + m + m) -> O(m) space taken up due to call stack max depth, the boolean flag array, as well as the current built up pairings array!
def maxCompatibilitySum(self, students: List[List[int]], mentors: List[List[int]]) -> int:
#first define helper function!
def compat_compute(s, m):
student_answers = students[s]
mentor_answers = mentors[m]
ans = 0
for i in range(len(student_answers)):
if(student_answers[i] == mentor_answers[i]):
ans += 1
return ans
#m = number of students and mentors!
m = len(students)
#intialize boolean flag array for indices from 0 to m-1!
bool_arr = [0] * m
#we can define main recursive helper function!
#4 paramters:
#1. student : student index we are on making decision for to which mentor to pair up with!
#2.cur: 2d array pass by ref. which will be list of all pairings in form of
#[si, mi], where si index student paired up with mi mentor!
#3. s-> sum of compatability scores of all pair elements that are in cur so far locally!
#4. b-> boolean array which tells us which index pos mentor element is not paired yet
#and is available for use!
res = 0
def helper(student, cur, s, b):
nonlocal res, m
#base case: we formed m pairs!
if(len(cur) == m):
#update answer!
res = max(res, s)
return
#otherwise, we need to pair up current student with all available mentors
#simply check each and every mentor from index 0 to m-1!
for i in range(0, m, 1):
#check if this mentor is available!
if(b[i] == 1):
continue
#if mentor is available, simply pair up current student with ith mentor!
cur.append([student, i])
#also we need to get updated_compatibility score!
updated_score = s + compat_compute(student, i)
#also, set the flag on for ith mentor to not make available for use in furhter
#recursive calls!
b[i] = 1
#now, recurse and pass cur and b by ref while making choice
#for the next student +1 index student as well as with new updated_score
#for all pairings in cur in rec. call!
helper(student + 1, cur, updated_score, b)
#once rec. call finishes and returns, we need to update cur and b!
cur.pop()
b[i] = 0
helper(0, [], 0, bool_arr)
return res
|
maximum-compatibility-score-sum
|
Python3 | Solved Using Recursion + Backtracking With Boolean Flag Array
|
JOON1234
| 0
| 19
|
maximum compatibility score sum
| 1,947
| 0.609
|
Medium
| 27,447
|
https://leetcode.com/problems/maximum-compatibility-score-sum/discuss/1376812/Python3-or-Backtracking
|
class Solution:
def maxCompatibilitySum(self, students: List[List[int]], mentors: List[List[int]]) -> int:
self.ans=0
self.solve(0,students,mentors,0)
return self.ans
def solve(self,strt,students,mentors,points):
if mentors==[]:
self.ans=max(self.ans,points)
return self.ans
for i in range(strt,len(students)):
points+=self.mapping(students[strt],mentors[i])
self.solve(strt,students[:strt]+students[strt+1:],mentors[:i]+mentors[i+1:],points)
points-=self.mapping(students[strt],mentors[i])
return
def mapping(self,students,mentors):
cnt=0
for i in range(len(students)):
if students[i]==mentors[i]:
cnt+=1
return cnt
|
maximum-compatibility-score-sum
|
Python3 | Backtracking
|
swapnilsingh421
| 0
| 86
|
maximum compatibility score sum
| 1,947
| 0.609
|
Medium
| 27,448
|
https://leetcode.com/problems/maximum-compatibility-score-sum/discuss/1370403/Permutation-on-sets
|
class Solution:
def maxCompatibilitySum(self, students: List[List[int]], mentors: List[List[int]]) -> int:
set_students = [set((i + 1) if v else -(i + 1)
for i, v in enumerate(row)) for row in students]
set_mentors = [set((i + 1) if v else -(i + 1)
for i, v in enumerate(row)) for row in mentors]
return max(sum(len(s & m) for s, m in zip(p, set_mentors))
for p in permutations(set_students))
|
maximum-compatibility-score-sum
|
Permutation on sets
|
EvgenySH
| 0
| 63
|
maximum compatibility score sum
| 1,947
| 0.609
|
Medium
| 27,449
|
https://leetcode.com/problems/maximum-compatibility-score-sum/discuss/1362778/Python-3-Backtracking
|
class Solution:
def maxCompatibilitySum(self, S: List[List[int]], M: List[List[int]]) -> int:
self.used = [0] * 9
self.ans = 0
self.m, self.n = len(M), len(M[0])
def dfs(students, mentors, index, score):
if index == self.m:
self.ans = max(self.ans, score)
return
for i in range(self.m):
if self.used[i]: continue
self.used[i] = 1
s = 0
for k in range(self.n):
s += students[index][k] == mentors[i][k]
dfs(students, mentors, index+1, score+s)
self.used[i] = 0
dfs(S, M, 0, 0)
return self.ans
|
maximum-compatibility-score-sum
|
[Python 3] Backtracking
|
marsii10170613
| 0
| 70
|
maximum compatibility score sum
| 1,947
| 0.609
|
Medium
| 27,450
|
https://leetcode.com/problems/maximum-compatibility-score-sum/discuss/1361000/Python-or-Brute-force-in-DFSor-Used-the-concept-of-permutating-number-in-array
|
class Solution:
def maxCompatibilitySum(self, students: List[List[int]], mentors: List[List[int]]) -> int:
return self.mySoldfs(students, mentors, set(), 0)
def mySoldfs(self, students, mentors, hashSet, indS):
if indS>=len(students):
return 0
res=0
maxx=0
for i in range(len(mentors)):
if i not in hashSet:
res = self.match(students[indS], mentors[i])
hashSet.add(i)
maxx = max(maxx, res+self.mySoldfs(students, mentors, hashSet, indS+1))
hashSet.remove(i)
return maxx
def match(self, x, y):
res=0
i=j=0
while(i<len(x)and j<len(y)):
if x[i]==y[j]:
res+=1
i+=1;
j+=1;
return res
|
maximum-compatibility-score-sum
|
Python | Brute force in DFS| Used the concept of permutating number in array
|
gaurav2697
| 0
| 65
|
maximum compatibility score sum
| 1,947
| 0.609
|
Medium
| 27,451
|
https://leetcode.com/problems/delete-duplicate-folders-in-system/discuss/1360749/Python3-serialize-sub-trees
|
class Solution:
def deleteDuplicateFolder(self, paths: List[List[str]]) -> List[List[str]]:
paths.sort()
tree = {"#": -1}
for i, path in enumerate(paths):
node = tree
for x in path: node = node.setdefault(x, {})
node["#"] = i
seen = {}
mark = set()
def fn(n):
"""Return serialized value of sub-tree rooted at n."""
if len(n) == 1: return "$" # leaf node
vals = []
for k in n:
if k != "#": vals.append(f"${k}${fn(n[k])}")
hs = "".join(vals)
if hs in seen:
mark.add(n["#"])
mark.add(seen[hs])
if hs != "$": seen[hs] = n["#"]
return hs
fn(tree)
ans = []
stack = [tree]
while stack:
n = stack.pop()
if n["#"] >= 0: ans.append(paths[n["#"]])
for k in n:
if k != "#" and n[k]["#"] not in mark: stack.append(n[k])
return ans
|
delete-duplicate-folders-in-system
|
[Python3] serialize sub-trees
|
ye15
| 4
| 469
|
delete duplicate folders in system
| 1,948
| 0.579
|
Hard
| 27,452
|
https://leetcode.com/problems/delete-duplicate-folders-in-system/discuss/1361068/Python3-Augmented-Trie
|
class Solution:
def deleteDuplicateFolder(self, paths: List[List[str]]) -> List[List[str]]:
leaves = []
trie_lambda = lambda: collections.defaultdict(trie_lambda)
trie = trie_lambda()
trie['*'] = trie['**'] = '*'
for p in paths:
t = trie
for f in p:
parent, t = t, t[f]
t['*'] = parent
t['**'] = f
def traverse(t):
if len(t) == 2:
leaves.append(t)
else:
for k, v in t.items():
if k[0] != '*':
traverse(v)
traverse(trie)
leaf_ids = set(id(leaf) for leaf in leaves)
candidates = {id(leaf['*']):leaf['*'] for leaf in leaves}
while candidates:
new = {}
dup = collections.defaultdict(list)
for cand in candidates.values():
if any(id(v) not in leaf_ids for k, v in cand.items() if k[0] != '*'):
continue
dup[','.join(sorted(cand.keys()))].append(cand)
for k, v in dup.items():
if len(v) > 1:
for cand in v:
f = cand['**']
parent = cand['*']
del parent[f]
leaf_ids.add(id(parent['*' + f]))
new[id(parent)] = parent
candidates = new
path = []
ans = []
def dfs(t):
for f in t:
if f[0] != '*':
path.append(f)
ans.append(list(path))
dfs(t[f])
path.pop()
dfs(trie)
return ans
|
delete-duplicate-folders-in-system
|
[Python3] Augmented Trie
|
chuan-chih
| 1
| 138
|
delete duplicate folders in system
| 1,948
| 0.579
|
Hard
| 27,453
|
https://leetcode.com/problems/three-divisors/discuss/1375468/Python3-1-line
|
class Solution:
def isThree(self, n: int) -> bool:
return sum(n%i == 0 for i in range(1, n+1)) == 3
|
three-divisors
|
[Python3] 1-line
|
ye15
| 14
| 866
|
three divisors
| 1,952
| 0.572
|
Easy
| 27,454
|
https://leetcode.com/problems/three-divisors/discuss/1375468/Python3-1-line
|
class Solution:
def isThree(self, n: int) -> bool:
if n == 1: return False # edge case
x = int(sqrt(n))
if x*x != n: return False
for i in range(2, int(sqrt(x))+1):
if x % i == 0: return False
return True
|
three-divisors
|
[Python3] 1-line
|
ye15
| 14
| 866
|
three divisors
| 1,952
| 0.572
|
Easy
| 27,455
|
https://leetcode.com/problems/three-divisors/discuss/1397244/Explained-Python-Solution-using-primes-O(1)-or-Faster-than-99
|
class Solution:
def isThree(self, n: int) -> bool:
primes = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97};
return sqrt(n) in primes
|
three-divisors
|
Explained Python Solution using primes, O(1) | Faster than 99%
|
the_sky_high
| 7
| 333
|
three divisors
| 1,952
| 0.572
|
Easy
| 27,456
|
https://leetcode.com/problems/three-divisors/discuss/1777316/Python3-or-Simple-Solution-or-89-lesser-memory-or-O(n)-Time-and-O(1)-Space
|
class Solution:
def isThree(self, n: int) -> bool:
c = 0
for i in range(1,n+1):
if n/i == int(n/i):
c += 1
if c>3:
return False
return c == 3
|
three-divisors
|
โPython3 | Simple Solution | 89% lesser memory | O(n) Time and O(1) Space
|
Coding_Tan3
| 2
| 129
|
three divisors
| 1,952
| 0.572
|
Easy
| 27,457
|
https://leetcode.com/problems/three-divisors/discuss/1568087/Python-Solution-oror-94-faster
|
class Solution:
def isThree(self, n: int) -> bool:
#check if exactly 1 divisor exists apart from 1 and number itself
if n <= 3:
return False
count = 0
for i in range(2,n//2 + 1):
#print(i)
if n % i == 0:
count += 1
if count > 1:
return False
if count == 0:
return False
return True
|
three-divisors
|
Python Solution || 94% faster
|
s_m_d_29
| 2
| 125
|
three divisors
| 1,952
| 0.572
|
Easy
| 27,458
|
https://leetcode.com/problems/three-divisors/discuss/1375810/The-really-Fastest-Solution-Python
|
class Solution:
def isThree(self, n):
return n in {4, 9, 25, 49, 121, 169, 289, 361, 529, 841, 961, 1369, 1681, 1849, 2209, 2809, 3481, 3721, 4489, 5041, 5329, 6241, 6889, 7921, 9409}
|
three-divisors
|
The really Fastest Solution Python
|
tenart
| 2
| 124
|
three divisors
| 1,952
| 0.572
|
Easy
| 27,459
|
https://leetcode.com/problems/three-divisors/discuss/1375810/The-really-Fastest-Solution-Python
|
class Solution:
def isThree(self, n):
answers = [4, 9, 25, 49, 121, 169, 289, 361, 529, 841, 961, 1369, 1681, 1849, 2209, 2809, 3481, 3721, 4489, 5041, 5329, 6241, 6889, 7921, 9409]
while True:
size = len(answers)
if size == 1:
return answers[0] == n
elif size == 0:
return False
mp = size // 2
if answers[mp] == n:
return True
elif answers[mp] > n:
answers = answers[:mp]
else:
answers = answers[mp + 1:]
|
three-divisors
|
The really Fastest Solution Python
|
tenart
| 2
| 124
|
three divisors
| 1,952
| 0.572
|
Easy
| 27,460
|
https://leetcode.com/problems/three-divisors/discuss/2807929/Efficient-and-Easy-Solution
|
class Solution:
def isThree(self, n: int) -> bool:
count = 0
i = 2
while i<(n//2+1):
if n%i==0:
count+=1
i+=1
if count == 1:
return True
else:
return False
|
three-divisors
|
Efficient and Easy Solution
|
shashank00818
| 0
| 4
|
three divisors
| 1,952
| 0.572
|
Easy
| 27,461
|
https://leetcode.com/problems/three-divisors/discuss/2786713/Just-one-line-(Python)
|
class Solution:
def isThree(self, n: int) -> bool:
return len([k for k in range(1, n+1) if n%k == 0]) == 3
|
three-divisors
|
Just one line (Python)
|
DNST
| 0
| 2
|
three divisors
| 1,952
| 0.572
|
Easy
| 27,462
|
https://leetcode.com/problems/three-divisors/discuss/2663444/Simple-Solution-for-Python-(Brute-Force)
|
class Solution:
def isThree(self, n: int) -> bool:
c=0
for i in range(2,n//2+1):
if n%i==0:
c+=1
if c==2:
return False
if c==1:
return True
else:
return False
|
three-divisors
|
Simple Solution for Python (Brute Force)
|
Hashir311
| 0
| 2
|
three divisors
| 1,952
| 0.572
|
Easy
| 27,463
|
https://leetcode.com/problems/three-divisors/discuss/2645250/Easy-solution-with-one-loop
|
class Solution:
def isThree(self, n: int) -> bool:
c=1
for i in range(2,n+1):
if n%i==0:
c+=1
return c==3
|
three-divisors
|
Easy solution with one loop
|
abhint1
| 0
| 2
|
three divisors
| 1,952
| 0.572
|
Easy
| 27,464
|
https://leetcode.com/problems/three-divisors/discuss/2645226/Python-Simple-and-Easy-Solution
|
class Solution:
def isThree(self, n: int) -> bool:
c = 1
for i in range(2,n+1):
if n % i == 0: c += 1
return c == 3
|
three-divisors
|
Python Simple and Easy Solution
|
SouravSingh49
| 0
| 17
|
three divisors
| 1,952
| 0.572
|
Easy
| 27,465
|
https://leetcode.com/problems/three-divisors/discuss/2276477/Easy-Python-optimised-Brute-Force-solution.....
|
class Solution:
def isThree(self, n: int) -> bool:
count=2
if n==4:
return True
elif n%2==0:
return False
else:
for i in range(2,n+1//2):
if count>3:
return False
if n%i==0:
count+=1
return count==3
|
three-divisors
|
Easy Python optimised Brute Force solution.....
|
guneet100
| 0
| 23
|
three divisors
| 1,952
| 0.572
|
Easy
| 27,466
|
https://leetcode.com/problems/three-divisors/discuss/2003976/Python-Clean-and-Simple!
|
class Solution:
def isThree(self, n):
d = 0
for i in range(1,n+1):
if n % i == 0: d += 1
if d > 3: return False
return d == 3
|
three-divisors
|
Python - Clean and Simple!
|
domthedeveloper
| 0
| 89
|
three divisors
| 1,952
| 0.572
|
Easy
| 27,467
|
https://leetcode.com/problems/three-divisors/discuss/2003976/Python-Clean-and-Simple!
|
class Solution:
def isThree(self, n):
return 3 == sum(not n%i for i in range(1,n+1))
|
three-divisors
|
Python - Clean and Simple!
|
domthedeveloper
| 0
| 89
|
three divisors
| 1,952
| 0.572
|
Easy
| 27,468
|
https://leetcode.com/problems/three-divisors/discuss/1860680/Python-O(n)-complexity-easy-solution
|
class Solution:
def isThree(self, n: int) -> bool:
count_div = 2
for i in range(2, n):
if n % i == 0:
count_div += 1
if count_div > 3:
return False
if count_div != 3:
return False
return True
|
three-divisors
|
Python O(n) complexity easy solution
|
alishak1999
| 0
| 39
|
three divisors
| 1,952
| 0.572
|
Easy
| 27,469
|
https://leetcode.com/problems/three-divisors/discuss/1818851/Easy-solution-with-only-5-line-of-code
|
class Solution:
def isThree(self, n: int) -> bool:
counter = 1
for i in range(1,n):
if n % i == 0:
counter += 1
return counter == 3
```
|
three-divisors
|
Easy solution with only 5 line of code
|
fazliddindehkanoff
| 0
| 29
|
three divisors
| 1,952
| 0.572
|
Easy
| 27,470
|
https://leetcode.com/problems/three-divisors/discuss/1645055/Fast-python-solution
|
class Solution:
def isThree(self, n: int) -> bool:
def isprime(v):
if v < 2:
return False
if v in (2, 3):
return True
if v % 2 == 0 or v % 3 == 0:
return False
i = 5
w = 2
while i*i <= v:
if v % i == 0:
return False
i += w
w = 6 - w
return True
def issquare(v):
return v == int(v**.5)**2
return issquare(n) and isprime(int(n**.5))
|
three-divisors
|
Fast python solution
|
emwalker
| 0
| 85
|
three divisors
| 1,952
| 0.572
|
Easy
| 27,471
|
https://leetcode.com/problems/three-divisors/discuss/1590682/Python-3-easy-solution
|
class Solution:
def isThree(self, n: int) -> bool:
sqrt = math.sqrt(n)
if sqrt % 1 == 0 and n > 1:
for i in range(2, int(sqrt)):
if n % i == 0:
return False
return True
return False
|
three-divisors
|
Python 3 easy solution
|
dereky4
| 0
| 80
|
three divisors
| 1,952
| 0.572
|
Easy
| 27,472
|
https://leetcode.com/problems/three-divisors/discuss/1550986/Set-for-divisors-99-speed
|
class Solution:
def isThree(self, n: int) -> bool:
divisors = {1, n}
for i in range(2, int(pow(n, 0.5)) + 1):
if not n % i:
divisors.add(i)
divisors.add(n // i)
if len(divisors) > 3:
return False
return len(divisors) == 3
|
three-divisors
|
Set for divisors, 99% speed
|
EvgenySH
| 0
| 39
|
three divisors
| 1,952
| 0.572
|
Easy
| 27,473
|
https://leetcode.com/problems/three-divisors/discuss/1390735/Python-with-explanation
|
class Solution:
def isThree(self, n: int) -> bool:
if n == 4:
return True
if n < 4 or not n % 2:
return False
candidate = n**0.5
if candidate.is_integer():
for i in range(3, int(candidate**0.5) + 1, 2):
if i != candidate and not candidate % i:
return False
else:
return False
return True
|
three-divisors
|
[Python] with explanation
|
cruim
| 0
| 49
|
three divisors
| 1,952
| 0.572
|
Easy
| 27,474
|
https://leetcode.com/problems/three-divisors/discuss/1382422/PYTHON3-%3A-or-95.52-or-O(sqrt(n))-or
|
class Solution:
def isThree(self, n: int) -> bool:
count = 0
for i in range(1, int(math.sqrt(n)) + 1) :
if n % i == 0 :
if n / i == i : # for distinct divisors
count += 1
else :
count += 2
if count > 3 : return False
return count == 3
|
three-divisors
|
PYTHON3 : | 95.52% | O(sqrt(n)) |
|
rohitkhairnar
| 0
| 126
|
three divisors
| 1,952
| 0.572
|
Easy
| 27,475
|
https://leetcode.com/problems/three-divisors/discuss/1380082/Python-3-or-Check-for-1-divisor-in-2-n2.
|
class Solution:
def isThree(self, n: int) -> bool:
count = 0
for i in range(2, n // 2 + 1):
if n % i == 0:
count += 1
if count > 1:
return False
return count == 1
|
three-divisors
|
[Python 3] | Check for 1 divisor in [2, n/2].
|
mb557x
| 0
| 47
|
three divisors
| 1,952
| 0.572
|
Easy
| 27,476
|
https://leetcode.com/problems/three-divisors/discuss/1375918/100-speed-100-memory
|
class Solution:
def isThree(self, n: int) -> bool:
if n < 3:
return False
count = 0
for i in range(2, n // 2 + 1):
if n % i == 0:
count += 1
if count > 1:
return False
for j in range(2, i // 2 + 1):
if i % j == 0:
return False
return count > 0
|
three-divisors
|
100% speed, 100% memory
|
JulianaYo
| 0
| 35
|
three divisors
| 1,952
| 0.572
|
Easy
| 27,477
|
https://leetcode.com/problems/three-divisors/discuss/1375725/Python-simple-solution
|
class Solution:
def isThree(self, n):
root_number, remainder = divmod(sqrt(n), 1)
if remainder or n == 1:
return False
root_number = int(root_number)
for i in range(2, root_number // 2 + 1):
if root_number % i == 0:
return False
return True
|
three-divisors
|
Python simple solution
|
tenart
| 0
| 44
|
three divisors
| 1,952
| 0.572
|
Easy
| 27,478
|
https://leetcode.com/problems/three-divisors/discuss/1375725/Python-simple-solution
|
class Solution(object):
def isThree(self, n):
"""
:type n: int
:rtype: bool
"""
count = 0
for i in range(2, n // 2 + 1):
if n % i == 0:
count += 1
if count > 1:
return False
return count == 1
|
three-divisors
|
Python simple solution
|
tenart
| 0
| 44
|
three divisors
| 1,952
| 0.572
|
Easy
| 27,479
|
https://leetcode.com/problems/three-divisors/discuss/1375621/Python-Brute-Force
|
class Solution:
def isThree(self, n: int) -> bool:
count = 2
for i in range(2,n):
if n%i == 0:
count+=1
if count > 3:
return False
return count == 3
|
three-divisors
|
[Python] Brute Force
|
ritika99
| 0
| 19
|
three divisors
| 1,952
| 0.572
|
Easy
| 27,480
|
https://leetcode.com/problems/three-divisors/discuss/1442442/Python-2-lines
|
class Solution:
def isThree(self, n: int) -> bool:
is_div = [i * (n//i) == n for i in range(2, int(math.sqrt(n))+1)]
return sum(is_div) == 1 and is_div[-1] == 1
|
three-divisors
|
Python, 2 lines
|
blue_sky5
| -2
| 63
|
three divisors
| 1,952
| 0.572
|
Easy
| 27,481
|
https://leetcode.com/problems/maximum-number-of-weeks-for-which-you-can-work/discuss/1375390/Python-Solution-with-detailed-explanation-and-proof-and-common-failure-analysis
|
class Solution:
def numberOfWeeks(self, milestones: List[int]) -> int:
_sum, _max = sum(milestones), max(milestones)
# (_sum - _max) is the sum of milestones from (2) the rest of projects, if True, we can form another project with the same amount of milestones as (1)
# can refer to the section `Why the greedy strategy works?` for the proof
if _sum - _max >= _max:
return _sum
return 2 * (_sum - _max) + 1 # start from the project with most milestones (_sum - _max + 1) and work on the the rest of milestones (_sum - _max)
|
maximum-number-of-weeks-for-which-you-can-work
|
[Python] Solution with detailed explanation & proof & common failure analysis
|
fishballLin
| 232
| 7,200
|
maximum number of weeks for which you can work
| 1,953
| 0.391
|
Medium
| 27,482
|
https://leetcode.com/problems/maximum-number-of-weeks-for-which-you-can-work/discuss/1375479/O(n)
|
class Solution:
def numberOfWeeks(self, m: List[int]) -> int:
return min(sum(m), 2 * (sum(m) - max(m)) + 1)
|
maximum-number-of-weeks-for-which-you-can-work
|
O(n)
|
votrubac
| 44
| 3,100
|
maximum number of weeks for which you can work
| 1,953
| 0.391
|
Medium
| 27,483
|
https://leetcode.com/problems/maximum-number-of-weeks-for-which-you-can-work/discuss/1375481/Python3-2-line
|
class Solution:
def numberOfWeeks(self, milestones: List[int]) -> int:
m, s = max(milestones), sum(milestones)
return s - max(0, 2*m - s - 1)
|
maximum-number-of-weeks-for-which-you-can-work
|
[Python3] 2-line
|
ye15
| 1
| 98
|
maximum number of weeks for which you can work
| 1,953
| 0.391
|
Medium
| 27,484
|
https://leetcode.com/problems/maximum-number-of-weeks-for-which-you-can-work/discuss/1375671/Python-Solution
|
class Solution:
def numberOfWeeks(self, milestones: List[int]) -> int:
'''
[1 2 5]
largest_num = 5
rest_sm = 3(sum(milestones)-max(milestones))
ans = rest_sum*2
if sum(milestones)-ans >= 1:
return count+1
return sum(milestones) #becuase if all milestones are achieved then it will be simply sum of all
else:
return count + 1
'''
largMilestone = max(milestones)
sumOfAllMilestones = sum(milestones)
sumOfRestMilestone = sumOfAllMilestones - largMilestone
val = sumOfRestMilestone*2
if sumOfAllMilestones - val >= 1:
return val+1
return sumOfAllMilestones
|
maximum-number-of-weeks-for-which-you-can-work
|
Python Solution
|
SaSha59
| 0
| 75
|
maximum number of weeks for which you can work
| 1,953
| 0.391
|
Medium
| 27,485
|
https://leetcode.com/problems/maximum-number-of-weeks-for-which-you-can-work/discuss/1375617/Python-Simple-solution.
|
class Solution(object):
def numberOfWeeks(self, milestones):
"""
:type milestones: List[int]
:rtype: int
"""
milestones.sort()
s = sum(milestones[:-1])
if milestones[-1] > s:
return s * 2 + 1
else:
return s + milestones[-1]
|
maximum-number-of-weeks-for-which-you-can-work
|
Python Simple solution.
|
tenart
| 0
| 49
|
maximum number of weeks for which you can work
| 1,953
| 0.391
|
Medium
| 27,486
|
https://leetcode.com/problems/minimum-garden-perimeter-to-collect-enough-apples/discuss/1589250/Explanation-for-Intuition-behind-the-math-formula-derivation
|
class Solution:
def minimumPerimeter(self, nap: int) -> int:
# here for n = 2 , there are two series :
# (1) Diagnal points for n=3 , diagnal apples = 2*n = 6
# (2) there is series = 2,3,3 = 2+ (sigma(3)-sigma(2))*2
# how to solve:
# here 3 = sigma(n+(n-1))-sigma(n) = sigma(2*n-1)-sigma(n) = 0.5*2n*(2n-1)-0.5*n*n-1
# (3) so our final 2,3,3 = 3*2+2 = (0.5*2n*(2n-1)-0.5*n*n-1)*2+n
# (4) so final 2,3,3 = 3*n*n - 2*n
# (5) we have 4 times repitation of (2,3,3) = 4*(2,3,3) = 4*(3*n*n - 2*n) = 12*n*n - 8*n
# (6) we have 4 diagnal points so their sum(4 diagnal) = 4*(2*n)
# (7) so final sum(total) = 4 diagnal sum + 4(2,3,3) = 4(2*n) + 12*n*n - 8*n = 12*n*n
# so at nth distance we have total 12*n*n apples at the circumfrance
# so net sum = sigma(12*n*n) = 2*n*(n+1)*(2*n+1)
n=1
val=2*n*(n+1)*(2*n+1)
while(val<nap):
n+=1
val=val=2*n*(n+1)*(2*n+1)
return n*8
|
minimum-garden-perimeter-to-collect-enough-apples
|
Explanation for Intuition behind the math formula derivation
|
martian_rock
| 2
| 123
|
minimum garden perimeter to collect enough apples
| 1,954
| 0.53
|
Medium
| 27,487
|
https://leetcode.com/problems/minimum-garden-perimeter-to-collect-enough-apples/discuss/1500436/Binary-Search-with-Math-or-5-Solutions-or-Explained-or-Python3
|
class Solution:
def minimumPerimeter(self, neededApples: int) -> int:
A = neededApples
x = 0
curr = 0
while curr < A:
temp = 0
x += 1
for i in range(1,x):
temp += ((x+i)*2)
curr += 4*(temp + 3*x)
return 4*(2*x)
|
minimum-garden-perimeter-to-collect-enough-apples
|
Binary Search with Math | 5 Solutions | Explained | Python3
|
Sanjaychandak95
| 2
| 124
|
minimum garden perimeter to collect enough apples
| 1,954
| 0.53
|
Medium
| 27,488
|
https://leetcode.com/problems/minimum-garden-perimeter-to-collect-enough-apples/discuss/1500436/Binary-Search-with-Math-or-5-Solutions-or-Explained-or-Python3
|
class Solution:
def minimumPerimeter(self, neededApples: int) -> int:
A = neededApples
x = 0
curr = 0
while curr < A:
temp = 0
x += 1
# for i in range(1,x):
# temp += ((x+i)*2)
temp = 2*(x-1)*x + x*(x-1)
curr += 4*(temp + 3*x)
return 4*(2*x)
|
minimum-garden-perimeter-to-collect-enough-apples
|
Binary Search with Math | 5 Solutions | Explained | Python3
|
Sanjaychandak95
| 2
| 124
|
minimum garden perimeter to collect enough apples
| 1,954
| 0.53
|
Medium
| 27,489
|
https://leetcode.com/problems/minimum-garden-perimeter-to-collect-enough-apples/discuss/1500436/Binary-Search-with-Math-or-5-Solutions-or-Explained-or-Python3
|
class Solution:
def minimumPerimeter(self, neededApples: int) -> int:
A = neededApples
x = 0
curr = 0
while curr < A:
temp = 0
x += 1
# temp = 2*(x-1)*x + x*(x-1)
# curr += 4*(temp + 3*x)
curr += 4*(3*x*x)
return 4*(2*x)
|
minimum-garden-perimeter-to-collect-enough-apples
|
Binary Search with Math | 5 Solutions | Explained | Python3
|
Sanjaychandak95
| 2
| 124
|
minimum garden perimeter to collect enough apples
| 1,954
| 0.53
|
Medium
| 27,490
|
https://leetcode.com/problems/minimum-garden-perimeter-to-collect-enough-apples/discuss/1500436/Binary-Search-with-Math-or-5-Solutions-or-Explained-or-Python3
|
class Solution:
def minimumPerimeter(self, neededApples: int) -> int:
A = neededApples
x = 0
curr = 0
while curr < A:
x += 1
curr = 2*(x)*(x+1)*(2*x+1)
return 4*(2*x)
|
minimum-garden-perimeter-to-collect-enough-apples
|
Binary Search with Math | 5 Solutions | Explained | Python3
|
Sanjaychandak95
| 2
| 124
|
minimum garden perimeter to collect enough apples
| 1,954
| 0.53
|
Medium
| 27,491
|
https://leetcode.com/problems/minimum-garden-perimeter-to-collect-enough-apples/discuss/1500436/Binary-Search-with-Math-or-5-Solutions-or-Explained-or-Python3
|
class Solution:
def minimumPerimeter(self, neededApples: int) -> int:
A = neededApples
x = 1
curr = 0
left = 0
right = min(A, 10**5)
while left<=right:
mid = left + (right-left)//2
curr = 2*(mid)*(mid+1)*(2*mid+1)
if curr >= A:
x = mid
right = mid-1
else:
left = mid+1
return 4*(2*x)
|
minimum-garden-perimeter-to-collect-enough-apples
|
Binary Search with Math | 5 Solutions | Explained | Python3
|
Sanjaychandak95
| 2
| 124
|
minimum garden perimeter to collect enough apples
| 1,954
| 0.53
|
Medium
| 27,492
|
https://leetcode.com/problems/minimum-garden-perimeter-to-collect-enough-apples/discuss/1375484/Python3-binary-search
|
class Solution:
def minimumPerimeter(self, neededApples: int) -> int:
lo, hi = 0, 10**5
while lo < hi:
mid = lo + hi >> 1
if 2*mid*(mid+1)*(2*mid+1) < neededApples: lo = mid + 1
else: hi = mid
return 8*lo
|
minimum-garden-perimeter-to-collect-enough-apples
|
[Python3] binary search
|
ye15
| 1
| 56
|
minimum garden perimeter to collect enough apples
| 1,954
| 0.53
|
Medium
| 27,493
|
https://leetcode.com/problems/minimum-garden-perimeter-to-collect-enough-apples/discuss/2747776/Python-or-Binary-Search-or-Sum-of-Squares
|
class Solution:
def minimumPerimeter(self, needed_apples: int) -> int:
def f(n):
n_2 = n * n
n_3 = n * n_2
apples = 4 * n_3 + 6 * n_2 + 2 * n
return apples >= needed_apples
def recherche_dichotomique (f, a, b):
l = a
r = b
while l < r:
m = l + (r - l) // 2
if f(m):
r = m
else:
l = m + 1
return l
return 8 * recherche_dichotomique(f, floor(pow(needed_apples / 12, 1/3)), ceil (pow(needed_apples / 4, 1/3)))
|
minimum-garden-perimeter-to-collect-enough-apples
|
Python | Binary Search | Sum of Squares
|
on_danse_encore_on_rit_encore
| 0
| 1
|
minimum garden perimeter to collect enough apples
| 1,954
| 0.53
|
Medium
| 27,494
|
https://leetcode.com/problems/minimum-garden-perimeter-to-collect-enough-apples/discuss/2096574/python-3-oror-binary-search-solution-oror-O(logn)O(1)
|
class Solution:
def minimumPerimeter(self, neededApples: int) -> int:
def apples(r):
return 2 * r * (r + 1) * (2*r + 1)
low, high = 1, neededApples
while low <= high:
mid = (low + high) // 2
total = apples(mid)
if total == neededApples:
return 8*mid
elif total < neededApples:
low = mid + 1
else:
high = mid - 1
return 8 * (mid + (total < neededApples))
|
minimum-garden-perimeter-to-collect-enough-apples
|
python 3 || binary search solution || O(logn)/O(1)
|
dereky4
| 0
| 93
|
minimum garden perimeter to collect enough apples
| 1,954
| 0.53
|
Medium
| 27,495
|
https://leetcode.com/problems/minimum-garden-perimeter-to-collect-enough-apples/discuss/1489005/Python-O(nlogn)-time-O(1)-solution-with-binary-search
|
class Solution:
def minimumPerimeter(self, n: int) -> int:
def condition(x):
return 2*x*(x+1)*(2*x+1) >= n
left, right = 1, n
while left < right:
mid = (left + right) // 2
if condition(mid):
right = mid
else:
left = mid + 1
return 8*left
|
minimum-garden-perimeter-to-collect-enough-apples
|
Python O(nlogn) time, O(1) solution with binary search
|
byuns9334
| 0
| 100
|
minimum garden perimeter to collect enough apples
| 1,954
| 0.53
|
Medium
| 27,496
|
https://leetcode.com/problems/minimum-garden-perimeter-to-collect-enough-apples/discuss/1440075/Python-3-or-Binary-Search-Math-O(logN)-or-Explanation
|
class Solution:
def minimumPerimeter(self, neededApples: int) -> int:
def ok(p):
center = p*(p+1)
base = center + (p*2+1)
last = base + (p*2+1) * (p-1)
total = (base+last) * p + center
return total >= neededApples
l, r = 1, int(1e5)
while l <= r:
mid = (l + r) // 2
if ok(mid):
r = mid - 1
else:
l = mid + 1
return 4*2*l
|
minimum-garden-perimeter-to-collect-enough-apples
|
Python 3 | Binary Search, Math, O(logN) | Explanation
|
idontknoooo
| 0
| 117
|
minimum garden perimeter to collect enough apples
| 1,954
| 0.53
|
Medium
| 27,497
|
https://leetcode.com/problems/minimum-garden-perimeter-to-collect-enough-apples/discuss/1376336/Easy-Python-Solution
|
class Solution:
def minimumPerimeter(self, neededApples: int) -> int:
total=0
for i in range(neededApples):
total+=12*(i+1)*(i+1)
if total>=neededApples:
return 8*(i+1)
|
minimum-garden-perimeter-to-collect-enough-apples
|
Easy Python Solution
|
Sneh17029
| 0
| 64
|
minimum garden perimeter to collect enough apples
| 1,954
| 0.53
|
Medium
| 27,498
|
https://leetcode.com/problems/count-number-of-special-subsequences/discuss/1387357/Simple-Python-with-comments.-One-pass-O(n)-with-O(1)-space
|
class Solution:
def countSpecialSubsequences(self, nums: List[int]) -> int:
total_zeros = 0 # number of subsequences of 0s so far
total_ones = 0 # the number of subsequences of 0s followed by 1s so far
total_twos = 0 # the number of special subsequences so far
M = 1000000007
for n in nums:
if n == 0:
# if we have found new 0 we can add it to any existing subsequence of 0s
# or use only this 0
total_zeros += (total_zeros + 1) % M
elif n == 1:
# if we have found new 1 we can add it to any existing subsequence of 0s or 0s and 1s
# to get a valid subsequence of 0s and 1s
total_ones += (total_zeros + total_ones) % M
else:
# if we have found new 2 we can add it to any existing subsequence of 0s and 1s 0r 0s,1s and 2s
# to get a valid subsequence of 0s,1s and 2s
total_twos += (total_ones + total_twos) % M
return total_twos % M
|
count-number-of-special-subsequences
|
Simple Python with comments. One pass O(n) with O(1) space
|
IlyaL
| 4
| 151
|
count number of special subsequences
| 1,955
| 0.513
|
Hard
| 27,499
|
Subsets and Splits
Top 2 Solutions by Upvotes
Identifies the top 2 highest upvoted Python solutions for each problem, providing insight into popular approaches.