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/perfect-squares/discuss/741367/Python-Recursive-DFS-and-BFS-Solutions-with-Comments! | class Solution:
def numSquares(self, n: int) -> int:
# Generate the squares.
sqrs = [i**2 for i in range(0, int(math.sqrt(n))+1)][::-1]
q = collections.deque([])
q.append((n, 0))
used = set()
while q:
# Get total and steps from our deque.
t, step = q.popleft()
for i in sqrs:
# We have found the answer!
if t - i == 0:
return step + 1
# If we need to deduct more from t
if t - i > 0:
# If we haven't already added what the next result we'll push to the deque
if (t - i, step + 1) not in used:
# Add our new t and increment our step
q.append((t - i, step + 1))
used.add((t - i, step + 1))
return -1 | perfect-squares | Python Recursive DFS and BFS Solutions with Comments! | Pythagoras_the_3rd | 2 | 550 | perfect squares | 279 | 0.526 | Medium | 5,000 |
https://leetcode.com/problems/perfect-squares/discuss/2150944/Pretty-slow-but-simple-to-understand-i-guess-or-Python | class Solution:
def numSquares(self, n: int) -> int:
dp = {}
def dfs(num):
if num == 0:
return 0
if num in dp:
return dp[num]
cnt = 1
r = inf
while cnt*cnt <= num:
r = min(r, 1 + dfs(num - (cnt * cnt)))
cnt += 1
dp[num] = r
return r
retval = dfs(n)
return retval | perfect-squares | Pretty slow but simple to understand i guess | Python | skrrtttt | 1 | 56 | perfect squares | 279 | 0.526 | Medium | 5,001 |
https://leetcode.com/problems/perfect-squares/discuss/2106792/PYTHON-oror-BACKTRACKING-oror-EXPLANED | class Solution:
def numSquares(self, n: int) -> int:
def solve(n,i,k,a):
if n==0:
return min(k,a)
if i<=0 or k>=a:
return a
if (i**2)<=n:
a=solve(n-(i**2),i,k+1,a)
a=solve(n,i-1,k,a)
return a
return solve(n,int(n**0.5),0,1001) | perfect-squares | ✔️ PYTHON || BACKTRACKING ||✔️ EXPLANED | karan_8082 | 1 | 197 | perfect squares | 279 | 0.526 | Medium | 5,002 |
https://leetcode.com/problems/perfect-squares/discuss/1674118/Simple-Python-DP-solution-with-comments | class Solution:
def numSquares(self, n: int) -> int:
squares = [] # list of perfect squares
sums = [0 for x in range(n + 1)] # DP array to keep track of min sums
for i in range(1, n + 1):
sqrt = i**(1/2)
if sqrt.is_integer():
squares.append(i)
sums[i] = 1 # perfect squares have min sums of 0
else:
possible_solutions = []
for sq_num in squares:
# for each perfect square we have previously encountered, determine
# if a more optimal solution can be created for i using the previous
# optimal solutions found and saved in sums
possible_solutions.append(1 + sums[i - sq_num])
sums[i] = min(possible_solutions) # only save min solution
return sums[-1] | perfect-squares | Simple Python DP solution with comments | nat_5t34 | 1 | 280 | perfect squares | 279 | 0.526 | Medium | 5,003 |
https://leetcode.com/problems/perfect-squares/discuss/1184790/python-three-square-theorem-(28ms-faster-than-99.87)-and-dp-(faster-than-50-4200ms) | class Solution:
def numSquares(self, n: int) -> int:
# https://en.wikipedia.org/wiki/Legendre%27s_three-square_theorem
while (n & 3) == 0:
n >>= 2 # 4^a part
if (n % 8) == 7: # check if is 4^a(8b + 7)
return 4
if int(math.sqrt(n)) ** 2 == n:
return 1
# check if the number can be represented as the sum of three squares of integers
for i in range(int(math.sqrt(n)), 0, -1):
if int(math.sqrt(n-i*i)) ** 2 == n-i*i:
return 2
# worst case from the three-square theorem
return 3
# dynamic programming:
# class Solution:
# def numSquares(self, n: int) -> int:
# dp = [n] * (n+1)
# dp[0] = 0
# dp[1] = 1
# for i in range(2, n+1):
# tmp = int(math.sqrt(i))
# for j in range(tmp, 0, -1): # pruning here
# dp[i] = min(dp[i], dp[i - j * j] + 1)
# if dp[i] == 2 or dp[i] == 1: break
# return dp[n] | perfect-squares | python, three-square theorem (28ms, faster than 99.87%) and dp (faster than 50%, 4200ms) | dustlihy | 1 | 340 | perfect squares | 279 | 0.526 | Medium | 5,004 |
https://leetcode.com/problems/perfect-squares/discuss/765682/Python3-math-and-dp | class Solution:
def numSquares(self, n: int) -> int:
if int(sqrt(n))**2 == n: return 1
for i in range(1, int(sqrt(n))+1):
if int(sqrt(n - i*i))**2 == n - i*i: return 2
while n % 4 == 0: n //= 4
return 4 if n%8 == 7 else 3 | perfect-squares | [Python3] math & dp | ye15 | 1 | 234 | perfect squares | 279 | 0.526 | Medium | 5,005 |
https://leetcode.com/problems/perfect-squares/discuss/765682/Python3-math-and-dp | class Solution:
def numSquares(self, n: int) -> int:
@lru_cache(None)
def fn(x):
"""Return least number of perfect squares summing to x"""
if x == 0: return 0
ans = inf
for i in range(1, int(sqrt(x))+1):
ans = min(ans, 1 + fn(x-i*i))
return ans
return fn(n) | perfect-squares | [Python3] math & dp | ye15 | 1 | 234 | perfect squares | 279 | 0.526 | Medium | 5,006 |
https://leetcode.com/problems/perfect-squares/discuss/765682/Python3-math-and-dp | class Solution:
def numSquares(self, n: int) -> int:
@lru_cache(None)
def fn(x):
"""Return least number of perfect squares summing to x"""
if x == 0: return 0
return min(1 + fn(x-i*i) for i in range(1, int(sqrt(x))+1))
return fn(n) | perfect-squares | [Python3] math & dp | ye15 | 1 | 234 | perfect squares | 279 | 0.526 | Medium | 5,007 |
https://leetcode.com/problems/perfect-squares/discuss/765682/Python3-math-and-dp | class Solution:
def numSquares(self, n: int) -> int:
dp = [0] + [n]*n
for i in range(1, n+1):
for x in range(1, int(sqrt(i))+1):
dp[i] = min(dp[i], 1 + dp[i-x*x])
return dp[-1] | perfect-squares | [Python3] math & dp | ye15 | 1 | 234 | perfect squares | 279 | 0.526 | Medium | 5,008 |
https://leetcode.com/problems/perfect-squares/discuss/486661/Python-3-(DP)-(With-and-Without-Global-DP-List)-(beats-95)-(88-ms) | class Solution:
def numSquares(self, n: int) -> int:
DP = [0]
for i in range(1,n+1): DP.append(1 + min(DP[i-j*j] for j in range(int(i**.5),0,-1)))
return DP[n] | perfect-squares | Python 3 (DP) (With and Without Global DP List) (beats 95%) (88 ms) | junaidmansuri | 1 | 458 | perfect squares | 279 | 0.526 | Medium | 5,009 |
https://leetcode.com/problems/perfect-squares/discuss/486661/Python-3-(DP)-(With-and-Without-Global-DP-List)-(beats-95)-(88-ms) | class Solution:
GDP = [0]
def numSquares(self, n: int) -> int:
DP, L = self.GDP, len(self.GDP)
for i in range(L,n+1): DP.append(1 + min(DP[i-j*j] for j in range(int(i**.5),0,-1)))
return DP[n]
- Junaid Mansuri
- Chicago, IL | perfect-squares | Python 3 (DP) (With and Without Global DP List) (beats 95%) (88 ms) | junaidmansuri | 1 | 458 | perfect squares | 279 | 0.526 | Medium | 5,010 |
https://leetcode.com/problems/perfect-squares/discuss/2840866/python3-short-and-simple | class Solution:
def numSquares(self, n: int) -> int:
k = 1
ps = []
while k*k<= n:
ps.append(k*k)
k += 1
items = set([n])
ans = 0
while items:
ans += 1
tmp = set()
for item in items:
for i in ps:
j = item-i
if j < 0: continue
if j == 0: return ans
if j > 0: tmp.add(j)
items = tmp | perfect-squares | python3, short and simple | pjy953 | 0 | 6 | perfect squares | 279 | 0.526 | Medium | 5,011 |
https://leetcode.com/problems/perfect-squares/discuss/2840503/Basic-Python-solution-with-recursion-and-cache | class Solution:
perf_squares = [i**2 for i in range(1,101)] # store all possible squares
comp_res = dict() # cache with computed results
def numSquares(self, n: int) -> int:
cache = self.comp_res.get(n) # if we computed optimal number previosly
if cache is not None:
return cache
else: # didn't execute our func for this n previosly
if n in self.perf_squares: # is it perfect square?
self.comp_res[n] = 1 # put in cache
return 1
else:
min_sqr_num = list() # list that we store results for all options in
i = 0
while self.perf_squares[i] < n: # subtract all possible squares
min_sqr_num.append(self.numSquares(n - self.perf_squares[i])) # execute recursion for each option
i += 1
optim = min(min_sqr_num) + 1 # select optimal option
self.comp_res[n] = optim # put in cache
return optim | perfect-squares | Basic Python solution with recursion and cache | n00bcracker | 0 | 5 | perfect squares | 279 | 0.526 | Medium | 5,012 |
https://leetcode.com/problems/perfect-squares/discuss/2840428/Python3-easy-solution-with-comments-(Beats-97) | class Solution:
def numSquares(self, n: int) -> int:
square_nums = set([i**2 for i in range(1, int(sqrt(n)+1))])
def is_div_by(n, c):
# at the last piece,
# is it a perfect square?
if c == 1: return n in square_nums
# keep dividing into more pieces, searching for whether or
# not the piece of n (n-square) is a perfect square
# because we already know the other piece of n (square) is
for square in square_nums:
if is_div_by(n - square, c - 1):
return True
return False
# try dividing n into c # of pieces
# starting with the least # of pieces
for c in range(1, n+1):
if is_div_by(n, c):
return c | perfect-squares | Python3, easy solution with comments (Beats 97%) | rschevenin | 0 | 8 | perfect squares | 279 | 0.526 | Medium | 5,013 |
https://leetcode.com/problems/perfect-squares/discuss/2840318/Very-Short-and-Fast-The-Best | class Solution:
def numSquares(self, n):
least = [0]
for m in range(1, n+1):
least.append(1 + min(least[m - x*x] for x in range(1, 1 + floor(sqrt(m)))))
return least[-1] | perfect-squares | Very Short and Fast, The Best | Triquetra | 0 | 4 | perfect squares | 279 | 0.526 | Medium | 5,014 |
https://leetcode.com/problems/perfect-squares/discuss/2840015/Python3-easy-solution | class Solution:
# Make dp a class variable :)
dp = [0]
def numSquares(self, n: int) -> int:
dp = self.dp
# Precompute the perfect squares.
perfectSq = [pow(i,2) for i in range(1, int(sqrt(n))+1)]
# We are building dp up to length n+1.
while len(dp) < n+1:
# Will add this new element to dp
dpI = inf
# dp equation
for ps in perfectSq:
if len(dp)<ps: break
dpI = min(dpI,1+dp[-ps])
dp.append(dpI)
return dp[n] | perfect-squares | Python3 easy solution | avs-abhishek123 | 0 | 7 | perfect squares | 279 | 0.526 | Medium | 5,015 |
https://leetcode.com/problems/perfect-squares/discuss/2839567/Python-BFS-Solution-(Detailed-Explanation) | class Solution:
def numSquares(self, n: int) -> int:
squares= [i**2 for i in range(floor(n**0.5),0,-1)]
visited = set()
q = deque([(n,0)])
while q:
x,s = q.popleft()
for i in squares:
if not x-i: return s+1
if x-i >= 0:
if x-i not in visited:
q.append((x-i,s+1))
visited.add(x-i) | perfect-squares | Python BFS Solution (Detailed Explanation) | jooern | 0 | 9 | perfect squares | 279 | 0.526 | Medium | 5,016 |
https://leetcode.com/problems/perfect-squares/discuss/2839481/Most-Efficient-and-Easy-Python-Solution | class Solution:
def numSquares(self, n: int) -> int:
if n < 2:
return n
while n % 4 == 0:
n /= 4
if n % 8 == 7:
return 4
a = 0
while a * a <= n:
b = int((n - a * a) ** 0.5)
if a * a + b * b == n:
return bool(a) + bool(b)
a += 1
return 3 | perfect-squares | Most Efficient and Easy Python Solution | aayushhh_13 | 0 | 4 | perfect squares | 279 | 0.526 | Medium | 5,017 |
https://leetcode.com/problems/perfect-squares/discuss/2839471/Python-solution-using-DP | class Solution:
def numSquares(self, n: int) -> int:
dp=[n]*(n+1)
#print(dp)
dp[0]=0
for target in range(1,n+1):
for s in range(1,target+1):
square=s*s
if (target-square) < 0:
break
dp[target]=min(dp[target],1+dp[target-square])
return dp[n] | perfect-squares | Python solution using DP | ashishneo | 0 | 6 | perfect squares | 279 | 0.526 | Medium | 5,018 |
https://leetcode.com/problems/perfect-squares/discuss/2839070/Dynamic-Programming-Bottom-up-in-python-Not-TLE | class Solution:
dp = [0]
@cache
def numSquares(self, n: int) -> int:
squares = [k ** 2 for k in range(1, math.ceil(pow(n, 0.5) + 1))]
dp = self.dp
while len(dp) < n + 1:
dpI = sys.maxsize
if len(dp) in squares: dp.append(1);continue
for square in squares:
if len(dp) < square: break
dpI = min(dpI, dp[len(dp) - square] + 1)
dp.append(dpI)
return dp[n] | perfect-squares | Dynamic Programming Bottom-up in python [Not TLE] | shiv-codes | 0 | 8 | perfect squares | 279 | 0.526 | Medium | 5,019 |
https://leetcode.com/problems/perfect-squares/discuss/2839017/Python3-Detailed-Explanation | class Solution:
def numSquares(self, n: int) -> int:
# Self is Perfect Square
if sqrt(n) == int(sqrt(n)) : return 1
# Base case
res = [1,2]
index = 3
while index <= n:
sqrt_number = sqrt(index)
if sqrt_number == int(sqrt_number) : res.append(1)
else:
mini = 10000
for i in range(1, int(sqrt_number)+1):
tmp = 1 + res[index - (i**2) - 1]
if tmp < mini:
mini = tmp
res.append(mini)
index += 1
return res[n-1] | perfect-squares | Python3 Detailed Explanation | dad88htc816 | 0 | 12 | perfect squares | 279 | 0.526 | Medium | 5,020 |
https://leetcode.com/problems/perfect-squares/discuss/2838930/Python-DP-tabulation-solution-O(n-sqrt-n) | class Solution:
def numSquares(self, n: int) -> int:
dp: List[int] = [i for i in range(n+1)]
i, i_sqr = 2, 4
while i_sqr <= n:
for j in range(i_sqr, len(dp)):
dp[j] = min(dp[j], 1 + dp[j - i_sqr])
i += 1
i_sqr = i * i
return dp[-1]
#end numSquares | perfect-squares | [Python] DP tabulation solution O(n sqrt n) | olzh06 | 0 | 25 | perfect squares | 279 | 0.526 | Medium | 5,021 |
https://leetcode.com/problems/perfect-squares/discuss/2838670/Python-or-DFS-or-Recursion-or-DP-(-2-Ways) | class Solution:
def numSquares(self, n: int) -> int:
square_set = set()
def square_finder(num):
while num**2>n:
return
square_set.add(num**2)
square_finder(num+1)
square_finder(1)
res = [float("inf")]
def dfs(arr, pos, total_sum, slate):
if total_sum > n :
return
if total_sum == n:
res[0] = min(res[0], len(slate[:]))
return
for index in range(pos, len(arr)):
dfs(arr, index, total_sum + arr[index], slate+[arr[index]])
arr = [x for x in square_set]
print(arr)
dfs(arr, 0, 0, [])
return res[0] | perfect-squares | Python | DFS | Recursion | DP ( 2 Ways) | ajay_gc | 0 | 8 | perfect squares | 279 | 0.526 | Medium | 5,022 |
https://leetcode.com/problems/perfect-squares/discuss/2838670/Python-or-DFS-or-Recursion-or-DP-(-2-Ways) | class Solution:
def numSquares(self, n: int) -> int:
square_set = set()
def square_finder(num):
while num**2>n:
return
square_set.add(num**2)
square_finder(num+1)
square_finder(1)
ROW = len(square_set)+1
COL = n+1
arr = [x for x in square_set]
dptable = [[float("inf")]*(n+1) for _ in range(len(square_set)+1)]
for row in range(ROW):
dptable[row][0] = 0
for row in range(1,ROW):
for col in range(1,COL):
if arr[row-1] <= col:
dptable[row][col] = min(dptable[row-1][col], 1+dptable[row][col-arr[row-1]])
else:
dptable[row][col] = dptable[row-1][col]
return dptable[-1][-1] | perfect-squares | Python | DFS | Recursion | DP ( 2 Ways) | ajay_gc | 0 | 8 | perfect squares | 279 | 0.526 | Medium | 5,023 |
https://leetcode.com/problems/perfect-squares/discuss/2838670/Python-or-DFS-or-Recursion-or-DP-(-2-Ways) | class Solution:
def numSquares(self, n: int) -> int:
arr = []
start = 1
while start*start <= n:
arr.append(start*start)
start += 1
COL = n+1
dptable = [float("inf")] * COL
dptable[0] = 0
for amount in range(1, COL):
min_value = dptable[amount]
for num in arr:
if num <= amount:
min_value = min(min_value, dptable[amount-num])
dptable[amount] = min_value +1
return dptable[-1] | perfect-squares | Python | DFS | Recursion | DP ( 2 Ways) | ajay_gc | 0 | 8 | perfect squares | 279 | 0.526 | Medium | 5,024 |
https://leetcode.com/problems/perfect-squares/discuss/2838662/Python-Easy-BFS-Solution | class Solution:
def numSquares(self, n: int) -> int:
queue = [(0,0)]
seen = [False]*(n+1)
ps = [i**2 for i in range(1,int(sqrt(n))+1)][::-1]
while queue:
total,steps = queue.pop(0)
for sq in ps:
tmp = total + sq
if tmp < n and not seen[tmp]:
queue.append((tmp,steps+1))
seen[tmp] = True
elif tmp == n:
return steps + 1
return -1 | perfect-squares | Python Easy BFS Solution | sparshlodha04 | 0 | 5 | perfect squares | 279 | 0.526 | Medium | 5,025 |
https://leetcode.com/problems/perfect-squares/discuss/2838646/Python-or-BFS-Solution-or-DP-Solution | class Solution:
def numSquares(self, n: int) -> int:
sq = []
for i in range(1, n + 1):
if i ** 2 < n:
sq.append(i ** 2)
elif i ** 2 == n:
return 1
else:
break
queue = deque([n])
seen = set()
seen.add(n)
count = 1
while queue:
for _ in range(len(queue)):
curr = queue.popleft()
if curr in sq:
return count
for s in sq:
if curr - s < 0:
break
if curr - s not in seen:
seen.add(curr - s)
queue.append(curr - s)
count += 1 | perfect-squares | Python | BFS Solution | DP Solution | KevinJM17 | 0 | 4 | perfect squares | 279 | 0.526 | Medium | 5,026 |
https://leetcode.com/problems/perfect-squares/discuss/2838646/Python-or-BFS-Solution-or-DP-Solution | class Solution:
def numSquares(self, n: int) -> int:
dp = [float('inf')] * (n + 1)
dp[0] = 0
root = 1
square = 1 # 1 * 1
while square <= n:
for target in range(square, n + 1):
dp[target] = min(dp[target], 1 + dp[target - square])
root += 1
square = root ** 2
return dp[-1] | perfect-squares | Python | BFS Solution | DP Solution | KevinJM17 | 0 | 4 | perfect squares | 279 | 0.526 | Medium | 5,027 |
https://leetcode.com/problems/perfect-squares/discuss/2838358/Python-or-Simple-math-solution-or-Beats-95%2B | class Solution:
def numSquares(self, n):
if int(sqrt(n))**2 == n: return 1
for j in range(int(sqrt(n)) + 1):
if int(sqrt(n - j*j))**2 == n - j*j: return 2
while n % 4 == 0:
n >>= 2
if n % 8 == 7: return 4
return 3 | perfect-squares | Python | Simple math solution | Beats 95+% | LordVader1 | 0 | 11 | perfect squares | 279 | 0.526 | Medium | 5,028 |
https://leetcode.com/problems/perfect-squares/discuss/2838271/Num-Squares-BFS-python-O(n*sqrtn) | class Solution:
def numSquares(self, n: int) -> int:
# 1 2 3 4 5 6 7
# 1 4 9 16 25 36 49
root = int(n**.5)
queue = [(n,0)]
while queue:
number, counter = queue.pop(0)
for iroot in reversed(range(1, root+1)):
resta = number - iroot**2
if resta >0:
queue.append([resta, counter +1])
elif resta == 0:
return counter +1 | perfect-squares | Num Squares - BFS - python O(n*sqrt{n}) | DavidCastillo | 0 | 8 | perfect squares | 279 | 0.526 | Medium | 5,029 |
https://leetcode.com/problems/perfect-squares/discuss/2838148/python-dp-explanation-in-comments | class Solution:
def numSquares(self, n: int) -> int:
#first we need dp array to solve subproblems first
#limit that at n- we know that's the max of the range
dp = [n] * (n+1)
#we know the first one must be zero
#best case scenario - zero squares if it's already a square
dp[0] = 0
#this extra line limits us to only the perfect squares in the range (to save time)
squares = [x**2 for x in range(0,n) if x**2<=n]
#iterate through all target values in range
#(1, n+1) because python is non-inclusive
for target in range(1, n+1):
#now we find the squares within the target range
for square in squares:
#if this square is too big, we can just break here
if target - square < 0:
break
#here we check possible solution
#if it's already the min we don't need to change
#add one to account for sqaure we jut used in lines above
dp[target] = min(dp[target], 1+dp[target-square])
#once this is done, the dp array position of n will give us the minimum number of squares required
return dp[n] | perfect-squares | python dp explanation in comments | ATHBuys | 0 | 6 | perfect squares | 279 | 0.526 | Medium | 5,030 |
https://leetcode.com/problems/perfect-squares/discuss/2837857/Python-DP-ez-to-understand | class Solution:
def numSquares(self, n: int) -> int:
dp = [n for _ in range(n + 2)]
dp[0] = 0
for target in range(1, n + 1):
for s in range(1, target + 1):
sq = s * s
if target - sq < 0:
break
dp[target] = min(dp[target], 1 + dp[target - sq])
return dp[n] | perfect-squares | Python DP, ez to understand | mukund-13 | 0 | 6 | perfect squares | 279 | 0.526 | Medium | 5,031 |
https://leetcode.com/problems/perfect-squares/discuss/2837825/Python-solution | class Solution:
def numSquares(self, n: int) -> int:
dp = [float('inf')] * (n + 1)
num = int(pow(n, 0.5))
lists = [pow(i,2) for i in range(1, num + 1)]
dp[0] = 0
for i in range(1, n + 1):
nums = []
for j in range(len(lists)):
idx = i - lists[j]
if idx >= 0:
nums.append(dp[idx])
dp[i] = min(nums) + 1
return dp[-1] | perfect-squares | Python solution | maomao1010 | 0 | 14 | perfect squares | 279 | 0.526 | Medium | 5,032 |
https://leetcode.com/problems/perfect-squares/discuss/2837780/279.-Perfect-Squares-or-Python3 | class Solution:
def solve(self, n, memo = {}):
if n == 0:
return 0
mc = sys.maxsize
if n not in memo:
for i in range(1, floor(sqrt(n))+1):
c = 1 + self.solve(n - i*i, memo)
mc = min(mc, c)
memo[n] = mc
return memo[n]
def numSquares(self, n: int) -> int:
return self.solve(n) | perfect-squares | 279. Perfect Squares | Python3 | AndrewMitchell25 | 0 | 4 | perfect squares | 279 | 0.526 | Medium | 5,033 |
https://leetcode.com/problems/perfect-squares/discuss/2837761/python-top-down-dp-6-lines | class Solution:
def numSquares(self, n: int) -> int:
sq = [i**2 for i in range(1, 101)]
ssq = set(sq)
@cache
def dp(i):
return min([1+dp(i-k) for k in takewhile(lambda t: t < i, sq)]) if i not in ssq else 1
return dp(n) | perfect-squares | python; top down dp; 6 lines | junhong030386 | 0 | 6 | perfect squares | 279 | 0.526 | Medium | 5,034 |
https://leetcode.com/problems/perfect-squares/discuss/2837711/Faster-than-99-based-on-factorization | class Solution:
def numSquares(self, n: int) -> int:
s=int(sqrt(n))
if n==s*s:
return 1
def sum2(n):
p=2
while p*p<n:
if not n%p:
pwr=0
while not n%p:
pwr+=1
n//=p
if p&3==3 and pwr&1:
return False
p+=1
return n&3!=3
if sum2(n):
return 2
for i in range(s, 0, -1):
if sum2(n-i*i):
return 3
return 4 | perfect-squares | Faster than 99%, based on factorization | mbeceanu | 0 | 4 | perfect squares | 279 | 0.526 | Medium | 5,035 |
https://leetcode.com/problems/perfect-squares/discuss/2837659/Python3-easy-solution-with-global-dp-list | class Solution:
gdp=[0]
def numSquares(self,n:int)->int:
dp,l=self.gdp,len(self.gdp)
for i in range(l,n+1):
dp.append(1+min(dp[i-j*j] for j in range(int(i**.5),0,-1)))
return dp[n] | perfect-squares | Python3 easy solution with global dp list | Motaharozzaman1996 | 0 | 16 | perfect squares | 279 | 0.526 | Medium | 5,036 |
https://leetcode.com/problems/perfect-squares/discuss/2837611/Python-or-Dynamic-Programming | class Solution:
def numSquares(self, n: int) -> int:
squares = [x*x for x in range(1,int(n**0.5)+1)]
res = [0]
for i in range(1,n+1):
mn = 1000
for j in range(len(squares)):
if squares[j] > i:
break
if res[i - squares[j]] + 1 < mn:
mn = res[i - squares[j]] + 1
res.append(mn)
return res[-1] | perfect-squares | Python | Dynamic Programming | jarvis277 | 0 | 7 | perfect squares | 279 | 0.526 | Medium | 5,037 |
https://leetcode.com/problems/perfect-squares/discuss/2837594/Easy-to-understand-linear-DP-in-python3 | class Solution:
def numSquares(self, n: int) -> int:
denoms = [1]
x = 2
while x*x <= n:
denoms.append(x*x)
x += 1
min_squares = [float('inf') for _ in range(n+1)]
min_squares[0] = 0
for denom in denoms:
for weight in range(1, len(min_squares)):
if denom <= weight:
min_squares[weight] = min(min_squares[weight-denom] + 1, min_squares[weight])
return min_squares[n] | perfect-squares | Easy to understand, linear DP in python3 | kunal5042 | 0 | 8 | perfect squares | 279 | 0.526 | Medium | 5,038 |
https://leetcode.com/problems/perfect-squares/discuss/2359532/Python3-Solution-with-using-dp | class Solution:
def numSquares(self, n: int) -> int:
squares = [i * i for i in range(int(sqrt(n)) + 1)]
dp = [float('inf')] * (n + 1)
dp[0], dp[1] = 0, 1
for i in range(2, n + 1):
for sq in squares:
if sq > i:
break
dp[i] = min(dp[i], dp[i - sq] + 1)
return dp[-1] | perfect-squares | [Python3] Solution with using dp | maosipov11 | 0 | 44 | perfect squares | 279 | 0.526 | Medium | 5,039 |
https://leetcode.com/problems/perfect-squares/discuss/2311210/Help!-Why-my-DFS-solution-by-Python-out-of-Time-Limit | class Solution:
def numSquares(self, n: int) -> int:
# p is the integer less than sqrt(n)
p = int(math.sqrt(n))
# initiate the dp
dp = [float('inf')]*(n+1)
dp[0] = 0
# DFS, firstly traverse every number less than n, then traverse every perfect square
for i in range(p, 0, -1):
m = i**2
for k in range(m, n+1):
dp[k] = min(dp[k-m]+1, dp[k])
return dp[-1] | perfect-squares | Help! Why my DFS solution by Python out of Time Limit? | XRFXRF | 0 | 52 | perfect squares | 279 | 0.526 | Medium | 5,040 |
https://leetcode.com/problems/perfect-squares/discuss/2096349/HELP-NEEDED-getting-TLE-while-using-the-coin-change-code-here | class Solution:
def numSquares(self, n: int) -> int:
coins = []
for i in range(1,n+1):
if i*i<=n:
coins.append(i*i)
else:
break
memo = {}
amount = n
ans = self.helper(coins, amount, memo)
print(memo)
if ans == 999999999999:
return -1
return ans
def helper(self, coins, amount, memo):
if amount in memo :
return memo[amount]
if len(coins)==0:
memo[amount] = 999999999999
return 999999999999
if amount==0:
memo[amount] = 0
return 0
if coins[0]<=amount:
ans = min(self.helper(coins[1:],amount,memo),1+self.helper(coins,amount-coins[0],memo))
memo[amount] = ans
return ans
else:
ans = self.helper(coins[1:], amount, memo)
memo[amount] = ans
return ans | perfect-squares | HELP NEEDED, getting TLE while using the coin change code here | abhineetsingh192 | 0 | 96 | perfect squares | 279 | 0.526 | Medium | 5,041 |
https://leetcode.com/problems/perfect-squares/discuss/1940543/Python-Dynamic-Programming | class Solution:
def numSquares(self, n: int) -> int:
dp = [n] * (n + 1)
dp[0] = 0
for target in range(1, n + 1):
for s in range(1, target + 1):
square = s * s
if target - square < 0:
break
dp[target] = min(dp[target], 1 + dp[target - square])
return dp[n] | perfect-squares | Python - Dynamic Programming | dayaniravi123 | 0 | 48 | perfect squares | 279 | 0.526 | Medium | 5,042 |
https://leetcode.com/problems/perfect-squares/discuss/1597940/Py3Py-Two-Solutions-one-with-memoization-and-one-with-dp-w-comments | class Solution:
# Recursion with memoization
def numSquares(self, n: int) -> int:
leastSqrs = n
@cache
def recursion(s):
nonlocal leastSqrs
if s > 3:
i = 1
while i**2 <= s:
leastSqrs = min(leastSqrs, 1 + recursion(s-i**2))
i += 1
return leastSqrs
return s
return recursion(n) | perfect-squares | [Py3/Py] Two Solutions one with memoization and one with dp w/ comments | ssshukla26 | 0 | 258 | perfect squares | 279 | 0.526 | Medium | 5,043 |
https://leetcode.com/problems/perfect-squares/discuss/1520700/Understandable-simple-Mathematics-based-solution.-(No-Formula-or-DP)-beats-94 | class Solution:
def numSquares(self, n: int) -> int:
import math
if int(math.sqrt(n))**2==n:return 1
for i in range(int(math.sqrt(n))+1):
if int(math.sqrt(n-i*i))**2 == n - i*i:return 2
for i in range(int(math.sqrt(n))+1):
for j in range(int(math.sqrt(n))+1):
if (n-i*i-j*j) < 0:break
if int(math.sqrt(n-i*i-j*j))**2 == (n - i*i - j*j) : return 3
return 4 | perfect-squares | Understandable simple Mathematics based solution. (No Formula or DP) beats 94% | Atri_Patel | 0 | 101 | perfect squares | 279 | 0.526 | Medium | 5,044 |
https://leetcode.com/problems/perfect-squares/discuss/1475376/2-end-BFS-python-solution-97.20-faster | class Solution:
def numSquares(self, n: int) -> int:
#check whether n is perfect square
if int(n**0.5)**2==n:
return 1
#collect the possible perfect squares used to construct n
ps=set()
i=1
while i**2<=n:
ps.add(i**2)
i+=1
#create two ends of the bfs
begin=set()
begin.add(0)
end=set()
end.add(n)
step=0
while begin and end:
step+=1
temp=set()
high=max(end)
for i in begin:
for j in ps:
#check if begin reaches end
if (i+j) in end:
return step
#if i+j>high, it's not possible to be a part of the answer
elif i+j<high:
temp.add(i+j)
begin=temp
step+=1
temp=set()
low=min(begin)
for i in end:
for j in ps:
#check if end reaches begin
if (i-j) in begin:
return step
#if i-j<low, it's not possible to be a part of the answer
elif i-j>low:
temp.add(i-j)
end=temp
return -1 | perfect-squares | 2-end BFS python solution, 97.20% faster | st60712 | 0 | 139 | perfect squares | 279 | 0.526 | Medium | 5,045 |
https://leetcode.com/problems/expression-add-operators/discuss/1031229/Python-Simple-heavily-commented-and-accepted-Recursive-Solution | class Solution:
def addOperators(self, num: str, target: int) -> List[str]:
exprs = []
def recurse(idx, value, delta, exp):
# base case here
if idx == len(num):
if value == target:
exprs.append("".join(exp))
# the loop will create the current operand and recursively call
# the next set of actions to be executed
for i in range(idx, len(num)):
# this is to avoid cases where the operand starts with a 0
# we need to have a case with just the 0 but not something like
# 05, so the condition will return early if we find such cases
if num[idx] == '0' and i > idx:
return
curr = int(num[idx:i+1])
curr_str = num[idx:i+1]
# when we start the problem we dont have a preceding operator or operand
if idx == 0:
recurse(i+1, curr, curr, exp + [curr_str])
else:
# We need to do 3 different recursions for each operator
# value stores the running value of the expression evaluated so far
# the crux of the logic lies in how we use and pass delta
# when the operation is '+' or '-' we don't care much about it and can just
# add or subtract it from the value
# when '*' is involved, we need to follow the precedence relation,
# but we have already evaluated the previous operator. We know the
# previous operation that was performed and how much it contributed to the value i.e., delta
# so, we can revert that operation by subtracting delta from value and reapplying the multiplication
recurse(i+1, value+curr, curr, exp + ['+', curr_str])
recurse(i+1, value-curr, -curr, exp + ['-', curr_str])
recurse(i+1, (value-delta)+curr*delta, curr*delta, exp + ['*', curr_str])
recurse(0, 0, 0, [])
return exprs | expression-add-operators | [Python] Simple, heavily commented and accepted Recursive Solution | gokivego | 4 | 354 | expression add operators | 282 | 0.392 | Hard | 5,046 |
https://leetcode.com/problems/expression-add-operators/discuss/837116/simple-and-easy-python-solution-or-backtracking | class Solution:
def Util(self, num, target, ind, l, mem, exp):
if ind == l - 1:
exp += num[ind]
if eval(exp) == target:
return [exp]
if ind >= l:
return []
ret1 = self.Util(num, target, ind + 1, l, mem, exp + str(num[ind]) + '+')
ret2 = self.Util(num, target, ind + 1, l, mem, exp + str(num[ind]) + '-')
ret3 = self.Util(num, target, ind + 1, l, mem, exp + str(num[ind]) + '*')
if (exp and exp[-1].isdigit() is True and num[ind] == '0') or num[ind] != '0':
ret4 = self.Util(num, target, ind + 1, l, mem, exp + str(num[ind]))
ret = ret1 + ret2 + ret3 + ret4
else:
ret = ret1 + ret2 + ret3
return ret
def addOperators(self, num: str, target: int) -> List[str]:
return self.Util(num, target, 0, len(num), dict(), '') | expression-add-operators | simple and easy python solution | backtracking | _YASH_ | 2 | 454 | expression add operators | 282 | 0.392 | Hard | 5,047 |
https://leetcode.com/problems/expression-add-operators/discuss/2394320/Python-recursive-solution | class Solution:
def addOperators(self, num: str, target: int) -> List[str]:
answer = set()
def dp(idx, total, path, last_number):
if idx == len(num) and total == target:
answer.add(path)
if idx >= len(num):
return
for i in range(idx, len(num)):
if len(num[idx:i+1]) > 1 and num[idx:i+1][0] == "0":
continue
tmp_number = num[idx:i+1]
if last_number == "":
dp(i + 1, int(tmp_number), tmp_number, tmp_number)
else:
# addition
dp(i + 1,total + int(tmp_number), path + "+" + tmp_number, tmp_number)
# subtraction
dp(i + 1,total - int(tmp_number), path + "-" + tmp_number, "-" + tmp_number)
# multiplication
dp(i + 1, total-int(last_number) + (int(last_number) * int(tmp_number)), path + "*" + tmp_number, str(int(tmp_number) * int(last_number)))
dp(0,-1,"", "")
return answer | expression-add-operators | Python recursive solution | pivovar3al | 1 | 96 | expression add operators | 282 | 0.392 | Hard | 5,048 |
https://leetcode.com/problems/expression-add-operators/discuss/1069896/Clean-Python-Solution | class Solution:
def addOperators(self, num: str, target: int) -> List[str]:
ret = []
def dfs(subtotal, last, path, start):
if start == len(num):
if subtotal == target:
ret.append(''.join(path))
return
for i in range(start, len(num)):
ch = num[start:i + 1]
if len(ch) > 1 and ch[0] == '0':
continue
integer = int(ch)
if not path:
dfs( integer, integer, [ch], i + 1 )
else:
dfs( subtotal + integer, integer, path + ['+', ch], i + 1 )
dfs( subtotal - integer, -integer, path + ['-', ch],i + 1 )
# the most interesting part:
# e.g. 1+2*3, we record last as 2, so: 3-2+2*3 = 7
dfs( subtotal - last + last * integer, last * integer, path + ['*', ch], i + 1 )
dfs(0, 0, [], 0)
return ret | expression-add-operators | Clean Python Solution | Black_Pegasus | 1 | 487 | expression add operators | 282 | 0.392 | Hard | 5,049 |
https://leetcode.com/problems/expression-add-operators/discuss/2798439/Python-Solution | class Solution:
def addOperators(self, num: str, target: int) -> List[str]:
n=len(num)
output=[]
def dfs(i,so_far_list,res,prev):
if i>=n:
#print(so_far_list,res)
if res==target:
output.append("".join(so_far_list))
#ouptut.append("".join(so_far_list))
return
for j in range(i,n):
cand=int(num[i:j+1])
if not so_far_list:
dfs(j+1,[num[i:j+1]],cand,cand)
else:
dfs(j+1,so_far_list+["+"]+[num[i:j+1]],res+cand,cand)
dfs(j+1,so_far_list+["-"]+[num[i:j+1]],res-cand,-cand)
dfs(j+1,so_far_list+["*"]+[num[i:j+1]],res-prev+cand*prev,cand*prev)
if num[i]=="0":
break
dfs(0,[],0,None)
return output | expression-add-operators | Python Solution | Rigved_25 | 0 | 7 | expression add operators | 282 | 0.392 | Hard | 5,050 |
https://leetcode.com/problems/expression-add-operators/discuss/2516487/Python3-DFS | class Solution:
def addOperators(self, num: str, target: int) -> List[str]:
def DFS(num_str: str = "", prev_exp_str: str = "", prev_eval: int = 0, last_operand: int = 0): # for example, num = "2307", target = 16
if num_str == "" and prev_eval == target: # terminal leaf node
res.append(prev_exp_str)
return
for i in range(len(num_str)):
if i>0 and num_str[0] == "0": # skipping any operands with leading zeros, namely, "00" ~ "09"
continue
this_operand_str = num_str[:i+1] # "2", "23", "230", "2307"
this_operand = int(this_operand_str)
remaining_str = num_str[i+1:] # "307", "07", "7"
if prev_exp_str == "":
DFS(remaining_str, this_operand_str, this_operand, this_operand)
else:
DFS(remaining_str, prev_exp_str+"+"+this_operand_str, prev_eval+this_operand, this_operand)
DFS(remaining_str, prev_exp_str+"-"+this_operand_str, prev_eval-this_operand, -this_operand)
DFS(remaining_str, prev_exp_str+"*"+this_operand_str, prev_eval-last_operand+last_operand*this_operand, last_operand*this_operand)
# 1+2 --> 1+2*3 ==> we need to do 1+2-2+2*3. undo the last operand
# 7+1*2 --> 7+1*2*3 ==> we need to 7+(1*2)-(1*2)+(1*2*3). undo the last operand
res = []
DFS(num)
return res
# "2307", 16
# Time Complexity O(4^N), because we have four possibilities between each two operands, "+", "-", "*", NO OP, and we have n digits
# Space Complexity O(N), which is the depth of the recusive tree, since all the operands are single digits | expression-add-operators | Python3 DFS | NinjaBlack | 0 | 86 | expression add operators | 282 | 0.392 | Hard | 5,051 |
https://leetcode.com/problems/expression-add-operators/discuss/1889222/Why-my-python-O(4N)-solution-get-time-limit-exceeded | class Solution:
def addOperators(self, num: str, target: int) -> List[str]:
ans = []
def backtrack(cur, i):
if i >= len(cur):
# print(cur)
if self.check(cur) and self.calculate(cur) == target:
ans.append(cur[:])
return
backtrack(cur[:i] + "*" + cur[i:], i+2)
backtrack(cur[:i] + "+" + cur[i:], i+2)
backtrack(cur[:i] + "-" + cur[i:], i+2)
backtrack(cur, i+1)
backtrack(num, 1)
return ans
def calculate(self, cur_digits: str) -> int:
ans = int(eval(cur_digits))
return ans
def check(self, cur_digits: str) -> bool:
ans = []
j = 0
for i in range(len(cur_digits)):
if cur_digits[i] in ["*", "+", "-"]:
if i - j > 1 and cur_digits[j] == "0":
return False
j = i + 1
if len(cur_digits) - j > 1 and cur_digits[j] == "0":
return False
return True | expression-add-operators | Why my python O(4^N) solution get time limit exceeded? | vandesa003 | 0 | 62 | expression add operators | 282 | 0.392 | Hard | 5,052 |
https://leetcode.com/problems/expression-add-operators/discuss/1889222/Why-my-python-O(4N)-solution-get-time-limit-exceeded | class Solution:
def addOperators(self, num, target):
def dfs(idx, path, value, last):
if idx == n and value == target:
ans.append(path)
for i in range(idx + 1, n + 1):
tmp = int(num[idx: i])
if i == idx + 1 or (i > idx + 1 and num[idx] != "0"):
if last is None :
dfs(i, num[idx: i], tmp, tmp)
else:
dfs(i, path + '+' + num[idx: i], value + tmp, tmp)
dfs(i, path + '-' + num[idx: i], value - tmp, -tmp)
dfs(i, path + '*' + num[idx: i], value - last + last*tmp, last*tmp)
ans, n = [], len(num)
dfs(0, "", 0, None)
return ans | expression-add-operators | Why my python O(4^N) solution get time limit exceeded? | vandesa003 | 0 | 62 | expression add operators | 282 | 0.392 | Hard | 5,053 |
https://leetcode.com/problems/expression-add-operators/discuss/775390/Python3-eval-string | class Solution:
def addOperators(self, num: str, target: int) -> List[str]:
ops = ["*", "+", "-"]
def fn(i):
"""Populate ans with a stack via backtracking."""
stack.append(num[i])
if i == len(num)-1:
expr = "".join(stack)
if eval(expr) == target: ans.append(expr)
else:
for op in ops + [""]:
if stack[-1] == "0" and op == "" and (len(stack) == 1 or stack[-2] in ops): continue
stack.append(op)
fn(i+1)
stack.pop()
stack.pop()
ans, stack = [], []
fn(0)
return ans | expression-add-operators | [Python3] eval string | ye15 | 0 | 230 | expression add operators | 282 | 0.392 | Hard | 5,054 |
https://leetcode.com/problems/expression-add-operators/discuss/775390/Python3-eval-string | class Solution:
def addOperators(self, num: str, target: int) -> List[str]:
def fn(i, expr, total, last):
"""Populate ans with expression evaluated to target."""
if i == len(num):
if total == target: ans.append(expr)
else:
for ii in range(i, len(num) if num[i] != "0" else i+1):
val = int(num[i:ii+1])
if i == 0: fn(ii+1, num[i:ii+1], val, val)
else:
fn(ii+1, expr + "*" + num[i:ii+1], total - last + last * val, last * val)
fn(ii+1, expr + "+" + num[i:ii+1], total + val, val)
fn(ii+1, expr + "-" + num[i:ii+1], total - val, -val)
ans = []
fn(0, "", 0, 0)
return ans | expression-add-operators | [Python3] eval string | ye15 | 0 | 230 | expression add operators | 282 | 0.392 | Hard | 5,055 |
https://leetcode.com/problems/move-zeroes/discuss/404010/Python-easy-solution | class Solution(object):
def moveZeroes(self, nums):
i=0
n = len(nums)
while i <n:
if nums[i]==0:
nums.pop(i)
nums.append(0)
n-=1
else:
i+=1 | move-zeroes | Python easy solution | saffi | 16 | 2,600 | move zeroes | 283 | 0.614 | Easy | 5,056 |
https://leetcode.com/problems/move-zeroes/discuss/1001971/Python-Easy-Solution-O(N)-time-O(1)-space | class Solution(object):
def moveZeroes(self, nums):
c=0
for i in range(len(nums)):
if nums[i]!=0:
nums[c],nums[i]=nums[i],nums[c]
c+=1
return nums | move-zeroes | Python Easy Solution / O(N) time / O(1) space | lokeshsenthilkumar | 15 | 2,200 | move zeroes | 283 | 0.614 | Easy | 5,057 |
https://leetcode.com/problems/move-zeroes/discuss/1748937/Python-Simple-and-Clean-Python-Solution-By-Two-Approach | class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
for i in nums:
if i==0:
nums.remove(i)
nums.append(0) | move-zeroes | [ Python ] ✔✅ Simple and Clean Python Solution By Two Approach | ASHOK_KUMAR_MEGHVANSHI | 14 | 439 | move zeroes | 283 | 0.614 | Easy | 5,058 |
https://leetcode.com/problems/move-zeroes/discuss/1748937/Python-Simple-and-Clean-Python-Solution-By-Two-Approach | class Solution:
def moveZeroes(self, nums: List[int]) -> None:
p,q=0,0
while q<len(nums):
if nums[q]==0:
q=q+1
else:
nums[p],nums[q]=nums[q],nums[p]
p=p+1
q=q+1
return nums | move-zeroes | [ Python ] ✔✅ Simple and Clean Python Solution By Two Approach | ASHOK_KUMAR_MEGHVANSHI | 14 | 439 | move zeroes | 283 | 0.614 | Easy | 5,059 |
https://leetcode.com/problems/move-zeroes/discuss/2071556/PYTHON-Easy-To-Understand-Code | class Solution:
def moveZeroes(self, nums: List[int]) -> None:
for i in nums:
if i == 0:
nums.remove(0)
nums.append(0) | move-zeroes | PYTHON Easy To Understand Code | Shivam_Raj_Sharma | 7 | 210 | move zeroes | 283 | 0.614 | Easy | 5,060 |
https://leetcode.com/problems/move-zeroes/discuss/1379090/Easy-Python-solution | class Solution:
def moveZeroes(self, nums: List[int]) -> None:
for y in nums:
if y == 0:
nums.append(0)
nums.remove(0) | move-zeroes | Easy Python solution | zhivkob | 4 | 230 | move zeroes | 283 | 0.614 | Easy | 5,061 |
https://leetcode.com/problems/move-zeroes/discuss/563197/Python-simple-solution-Faster-than-73.17 | class Solution:
def moveZeroes(self, nums: List[int]) -> None:
first_zero = 0
for i in range(0, len(nums)):
if nums[i] != 0:
nums[first_zero], nums[i] = nums[i], nums[first_zero]
first_zero += 1 | move-zeroes | Python simple solution, Faster than 73.17% | t_hara | 4 | 397 | move zeroes | 283 | 0.614 | Easy | 5,062 |
https://leetcode.com/problems/move-zeroes/discuss/2775687/Efficient-python-solution-with-explanation | class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
freePos = None
for i in range(len(nums)):
if freePos == None and nums[i] == 0:
freePos = i
if freePos != None and nums[i] != 0:
nums[freePos], nums[i] = nums[i], 0
freePos += 1 | move-zeroes | Efficient python solution with explanation | really_cool_person | 3 | 409 | move zeroes | 283 | 0.614 | Easy | 5,063 |
https://leetcode.com/problems/move-zeroes/discuss/2348136/Python-Easy-Top-90-with-explanation | class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
# Init slow pointer
slow = 0
# Iterate through numbers with fast pointer
for fast in range(len(nums)):
# 0
if nums[fast] != 0 and nums[slow] == 0:
# Swap numbers between 0 and fast
nums[slow], nums[fast] = nums[fast],nums[slow]
# Non-zero
if nums[slow] != 0 :
# Increment slow
slow += 1 | move-zeroes | Python Easy Top 90% with explanation | drblessing | 3 | 141 | move zeroes | 283 | 0.614 | Easy | 5,064 |
https://leetcode.com/problems/move-zeroes/discuss/2130042/Simple-Logic | class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead
"""
n = len(nums)
i = 0
for j in range(n):
if nums[j] != 0:
nums[i], nums[j] = nums[j], nums[i]
i += 1 | move-zeroes | Simple Logic | writemeom | 3 | 177 | move zeroes | 283 | 0.614 | Easy | 5,065 |
https://leetcode.com/problems/move-zeroes/discuss/1902090/100-working-super-easy-to-understand-python-code | class Solution:
def moveZeroes(self, nums: List[int]) -> None:
p=0
for i in range(0,len(nums)):
if nums[i]!=0:
nums[i],nums[p] = nums[p],nums[i]
p+=1 | move-zeroes | 100% working, super easy to understand python code | tkdhimanshusingh | 3 | 166 | move zeroes | 283 | 0.614 | Easy | 5,066 |
https://leetcode.com/problems/move-zeroes/discuss/1563112/Simple-Python-Solution | class Solution:
def moveZeroes(self, nums: List[int]) -> None:
i = 0
for j in range(len(nums)):
if nums[j] != 0:
nums[i], nums[j] = nums[j], nums[i]
i += 1 | move-zeroes | Simple Python Solution | VicV13 | 3 | 128 | move zeroes | 283 | 0.614 | Easy | 5,067 |
https://leetcode.com/problems/move-zeroes/discuss/2234421/Python3-solution-using-two-pointers-faster-than-96 | class Solution:
def moveZeroes(self, nums: List[int]) -> None:
firstZero = None
for i in range(len(nums)):
if(nums[i] == 0):
if(firstZero == None):
firstZero = i
else:
if(firstZero!=None):
nums[i],nums[firstZero] = nums[firstZero],nums[i]
firstZero += 1 | move-zeroes | 📌 Python3 solution using two pointers faster than 96% | Dark_wolf_jss | 2 | 82 | move zeroes | 283 | 0.614 | Easy | 5,068 |
https://leetcode.com/problems/move-zeroes/discuss/1982832/Python-or-Two-Pointers | class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
slow = 0
fast = 0
while fast < len(nums):
if nums[fast] == 0:
fast += 1
else:
nums[slow], nums[fast] = nums[fast], nums[slow]
slow += 1
fast += 1 | move-zeroes | Python | Two Pointers | Mikey98 | 2 | 188 | move zeroes | 283 | 0.614 | Easy | 5,069 |
https://leetcode.com/problems/move-zeroes/discuss/1558315/Easiest-Python3-Beats-98 | class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
writer=0
for i, val in enumerate(nums):
if val!=0:
nums[writer], nums[i] = val, nums[writer]
writer+=1 | move-zeroes | Easiest Python3 Beats 98% | Blank__ | 2 | 283 | move zeroes | 283 | 0.614 | Easy | 5,070 |
https://leetcode.com/problems/move-zeroes/discuss/1524919/easy-solution-Python3 | class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
for i in nums:
if(i==0):
nums.remove(i)
nums.insert(len(nums),0)
return nums | move-zeroes | easy solution Python3 | RashmiBhaskar | 2 | 184 | move zeroes | 283 | 0.614 | Easy | 5,071 |
https://leetcode.com/problems/move-zeroes/discuss/1432781/Python-Two-pointer-Easy-Solution | class Solution:
def moveZeroes(self, nums: List[int]) -> None:
# i is the pointer which go through all the numbers in the array
# pos is the pointer which stop at position when there is a number 0, waiting there for a further swap
pos = 0
for i in range(len(nums)):
if nums[i] != 0:
nums[pos], nums[i] = nums[i], nums[pos]
pos += 1 | move-zeroes | Python Two-pointer Easy Solution | Janetcxy | 2 | 108 | move zeroes | 283 | 0.614 | Easy | 5,072 |
https://leetcode.com/problems/move-zeroes/discuss/1234199/Easy-python-solution | class Solution:
def moveZeroes(self, nums: List[int]) -> None:
c=0
x=len(nums)
if(x==1):
return nums
for i in range(x):
if(nums[i]==0 and i!=x-1):
nums[i-c]=nums[i+1]
c+=1
continue
nums[i-c]=nums[i]
for i in range(x-c,x):
nums[i]=0 | move-zeroes | Easy python solution | Sneh17029 | 2 | 1,000 | move zeroes | 283 | 0.614 | Easy | 5,073 |
https://leetcode.com/problems/move-zeroes/discuss/1161254/Python-Solution-without-swap-only-use-pop-and-append | class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
for idx in range(len(nums) -1 , -1, -1):
if nums[idx] == 0:
nums.pop(idx)
nums.append(0) | move-zeroes | Python Solution without swap, only use pop and append | real_tao4free | 2 | 411 | move zeroes | 283 | 0.614 | Easy | 5,074 |
https://leetcode.com/problems/move-zeroes/discuss/899394/Beats-100-of-memory-usage | class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
count = 0
zeroCount = 0
while count < len(nums):
if nums[count] == 0:
del nums[count]
zeroCount += 1
else:
count += 1
for i in range(zeroCount):
nums.append(0) | move-zeroes | Beats 100% of memory usage | JuanRodriguez | 2 | 282 | move zeroes | 283 | 0.614 | Easy | 5,075 |
https://leetcode.com/problems/move-zeroes/discuss/2536841/My-Python-solution-without-for-loop | class Solution:
def moveZeroes(self, nums: List[int]) -> None:
i = 0
j = 0
leng = len(nums)
while j < leng:
if nums[j] != 0:
nums[i], nums[j] = nums[j], nums[i]
i += 1
j+= 1 | move-zeroes | My Python solution without for loop | Speecial | 1 | 130 | move zeroes | 283 | 0.614 | Easy | 5,076 |
https://leetcode.com/problems/move-zeroes/discuss/2535078/EASY-PYTHON3-SOLUTION | class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
pos = 0
for i in range(len(nums)):
el = nums[i]
if el != 0:
nums[pos], nums[i] = nums[i], nums[pos]
pos += 1 | move-zeroes | 🔥 EASY PYTHON3 SOLUTION 🔥 | rajukommula | 1 | 23 | move zeroes | 283 | 0.614 | Easy | 5,077 |
https://leetcode.com/problems/move-zeroes/discuss/2418619/Python-Short-Easy-and-Faster-Solution-oror-Documented | class Solution:
def moveZeroes(self, nums: List[int]) -> None:
l = 0 # left pointer for non-zero value
for r in range(len(nums)): # right points to current value
if nums[r]: # if non-zero
nums[l], nums[r] = nums[r], nums[l] # swap the values
l += 1 # forward non-zero pointer | move-zeroes | [Python] Short, Easy and Faster Solution || Documented | Buntynara | 1 | 44 | move zeroes | 283 | 0.614 | Easy | 5,078 |
https://leetcode.com/problems/move-zeroes/discuss/2172768/Python-3-One-Line-99.04-fast-Solution | class Solution:
def moveZeroes(self, nums: List[int]) -> None:
nums[:] = [n for n in nums if n] + [0]*nums.count(0) | move-zeroes | [Python 3] One Line 99.04% fast Solution | omjinLTS | 1 | 64 | move zeroes | 283 | 0.614 | Easy | 5,079 |
https://leetcode.com/problems/move-zeroes/discuss/2157596/PYTHON-EASY-CODE | class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
c=0
while(0 in nums):
c=c+1
nums.remove(0)
for i in range(c):
nums.append(0) | move-zeroes | PYTHON - EASY CODE | T1n1_B0x1 | 1 | 85 | move zeroes | 283 | 0.614 | Easy | 5,080 |
https://leetcode.com/problems/move-zeroes/discuss/2094271/python3-3-solution-O(n)-O(1) | class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
return self.moveZerosOptimal(nums)
return self.moveZerosOptimalTwo(nums)
# return self.moveZeroesByPopAndAppend(nums)
# O(n) || O(1)
# runtime: 291ms 32.26%
def moveZerosOptimal(self, nums):
if not nums:return nums
nextPtr = 0
for num in nums:
if num != 0:
nums[nextPtr] = num
nextPtr += 1
for i in range(nextPtr, len(nums)):
nums[i] = 0
return nums
# O(n) || O(1)
def moveZerosOptimalTwo(self, nums):
if not nums:
return nums
left = 0
for right in range(len(nums)):
if nums[right]:
nums[left], nums[right] = nums[right], nums[left]
left += 1
return nums
# O(n) || O(1) space: but its a bad practice;
# appending a element is an O(1) operation but when you pop(O(1))
# all the elements to its right move to fill the space. O(n)
# runtime: 1698ms 5.69%
def moveZeroesByPopAndAppend(self, nums):
if not nums:
return nums
for i in nums:
if i == 0:
nums.remove(i)
nums.append(i)
return nums | move-zeroes | python3 3 solution O(n) O(1) | arshergon | 1 | 153 | move zeroes | 283 | 0.614 | Easy | 5,081 |
https://leetcode.com/problems/move-zeroes/discuss/1981752/Python-Easy-to-Conceptualize-Approach-(not-the-fastest) | class Solution:
def moveZeroes(self, nums: List[int]) -> None:
for i in nums:
if i == 0:
nums.remove(i)
nums.append(0)
return nums | move-zeroes | Python Easy to Conceptualize Approach (not the fastest) | c-freeman | 1 | 76 | move zeroes | 283 | 0.614 | Easy | 5,082 |
https://leetcode.com/problems/move-zeroes/discuss/1820038/Two-pointer-oror-Ez-to-understand-oror-O(n)-oror-Beats-99.81 | class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
i=j=0
hi=len(nums)-1
while(j<hi):
if nums[j]!=0:
nums[i], nums[j]=nums[j], nums[i]
i+=1
j+=1
nums[i], nums[hi]=nums[hi], nums[i] | move-zeroes | Two pointer || Ez to understand || O(n) || Beats 99.81% | ashu_py22 | 1 | 52 | move zeroes | 283 | 0.614 | Easy | 5,083 |
https://leetcode.com/problems/move-zeroes/discuss/1690361/Python-Intuitive-Optimal-O(n)-time-explained-Big-O-analysis | class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
replacementIndex = 0
for i, num in enumerate(nums):
if num != 0:
nums[replacementIndex] = num
replacementIndex += 1
endOfNonZero = replacementIndex
for index in range(endOfNonZero,len(nums)):
nums[index] = 0
return nums | move-zeroes | Python Intuitive Optimal O(n) time, explained Big O analysis | kenanR | 1 | 192 | move zeroes | 283 | 0.614 | Easy | 5,084 |
https://leetcode.com/problems/move-zeroes/discuss/1641203/Most-Easy-Understand-Solution-with-Python | class Solution:
def moveZeroes(self, nums: List[int]) -> None:
i = 0
for j in range(len(nums)):
if nums[j] != 0:
# swap element
nums[j], nums[i] = nums[i], nums[j]
i += 1 | move-zeroes | Most Easy Understand Solution with Python | qanghaa | 1 | 103 | move zeroes | 283 | 0.614 | Easy | 5,085 |
https://leetcode.com/problems/move-zeroes/discuss/1595816/93.21-of-Python3-online-submissions | class Solution:
def moveZeroes(self, nums: List[int]) -> None:
j=0
for i in range(len(nums)):
if nums[i]!=0:
nums[j],nums[i]=nums[i],nums[j]
j+=1
``` | move-zeroes | 93.21% of Python3 online submissions | harshmalviya7 | 1 | 114 | move zeroes | 283 | 0.614 | Easy | 5,086 |
https://leetcode.com/problems/move-zeroes/discuss/1437461/Python-Solution-2-Methods-With-explanation | class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
""" | move-zeroes | Python Solution- 2 Methods - With explanation | deleted_user | 1 | 104 | move zeroes | 283 | 0.614 | Easy | 5,087 |
https://leetcode.com/problems/move-zeroes/discuss/1363079/Move-zeros-getting-error | class Solution:
def moveZeroes(self, nums: List[int]) -> None:
temp =[]
zeros=[]
for i in range(len(nums)):
if nums[i] != 0:
temp.append(nums[i])
else:
zeros.append(nums[i])
temp1=sorted(temp)
nums = temp1 + zeros
return nums | move-zeroes | Move zeros getting error | gulsan | 1 | 28 | move zeroes | 283 | 0.614 | Easy | 5,088 |
https://leetcode.com/problems/move-zeroes/discuss/822500/Python3-easy-to-understand-95.60-Faster | class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
index1, index2 = 0, 1
while index2 <= len(nums)-1:
if nums[index1] != 0:
index1 += 1
index2 += 1
else:
if nums[index2] != 0:
temp = nums[index1]
nums[index1] = nums[index2]
nums[index2] = temp
else:
index2 += 1 | move-zeroes | Python3, easy to understand, 95.60% Faster | DerrickTsui | 1 | 113 | move zeroes | 283 | 0.614 | Easy | 5,089 |
https://leetcode.com/problems/move-zeroes/discuss/742533/python-simple-solution | class Solution(object):
def moveZeroes(self, nums):
for i in nums:
if i==0:
nums.remove(i)
nums.append(i)
return nums | move-zeroes | python simple solution | Namangarg98 | 1 | 116 | move zeroes | 283 | 0.614 | Easy | 5,090 |
https://leetcode.com/problems/move-zeroes/discuss/681529/Help-Required-Python3-Weird-Behaviour | class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
n = nums.count(0)
nums[:] = [i for i in nums if i != 0]
nums.extend([0 for i in range(n)]) | move-zeroes | Help Required Python3 Weird Behaviour | adi10hero | 1 | 50 | move zeroes | 283 | 0.614 | Easy | 5,091 |
https://leetcode.com/problems/move-zeroes/discuss/553959/Python-3-Solution-45ms-runtime-faster-than-most-submissions-%3A) | class Solution:
def moveZeroes(self, nums: List[int]) -> None:
i = 0
for j in range(0, len(nums)):
if(nums[j]!=0):
nums[j], nums[i] = nums[i], nums[j]
i += 1 | move-zeroes | Python 3 Solution 45ms runtime, faster than most submissions :) | Nilarjun | 1 | 120 | move zeroes | 283 | 0.614 | Easy | 5,092 |
https://leetcode.com/problems/move-zeroes/discuss/2843449/python-oror-simple-solution-oror-two-pointers | class Solution:
def moveZeroes(self, nums: List[int]) -> None:
idx = 0 # keep track of last non-zero
for i in range(len(nums)):
# non-zero
if nums[i]:
# swap idx, i
nums[i], nums[idx] = nums[idx], nums[i]
idx += 1 | move-zeroes | python || simple solution || two pointers | wduf | 0 | 2 | move zeroes | 283 | 0.614 | Easy | 5,093 |
https://leetcode.com/problems/move-zeroes/discuss/2842120/Check-it-out-beats-97.46-(Python-code) | class Solution(object):
def moveZeroes(self, nums):
i = 0
len_ = len(nums) - 1
while i != len_:
if nums[i] == 0:
del nums[i]
nums.append(0)
len_ -= 1
else:
i += 1
return nums | move-zeroes | Check it out, beats 97.46% (Python code) | Nematulloh | 0 | 1 | move zeroes | 283 | 0.614 | Easy | 5,094 |
https://leetcode.com/problems/move-zeroes/discuss/2841457/beats-94-in-time-65-in-mem-two-pointer-O(n)-time-in-place-O(1)-mem | class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
j = 0
for i in range(len(nums)):
if nums[i]: nums[j], j = nums[i], j+1
while j < len(nums): nums[j], j = 0, j+1 | move-zeroes | beats 94% in time, 65% in mem, two-pointer O(n) time in-place O(1) mem | Aritram | 0 | 1 | move zeroes | 283 | 0.614 | Easy | 5,095 |
https://leetcode.com/problems/move-zeroes/discuss/2840434/Python-two-pointer-solution | class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
# what if we use 1 pointer to read. we're seeking out non 0 values.
read_pointer = 0
# and one to write.
write_ptr = 0
# scan the read pointer along the full length of nums
while read_pointer < len(nums):
# if we find a non zero value.
if nums[read_pointer] != 0:
# copy the value into the index of write_ptr and
# advance the write_pointer.
nums[write_ptr] = nums[read_pointer]
write_ptr += 1
# always advance the read pointer. we're essentially skipping over the 0 values
# in this loop. this preserves the ordering.
read_pointer +=1
# if write_pointer is still less than the length, then fill in the rest of nums1 with 0's
# as we've already scanned for and written all the non zero values in.
while write_ptr < len(nums):
nums[write_ptr] = 0
write_ptr += 1
return | move-zeroes | Python two pointer solution | philipbarile | 0 | 2 | move zeroes | 283 | 0.614 | Easy | 5,096 |
https://leetcode.com/problems/move-zeroes/discuss/2836219/Wall-Approach-beats-93-ms-faster-or-Python | class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
# implement wall of good elements approach
i = 0
j = -1
while i < nums.__len__():
if nums[i] != 0:
j += 1
nums[j], nums[i] = nums[i], nums[j]
i += 1 | move-zeroes | Wall Approach beats 93% ms faster | Python | tejs_13 | 0 | 3 | move zeroes | 283 | 0.614 | Easy | 5,097 |
https://leetcode.com/problems/move-zeroes/discuss/2834309/Simple-Python-solution | class Solution:
def moveZeroes(self, nums: List[int]) -> None:
l = len(nums)
nz = 0
for i in range(l):
if nums[i] == 0:
nz += 1
continue
nums[i-nz] = nums[i]
ne = l-nz
nums[ne:] = [0]*nz | move-zeroes | Simple Python solution | user5472Pj | 0 | 4 | move zeroes | 283 | 0.614 | Easy | 5,098 |
https://leetcode.com/problems/move-zeroes/discuss/2831502/Python3-Simple-O(n)-2-pointer-solution | class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
[1, 3, 12, 0, 0]
| |
expand and shrink concept;
expand -> when both the pointers are pointing to zero
shirnk -> after a swap of zero ele is done;
[1, 2, -19, -1, 0]
l r
if left is 0 then swap with the right (non zero); make sure to expand till the left is non zero
[0, 0, 0 , 0]
l. r
[2, 3, 8, 8, 0, 0]
l. r
"""
left, right = 0, 1
while left < right and right < len(nums):
if nums[left] == 0 and nums[right] != 0:
nums[left], nums[right] = nums[right], nums[left]
left += 1
right += 1
elif nums[left] == 0 and nums[right] == 0:
right += 1
else:
left += 1
right += 1
return | move-zeroes | [Python3] - Simple O(n) 2 pointer solution | proGeekCoder | 0 | 5 | move zeroes | 283 | 0.614 | Easy | 5,099 |
Subsets and Splits