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/count-good-meals/discuss/1001094/Python-Hash-Table-based-solution | class Solution:
def countPairs(self, deliciousness: List[int]) -> int:
"""
A + B == 1 << i
A = 2 << i - B
"""
result = 0
seen = defaultdict(int)
deliciousness.sort()
for d in deliciousness:
n = 1
# because it is a sorted array.
# the maximum sum it can get by i-th number is deliciousness[i] + deliciousness[i]
while n <= d + d:
result = (result + seen[n-d]) % (10 ** 9 + 7)
n = n << 1
seen[d] += 1
return result | count-good-meals | Python Hash Table based solution | pochy | 0 | 145 | count good meals | 1,711 | 0.29 | Medium | 24,800 |
https://leetcode.com/problems/ways-to-split-array-into-three-subarrays/discuss/999157/Python3-binary-search-and-2-pointer | class Solution:
def waysToSplit(self, nums: List[int]) -> int:
prefix = [0]
for x in nums: prefix.append(prefix[-1] + x)
ans = 0
for i in range(1, len(nums)):
j = bisect_left(prefix, 2*prefix[i])
k = bisect_right(prefix, (prefix[i] + prefix[-1])//2)
ans += max(0, min(len(nums), k) - max(i+1, j))
return ans % 1_000_000_007 | ways-to-split-array-into-three-subarrays | [Python3] binary search & 2-pointer | ye15 | 65 | 4,900 | ways to split array into three subarrays | 1,712 | 0.325 | Medium | 24,801 |
https://leetcode.com/problems/ways-to-split-array-into-three-subarrays/discuss/999157/Python3-binary-search-and-2-pointer | class Solution:
def waysToSplit(self, nums: List[int]) -> int:
prefix = [0]
for x in nums: prefix.append(prefix[-1] + x)
ans = j = k = 0
for i in range(1, len(nums)):
j = max(j, i+1)
while j < len(nums) and 2*prefix[i] > prefix[j]: j += 1
k = max(k, j)
while k < len(nums) and 2*prefix[k] <= prefix[i] + prefix[-1]: k += 1
ans += k - j
return ans % 1_000_000_007 | ways-to-split-array-into-three-subarrays | [Python3] binary search & 2-pointer | ye15 | 65 | 4,900 | ways to split array into three subarrays | 1,712 | 0.325 | Medium | 24,802 |
https://leetcode.com/problems/ways-to-split-array-into-three-subarrays/discuss/1447421/Python-3-or-Binary-Search-or-Explanation | class Solution:
def waysToSplit(self, nums: List[int]) -> int:
mod, pre_sum = int(1e9+7), [nums[0]]
for num in nums[1:]: # create prefix sum array
pre_sum.append(pre_sum[-1] + num)
ans, n = 0, len(nums)
for i in range(n): # pre_sum[i] is the sum of the 1st segment
prev = pre_sum[i] # i+1 is the starting index of the 2nd segment
if prev * 3 > pre_sum[-1]: break # break loop if first segment is larger than the sum of 2 & 3 segments
j = bisect.bisect_left(pre_sum, prev * 2, i+1) # j is the first possible ending index of 2nd segment
middle = (prev + pre_sum[-1]) // 2 # last possible ending value of 2nd segment
k = bisect.bisect_right(pre_sum, middle, j+1) # k-1 is the last possible ending index of 2nd segment
if k-1 >= n or pre_sum[k-1] > middle: continue # make sure the value satisfy the condition since we are using bisect_right here
ans = (ans + min(k, n - 1) - j) % mod # count & handle edge case
return ans | ways-to-split-array-into-three-subarrays | Python 3 | Binary Search | Explanation | idontknoooo | 20 | 2,100 | ways to split array into three subarrays | 1,712 | 0.325 | Medium | 24,803 |
https://leetcode.com/problems/ways-to-split-array-into-three-subarrays/discuss/1511845/Well-Coded-oror-Both-Method-oror-Two-Pointer-oror-Binary-Search | class Solution:
def waysToSplit(self, nums: List[int]) -> int:
MOD = 10**9 + 7
n = len(nums)
for i in range(1,n):
nums[i]+=nums[i-1]
res,j,k = 0,0,0
for i in range(n-2):
if j<=i:
j = i+1
while j<n-1 and nums[i]>nums[j]-nums[i]:
j+=1
if k<j:
k = j
while k<n-1 and nums[k]-nums[i]<=nums[n-1]-nums[k]:
k += 1
res = (res + k - j)%MOD
return res | ways-to-split-array-into-three-subarrays | ππ Well-Coded || Both Method || Two-Pointer || Binary Search π | abhi9Rai | 3 | 735 | ways to split array into three subarrays | 1,712 | 0.325 | Medium | 24,804 |
https://leetcode.com/problems/ways-to-split-array-into-three-subarrays/discuss/1511845/Well-Coded-oror-Both-Method-oror-Two-Pointer-oror-Binary-Search | class Solution:
def waysToSplit(self, nums: List[int]) -> int:
mod, pre_sum = int(1e9+7), [nums[0]]
for num in nums[1:]: # create prefix sum array
pre_sum.append(pre_sum[-1] + num)
ans, n = 0, len(nums)
for i in range(n): # pre_sum[i] is the sum of the 1st segment
prev = pre_sum[i] # i+1 is the starting index of the 2nd segment
if prev * 3 > pre_sum[-1]: break # break loop if first segment is larger than the sum of 2 & 3 segments
j = bisect.bisect_left(pre_sum, prev * 2, i+1) # j is the first possible ending index of 2nd segment
middle = (prev + pre_sum[-1]) // 2 # last possible ending value of 2nd segment
k = bisect.bisect_right(pre_sum, middle, j+1) # k-1 is the last possible ending index of 2nd segment
if k-1 >= n or pre_sum[k-1] > middle: continue # make sure the value satisfy the condition since we are using bisect_right here
ans = (ans + min(k, n - 1) - j) % mod # count & handle edge case
return ans | ways-to-split-array-into-three-subarrays | ππ Well-Coded || Both Method || Two-Pointer || Binary Search π | abhi9Rai | 3 | 735 | ways to split array into three subarrays | 1,712 | 0.325 | Medium | 24,805 |
https://leetcode.com/problems/ways-to-split-array-into-three-subarrays/discuss/2839926/Linear-search-and-binary-search | class Solution:
def waysToSplit(self, nums: List[int]) -> int:
prefix_sum = [0]
for n in nums:
prefix_sum.append(prefix_sum[-1] + n)
res = 0
for i in range(1, len(nums) - 1):
for j in range(i+1, len(nums)):
left = prefix_sum[i] - prefix_sum[0]
mid = prefix_sum[j] - prefix_sum[i]
right = prefix_sum[-1] - prefix_sum[j]
#print(i, j, left, mid, right)
if left <= mid <= right:
res += 1
elif mid > right:
break
return res | ways-to-split-array-into-three-subarrays | Linear search and binary search | michaelniki | 0 | 2 | ways to split array into three subarrays | 1,712 | 0.325 | Medium | 24,806 |
https://leetcode.com/problems/ways-to-split-array-into-three-subarrays/discuss/2839926/Linear-search-and-binary-search | class Solution:
def waysToSplit(self, nums: List[int]) -> int:
prefix_sum = [0]
for n in nums:
prefix_sum.append(prefix_sum[-1] + n)
if prefix_sum[-1] == 0:
return (1 + len(nums) - 2) * (len(nums) -2) // 2 % 1_000_000_007
res = 0
for i in range(1, len(nums) - 1):
left_sum = prefix_sum[i] - prefix_sum[0]
left, right = i + 1, len(nums) - 1
while left < right:
mid = left + (right - left) // 2
mid_sum = prefix_sum[mid] - prefix_sum[i]
if mid_sum >= left_sum:
right = mid
else:
left = mid + 1
if prefix_sum[right] - prefix_sum[i] >= left_sum:
left_j = right
else:
continue
left, right = left_j, len(nums) - 1
while left < right:
mid = left + (right - left + 1) // 2
mid_sum = prefix_sum[mid] - prefix_sum[i]
right_sum = prefix_sum[-1] - prefix_sum[mid]
if mid_sum <= right_sum:
left = mid
else:
right = mid - 1
if prefix_sum[-1] - prefix_sum[left] >= prefix_sum[left] - prefix_sum[i]:
right_j = left
res = (res + right_j - left_j + 1) % 1_000_000_007
return res | ways-to-split-array-into-three-subarrays | Linear search and binary search | michaelniki | 0 | 2 | ways to split array into three subarrays | 1,712 | 0.325 | Medium | 24,807 |
https://leetcode.com/problems/ways-to-split-array-into-three-subarrays/discuss/2074135/Python-oror-Easy-Solution-oror-100 | * class Solution:
def waysToSplit(self, nums: List[int]) -> int:
n, MOD = len(nums), 10**9+7
arr = [0 for _ in range(n+1)]
for i, val in enumerate(nums, 1):
arr[i] = arr[i-1] + val
j = k = ans = 0
for i in range(1, n-1):
j = max(j, i+1)
while j < n-1 and arr[j]-arr[i] < arr[i]: j += 1
k = max(k, j)
while k < n-1 and arr[n]-arr[k+1] >= arr[k+1]-arr[i]: k += 1
if arr[i] > arr[j]-arr[i]: break
if arr[j]-arr[i] > arr[n]-arr[j]: continue
if (ans+k-j+1) > MOD:
ans=(ans+k-j+1) - MOD;
else:
ans =(ans+k-j+1)
return ans | ways-to-split-array-into-three-subarrays | β
Python || Easy Solution || 100% | keyxk | 0 | 491 | ways to split array into three subarrays | 1,712 | 0.325 | Medium | 24,808 |
https://leetcode.com/problems/ways-to-split-array-into-three-subarrays/discuss/1841519/python3-one-pass-loop-o(n) | class Solution:
def waysToSplit(self, nums: List[int]) -> int:
pre_sum = [0]
for n in nums:
pre_sum.append(pre_sum[-1] + n)
length = len(nums)
ret, mid_l, mid_r = 0, 0, 0
for i in range(1, length):
mid_l = max(mid_l, i + 1)
while mid_l < length and 2 * pre_sum[i] > pre_sum[mid_l]:
mid_l += 1
mid_r = max(mid_r, mid_l)
while mid_r < length and 2 * pre_sum[mid_r] <= pre_sum[i] + pre_sum[-1]:
mid_r += 1
ret += mid_r - mid_l
return ret % 1_000_000_007 | ways-to-split-array-into-three-subarrays | python3 one pass loop o(n) | BichengWang | 0 | 634 | ways to split array into three subarrays | 1,712 | 0.325 | Medium | 24,809 |
https://leetcode.com/problems/minimum-operations-to-make-a-subsequence/discuss/999141/Python3-binary-search | class Solution:
def minOperations(self, target: List[int], arr: List[int]) -> int:
loc = {x: i for i, x in enumerate(target)}
stack = []
for x in arr:
if x in loc:
i = bisect_left(stack, loc[x])
if i < len(stack): stack[i] = loc[x]
else: stack.append(loc[x])
return len(target) - len(stack) | minimum-operations-to-make-a-subsequence | [Python3] binary search | ye15 | 5 | 294 | minimum operations to make a subsequence | 1,713 | 0.492 | Hard | 24,810 |
https://leetcode.com/problems/minimum-operations-to-make-a-subsequence/discuss/2544675/Python3-Solution-or-LIS | class Solution:
def minOperations(self, target, arr):
n, nums = len(target), []
D = {target[i]: i for i in range(n)}
res = [D[i] for i in arr if i in D.keys()]
for i in res:
j = bisect.bisect_left(nums, i)
if j == len(nums): nums.append(i)
else: nums[j] = i
return n - len(nums) | minimum-operations-to-make-a-subsequence | β Python3 Solution | LIS | satyam2001 | 1 | 43 | minimum operations to make a subsequence | 1,713 | 0.492 | Hard | 24,811 |
https://leetcode.com/problems/minimum-operations-to-make-a-subsequence/discuss/999485/Python-Simplest-Solution-or-Binary-Search-or-Similar-to-300 | class Solution(object):
def minOperations(self, target, arr):
d = {num: idx for idx, num in enumerate(target)}
arr = [d.get(num, -1) for num in arr]
res = []
for num in arr:
if num == -1: continue
else:
pos = bisect.bisect_left(res, num)
if pos == len(res):
res.append(num)
else:
res[pos] = min(res[pos], num)
return len(target) - len(res) | minimum-operations-to-make-a-subsequence | [Python] Simplest Solution | Binary Search | Similar to #300 | ianliuy | 0 | 100 | minimum operations to make a subsequence | 1,713 | 0.492 | Hard | 24,812 |
https://leetcode.com/problems/calculate-money-in-leetcode-bank/discuss/1138960/Python-3-very-easy-solution | class Solution:
def totalMoney(self, n: int) -> int:
res,k=0,0
for i in range(n):
if i%7==0:
k+=1
res+=k+(i%7)
return res | calculate-money-in-leetcode-bank | Python 3 very easy solution | lin11116459 | 5 | 367 | calculate money in leetcode bank | 1,716 | 0.652 | Easy | 24,813 |
https://leetcode.com/problems/calculate-money-in-leetcode-bank/discuss/2689980/Recursive-solution-or-Python3 | class Solution:
def totalMoney(self, n: int) -> int:
def week(days, n=1, wek=7):
res = 0
for day in range(n, days+n):
res += day
print(day)
if day == wek:
return res + week(days-7, n+1, wek+1)
return res
return week(n) | calculate-money-in-leetcode-bank | Recursive solution | Python3 | mr6nie | 1 | 8 | calculate money in leetcode bank | 1,716 | 0.652 | Easy | 24,814 |
https://leetcode.com/problems/calculate-money-in-leetcode-bank/discuss/1206286/Python-Solution-or-20-ms-faster-than-99.48 | class Solution:
def totalMoney(self, n: int) -> int:
#here s is sum of 1 to 7
s = 28
res = 0
if n>7:
res = s
div = n//7
for i in range(1,div):
res+=s+7*i
rem = n%7
for i in range(1,rem+1):
res+=i+div
else:
for i in range(1,n+1):
res+=i
return res | calculate-money-in-leetcode-bank | Python Solution | 20 ms, faster than 99.48% | prachijpatel | 1 | 176 | calculate money in leetcode bank | 1,716 | 0.652 | Easy | 24,815 |
https://leetcode.com/problems/calculate-money-in-leetcode-bank/discuss/1057237/Python3-faster-than-83-Simple-Solution | class Solution:
def totalMoney(self, n: int) -> int:
if n<=7:
return int(n*(n+1)/2)
else:
l = [i for i in range(1,8)]
s=28
while n>0:
n-=7
l = [i+1 for i in l][:n]
if n<=7:
s += sum(l)
return s
else:
s += sum(l)
return s | calculate-money-in-leetcode-bank | [Python3 faster than 83%] Simple Solution | vatsalbhuva11 | 1 | 97 | calculate money in leetcode bank | 1,716 | 0.652 | Easy | 24,816 |
https://leetcode.com/problems/calculate-money-in-leetcode-bank/discuss/1026954/Python3-math-O(1) | class Solution:
def totalMoney(self, n: int) -> int:
q, r = divmod(n, 7)
return ((7*q + (49+2*r))*q + r*(r+1))//2 | calculate-money-in-leetcode-bank | [Python3] math O(1) | ye15 | 1 | 114 | calculate money in leetcode bank | 1,716 | 0.652 | Easy | 24,817 |
https://leetcode.com/problems/calculate-money-in-leetcode-bank/discuss/1026954/Python3-math-O(1) | class Solution:
def totalMoney(self, n: int) -> int:
ans = x = 0
for i in range(n):
if i%7 == 0: x += 1
ans += x + i%7
return ans | calculate-money-in-leetcode-bank | [Python3] math O(1) | ye15 | 1 | 114 | calculate money in leetcode bank | 1,716 | 0.652 | Easy | 24,818 |
https://leetcode.com/problems/calculate-money-in-leetcode-bank/discuss/1026954/Python3-math-O(1) | class Solution:
def totalMoney(self, n: int) -> int:
ans = val = 0
for x in range(n):
if x % 7 == 0: val = x//7 # reset
val += 1
ans += val
return ans | calculate-money-in-leetcode-bank | [Python3] math O(1) | ye15 | 1 | 114 | calculate money in leetcode bank | 1,716 | 0.652 | Easy | 24,819 |
https://leetcode.com/problems/calculate-money-in-leetcode-bank/discuss/1009220/Python-math-with-explanation | class Solution:
def totalMoney(self, n: int) -> int:
weeks, days = divmod(n, 7)
return (28 * weeks + # (1+2+...+7) = 28 * number of full weeks
(weeks-1) * 7 * weeks // 2 + # (0+7+14+28+..) adding 7 for weeks - 1 starting from the second one
(2*weeks + days + 1) * days // 2) # last week sum: (weeks + 1) + .... + [(weeks + 1) + (days - 1)] | calculate-money-in-leetcode-bank | Python math with explanation | blue_sky5 | 1 | 112 | calculate money in leetcode bank | 1,716 | 0.652 | Easy | 24,820 |
https://leetcode.com/problems/calculate-money-in-leetcode-bank/discuss/2836245/Simple-Python-solution | class Solution:
def totalMoney(self, n: int) -> int:
weeks = n // 7
remaining = n % 7
ans = 0
for i in range(weeks):
j = i+1
while j < i + 8:
ans += j
j += 1
if remaining > 0:
j = weeks + 1
while remaining > 0 and j < weeks + 7:
ans += j
j += 1
remaining -= 1
return ans | calculate-money-in-leetcode-bank | Simple Python solution | aruj900 | 0 | 1 | calculate money in leetcode bank | 1,716 | 0.652 | Easy | 24,821 |
https://leetcode.com/problems/calculate-money-in-leetcode-bank/discuss/2803991/Python-beats-95-(Simple-clean-solution) | class Solution:
def totalMoney(self, n: int) -> int:
sumn, start, loop = 28, 28, n // 7
if loop == 0: sumn = 0
for l in range(loop - 1):
sumn += start + 7
start += 7
for i in range(1, (n - 7 * loop) + 1) : sumn += i + loop
return sumn | calculate-money-in-leetcode-bank | Python beats 95% (Simple clean solution) | farruhzokirov00 | 0 | 6 | calculate money in leetcode bank | 1,716 | 0.652 | Easy | 24,822 |
https://leetcode.com/problems/calculate-money-in-leetcode-bank/discuss/2471851/Python | class Solution:
def totalMoney(self, n: int) -> int:
count_weeks = 0
count_days = 0
sum_m = 0
for i in range(n):
count_days += 1
sum_m += count_days + count_weeks
if count_days == 7:
count_weeks += 1
count_days = 0
return sum_m | calculate-money-in-leetcode-bank | Python | Yauhenish | 0 | 24 | calculate money in leetcode bank | 1,716 | 0.652 | Easy | 24,823 |
https://leetcode.com/problems/calculate-money-in-leetcode-bank/discuss/2449998/Simple-and-easy-to-understand | class Solution:
def totalMoney(self, n: int) -> int:
a=[]
cnt=0
b=1
c=1
cnt=0
while(n!=0):
a.append(b)
n=n-1
b=b+1
cnt=cnt+1
if(cnt==7):
c=c+1
b=c
cnt=0
return (sum(a)) | calculate-money-in-leetcode-bank | Simple and easy to understand | Durgavamsi | 0 | 25 | calculate money in leetcode bank | 1,716 | 0.652 | Easy | 24,824 |
https://leetcode.com/problems/calculate-money-in-leetcode-bank/discuss/2334695/easy-python-solution | class Solution:
def totalMoney(self, n: int) -> int:
monday = 1
amount, money, day = 0, 1, 0
while day < n :
if (day%7 == 0) and (day != 0) :
monday += 1
money = monday
amount += money
money += 1
day += 1
# print(amount, money, day, monday)
return amount | calculate-money-in-leetcode-bank | easy python solution | sghorai | 0 | 30 | calculate money in leetcode bank | 1,716 | 0.652 | Easy | 24,825 |
https://leetcode.com/problems/calculate-money-in-leetcode-bank/discuss/2317724/Easy-solution(Basic-looping-condition) | ```class Solution:
def totalMoney(self, n: int) -> int:
i = 1
j = i + 1
amount = 1
while n > 1:
n = n - 1
amount = amount + j
j += 1
if (j - i) == 7:
i += 1
j = i
return (amount) | calculate-money-in-leetcode-bank | Easy solution(Basic looping condition) | Jonny69 | 0 | 34 | calculate money in leetcode bank | 1,716 | 0.652 | Easy | 24,826 |
https://leetcode.com/problems/calculate-money-in-leetcode-bank/discuss/2114210/Python-One-Liner-with-O(1)-greaterTime-Complexity | class Solution:
def totalMoney(self, n: int) -> int:
return (28*(n//7)+7*((n//7)*((n//7)-1)//2))+int(((n%7)/2)*(2*(n//7)+1+(n%7))) | calculate-money-in-leetcode-bank | Python One Liner with O(1)->Time Complexity | Kunalbmd | 0 | 56 | calculate money in leetcode bank | 1,716 | 0.652 | Easy | 24,827 |
https://leetcode.com/problems/calculate-money-in-leetcode-bank/discuss/1947704/Python-Simple-and-Pure-Mathematical-Solution | class Solution:
def totalMoney(self, n: int) -> int:
ans = count = 0
while n != 0:
if n > 7:
# each iteration sum from 1 to 7 is 28
ans += 28 + count * 7
n -= 7
count += 1
else:
ans += (n*(n+1)//2) + count * n
n = 0
return ans | calculate-money-in-leetcode-bank | [Python] Simple and Pure Mathematical Solution | jamil117 | 0 | 57 | calculate money in leetcode bank | 1,716 | 0.652 | Easy | 24,828 |
https://leetcode.com/problems/calculate-money-in-leetcode-bank/discuss/1906858/Python-Solution | class Solution:
def totalMoney(self, n: int) -> int:
x, y = divmod(n, 7)
return sum([sum(range(i, i + 7)) for i in range(1, x + 1)]) + sum(range(x + 1, x + y + 1)) | calculate-money-in-leetcode-bank | Python Solution | hgalytoby | 0 | 59 | calculate money in leetcode bank | 1,716 | 0.652 | Easy | 24,829 |
https://leetcode.com/problems/calculate-money-in-leetcode-bank/discuss/1906858/Python-Solution | class Solution:
def totalMoney(self, n: int) -> int:
x, y = divmod(n, 7)
result = 0
for i in range(1, x + 1):
result += sum(range(i, i + 7))
return result + sum(range(x + 1, x + y + 1)) | calculate-money-in-leetcode-bank | Python Solution | hgalytoby | 0 | 59 | calculate money in leetcode bank | 1,716 | 0.652 | Easy | 24,830 |
https://leetcode.com/problems/calculate-money-in-leetcode-bank/discuss/1896360/Python-easy-logic-for-beginners | class Solution:
def totalMoney(self, n: int) -> int:
res = 0
if n <= 7:
for i in range(1, n+1):
res += i
return res
monday = 1
for i in range(n // 7):
for j in range(monday, monday + 7):
res += j
monday += 1
for i in range(monday, monday + (n % 7)):
res += i
return res | calculate-money-in-leetcode-bank | Python easy logic for beginners | alishak1999 | 0 | 35 | calculate money in leetcode bank | 1,716 | 0.652 | Easy | 24,831 |
https://leetcode.com/problems/calculate-money-in-leetcode-bank/discuss/1845561/4-Lines-Python-Solution-oror-75-Faster-oror-Memory-less-than-40 | class Solution:
def totalMoney(self, n: int) -> int:
ans=0 ; i=0 ; D={0:0, 1:1, 2:3, 3:6, 4:10, 5:15, 6:21}
if n<7: return D[n]
while n>=7: n=n-7 ; ans+=28+7*i ; i+=1
return ans+D[n]+n*i | calculate-money-in-leetcode-bank | 4-Lines Python Solution || 75% Faster || Memory less than 40% | Taha-C | 0 | 38 | calculate money in leetcode bank | 1,716 | 0.652 | Easy | 24,832 |
https://leetcode.com/problems/calculate-money-in-leetcode-bank/discuss/1845561/4-Lines-Python-Solution-oror-75-Faster-oror-Memory-less-than-40 | class Solution:
def totalMoney(self, n: int) -> int:
return sum([i//7+i%7+1 for i in range(n)]) | calculate-money-in-leetcode-bank | 4-Lines Python Solution || 75% Faster || Memory less than 40% | Taha-C | 0 | 38 | calculate money in leetcode bank | 1,716 | 0.652 | Easy | 24,833 |
https://leetcode.com/problems/calculate-money-in-leetcode-bank/discuss/1843971/Python-Solution | class Solution:
def totalMoney(self, n: int) -> int:
count = 0
j = (n//7) + 1
for i in range(j,j+n%7):
count += i
if n > 7:
count += 28
c = 28
for i in range((n//7)-1):
c += 7
count += c
return count | calculate-money-in-leetcode-bank | Python Solution | AakRay | 0 | 38 | calculate money in leetcode bank | 1,716 | 0.652 | Easy | 24,834 |
https://leetcode.com/problems/calculate-money-in-leetcode-bank/discuss/1790012/Python3-easy-to-understand | class Solution:
def totalMoney(self, n: int) -> int:
# Calculate number of weeks
numberOfWeeks = n // 7
# Calculate number of remaing days .i.e. if the input is not exactly divisible by 7
remainingDays = abs(n-numberOfWeeks*7)
count = 0
# Find sum for those number of weeks
for i in range(1, numberOfWeeks+1):
count += sum(range(i,i+7))
# Find the count for remaining days
count += sum(range(numberOfWeeks+1,numberOfWeeks+1+remainingDays))
return count | calculate-money-in-leetcode-bank | Python3 - easy to understand | htalanki2211 | 0 | 35 | calculate money in leetcode bank | 1,716 | 0.652 | Easy | 24,835 |
https://leetcode.com/problems/calculate-money-in-leetcode-bank/discuss/1489150/No-loop-one-formula-98-speed | class Solution:
def totalMoney(self, n: int) -> int:
w, d = divmod(n, 7)
return 28 * w + 7 * w * (w - 1) // 2 + (1 + w) * d + d * (d - 1) // 2 | calculate-money-in-leetcode-bank | No loop, one formula, 98% speed | EvgenySH | 0 | 145 | calculate money in leetcode bank | 1,716 | 0.652 | Easy | 24,836 |
https://leetcode.com/problems/calculate-money-in-leetcode-bank/discuss/1409048/Python3-Faster-Than-98.15-Math-Solution-and-Simulation-Solution | class Solution:
def totalMoney(self, n: int) -> int:
# Math Solution
w, d = divmod(n, 7)
result = w * 28 + 7 * w * (w - 1) / 2
result += (w * d) + d * (d + 1) / 2
return int(result)
# Simulation Solution
# class Solution:
# def totalMoney(self, n: int) -> int:
# i, s, init, limit = 1, 0, 1, 7
# while(True):
# s += i
# i += 1
# n -= 1
# if n == 0:
# return s
# if i == limit:
# s += i
# init += 1
# i = init
# n -= 1
# limit += 1
# if n == 0:
# return s | calculate-money-in-leetcode-bank | Python3 Faster Than 98.15% Math Solution & Simulation Solution | Hejita | 0 | 57 | calculate money in leetcode bank | 1,716 | 0.652 | Easy | 24,837 |
https://leetcode.com/problems/calculate-money-in-leetcode-bank/discuss/1142320/Python-3-or-O(n)-Time-O(1)-Space-or-Explanation | class Solution:
def totalMoney(self, n: int) -> int:
res = 0
curr = 1
prev = 1
pos = 1
while pos <= n:
res += curr
if pos % 7 == 0:
curr = prev + 1
prev += 1
else:
curr += 1
pos += 1
return res | calculate-money-in-leetcode-bank | Python 3 | O(n) Time O(1) Space | Explanation | abhyasa | 0 | 74 | calculate money in leetcode bank | 1,716 | 0.652 | Easy | 24,838 |
https://leetcode.com/problems/calculate-money-in-leetcode-bank/discuss/1113630/Python-or-Simple-Logic-or-Easy-To-Understand | class Solution:
def totalMoney(self, n: int) -> int:
monday=1
res = []
while n>0:
res.append(monday)
days=0
weekdays=monday
n-=1
while days<6 and n>0:
weekdays+=1
res.append(weekdays)
days+=1
n-=1
if n==0:
return sum(res)
monday+=1
return sum(res) | calculate-money-in-leetcode-bank | Python | Simple Logic | Easy To Understand | bharatgg | 0 | 59 | calculate money in leetcode bank | 1,716 | 0.652 | Easy | 24,839 |
https://leetcode.com/problems/calculate-money-in-leetcode-bank/discuss/1103272/Python | class Solution:
def totalMoney(self, n: int) -> int:
result = 0
# Accumulate for each "entire week"
for i in range(n//7):
result += self.accumulate(i+1)
# Accumulate for the last, "partial week"
result += self.accumulate(bias = (n // 7)+1, num_days = n % 7)
return result
def accumulate(self, bias=1, num_days=7):
"""Sums a range of a number, adding a bias."""
return sum([bias+i for i in range(num_days)]) | calculate-money-in-leetcode-bank | Python | dev-josh | 0 | 112 | calculate money in leetcode bank | 1,716 | 0.652 | Easy | 24,840 |
https://leetcode.com/problems/calculate-money-in-leetcode-bank/discuss/1102211/PYTHON-BY-A-WEEB | class Solution:
def totalMoney(self, n: int) -> int:
total = count = 0
day = money = 0
while day<n:
if day % 7 == 0: # one week
count+=1
money = count
total += money
money += 1
day+=1
return total | calculate-money-in-leetcode-bank | PYTHON BY A WEEB | Skywalker5423 | 0 | 84 | calculate money in leetcode bank | 1,716 | 0.652 | Easy | 24,841 |
https://leetcode.com/problems/calculate-money-in-leetcode-bank/discuss/1075126/Python-1-Liner-O(n) | class Solution:
def totalMoney(self, n: int) -> int:
return sum(sum(divmod(i, 7)) + 1 for i in range(n)) | calculate-money-in-leetcode-bank | Python - 1 Liner O(n) | leeteatsleep | 0 | 79 | calculate money in leetcode bank | 1,716 | 0.652 | Easy | 24,842 |
https://leetcode.com/problems/calculate-money-in-leetcode-bank/discuss/1072893/Python3-O(1)-two-lines-explained-formula | class Solution:
def totalMoney(self, n: int) -> int:
temp = 0
for i in range(1, n+1):
temp += (i-1) % 7 + (i-1) // 7
return n + temp | calculate-money-in-leetcode-bank | Python3 - O(1), two lines, explained formula | gaape47 | 0 | 110 | calculate money in leetcode bank | 1,716 | 0.652 | Easy | 24,843 |
https://leetcode.com/problems/calculate-money-in-leetcode-bank/discuss/1072893/Python3-O(1)-two-lines-explained-formula | class Solution:
def totalMoney(self, n: int) -> int:
a, b = (n-1) // 7, (n-1) % 7
return n + 21 * a + b * (b+1) // 2 + 7 * (a-1) * a // 2 + a * (b+1) | calculate-money-in-leetcode-bank | Python3 - O(1), two lines, explained formula | gaape47 | 0 | 110 | calculate money in leetcode bank | 1,716 | 0.652 | Easy | 24,844 |
https://leetcode.com/problems/calculate-money-in-leetcode-bank/discuss/1037727/Python3-simple-solution | class Solution:
def totalMoney(self, n: int) -> int:
a = 0
x = 1
sum = 0
for i in range(1,n+1):
if i % 7 == 1:
a += 1
x = a
sum += x
x += 1
return sum | calculate-money-in-leetcode-bank | Python3 simple solution | EklavyaJoshi | 0 | 51 | calculate money in leetcode bank | 1,716 | 0.652 | Easy | 24,845 |
https://leetcode.com/problems/calculate-money-in-leetcode-bank/discuss/1027546/faster-than-98.38-Python-3 | class Solution:
def totalMoney(self, n: int) -> int:
carry, remainder = divmod(n,7)
total = 0
for i in range(carry+1, remainder+carry+1):
total+=i
for i in range(carry):
total += 7 * (i + 4)
return total | calculate-money-in-leetcode-bank | [faster than 98.38 %] Python 3 | WiseLin | 0 | 74 | calculate money in leetcode bank | 1,716 | 0.652 | Easy | 24,846 |
https://leetcode.com/problems/calculate-money-in-leetcode-bank/discuss/1009033/Python-3-THREE-solutions-one-liner-math-and-simulation | class Solution:
def totalMoney(self, n: int) -> int:
return n//7*28 + n//7*(n//7-1)//2*7 + (n%7)*(n//7+1) + (n%7-1)*(n%7)//2
class Solution2:
def totalMoney(self, n: int) -> int:
fullWeeks=n//7
reminder=n%7
totalMoney=28*fullWeeks + 7*(fullWeeks-1)*fullWeeks//2 + reminder*(fullWeeks+1) + (reminder-1)*reminder//2
return totalMoney
class Solution1:
def totalMoney(self, n: int) -> int:
fullWeeks=0
totalMoney=0
for day in range(n):
if day%7==0: fullWeeks+=1
totalMoney+=fullWeeks+day%7
return totalMoney | calculate-money-in-leetcode-bank | Python 3, THREE solutions, one liner, math, and simulation | Silvia42 | 0 | 61 | calculate money in leetcode bank | 1,716 | 0.652 | Easy | 24,847 |
https://leetcode.com/problems/maximum-score-from-removing-substrings/discuss/1009152/Python-solution-with-explanation | class Solution:
def maximumGain(self, s: str, x: int, y: int) -> int:
# to calculate first, high value of x or y
a, b = 'ab', 'ba'
if y > x:
b, a, y, x = a, b, x, y
answer = 0
for word in [a, b]:
stack = []
i = 0
while i < len(s):
stack.append(s[i])
n = len(stack)
prefix = stack[n-2] + stack[n-1]
# if see the prefix ab or ba move from stack and increment the answer
if prefix == word:
answer += x
stack.pop()
stack.pop()
i += 1
# change the x point to y for 2nd iteration
x = y
# assign new letters with already removed prefix
s = ''.join(stack)
return answer | maximum-score-from-removing-substrings | Python solution with explanationππ» | just_4ina | 9 | 602 | maximum score from removing substrings | 1,717 | 0.461 | Medium | 24,848 |
https://leetcode.com/problems/maximum-score-from-removing-substrings/discuss/1061449/Python3-greedy-(via-two-counters) | class Solution:
def maximumGain(self, s: str, x: int, y: int) -> int:
a, b = "a", "b"
if x < y:
x, y = y, x
a, b = b, a
ans = cnt0 = cnt1 = 0
for c in s:
if c not in "ab":
ans += min(cnt0, cnt1) * y
cnt0 = cnt1 = 0
elif c == b:
if cnt0:
cnt0 -= 1
ans += x
else: cnt1 += 1
else: cnt0 += 1
return ans + min(cnt0, cnt1) * y | maximum-score-from-removing-substrings | [Python3] greedy (via two counters) | ye15 | 2 | 128 | maximum score from removing substrings | 1,717 | 0.461 | Medium | 24,849 |
https://leetcode.com/problems/construct-the-lexicographically-largest-valid-sequence/discuss/1008948/Python-Greedy%2BBacktracking-or-Well-Explained-or-Comments | class Solution:
def constructDistancedSequence(self, n: int) -> List[int]:
arr = [0]*(2*n-1) # the array we want to put numbers. 0 means no number has been put here
i = 0 # current index to put a number
vi = [False] * (n+1) # check if we have used that number
# backtracking
def dfs(arr, i, vi):
# if we already fill the array successfully, return True
if i >= (2*n-1):
return True
# try each number from n to 1
for x in range(n, 0, -1):
# two cases:
# x > 1, we check two places. Mind index out of bound here.
# x = 1, we only check one place
# arr[i] == 0 means index i is not occupied
if (x > 1 and ((not (arr[i] == 0 and (i+x < 2*n-1) and arr[i+x] == 0)) or vi[x])) \
or (x == 1 and (arr[i] != 0 or vi[x])):
continue
# if it can be placed, then place it
if x > 1:
arr[i] = x
arr[i+x] = x
else:
arr[i] = x
vi[x] = True
# find the next available place
nexti = i+1
while nexti < 2*n-1 and arr[nexti]:
nexti += 1
# place the next one
if dfs(arr, nexti, vi):
# if it success, it is already the lexicographically largest one, we don't search anymore
return True
# backtracking... restore the state
if x > 1:
arr[i] = 0
arr[i+x] = 0
else:
arr[i] = 0
vi[x] = False
# we could not find a solution, return False
return False
dfs(arr, i, vi)
return arr | construct-the-lexicographically-largest-valid-sequence | Python Greedy+Backtracking | Well Explained | Comments | etoss | 23 | 1,800 | construct the lexicographically largest valid sequence | 1,718 | 0.516 | Medium | 24,850 |
https://leetcode.com/problems/construct-the-lexicographically-largest-valid-sequence/discuss/1062480/Python3-backtracking | class Solution:
def constructDistancedSequence(self, n: int) -> List[int]:
ans = [0]*(2*n-1)
def fn(i):
"""Return largest sequence after filling in ith position."""
if i == 2*n-1 or ans[i] and fn(i+1): return True
for x in reversed(range(1, n+1)):
if x not in ans:
ii = x if x > 1 else 0
if i+ii < 2*n-1 and ans[i] == ans[i+ii] == 0:
ans[i] = ans[i+ii] = x
if fn(i+1): return True
ans[i] = ans[i+ii] = 0
fn(0)
return ans | construct-the-lexicographically-largest-valid-sequence | [Python3] backtracking | ye15 | 2 | 185 | construct the lexicographically largest valid sequence | 1,718 | 0.516 | Medium | 24,851 |
https://leetcode.com/problems/construct-the-lexicographically-largest-valid-sequence/discuss/2717913/Python-Backtracking-Solution-Faster-than-91 | class Solution:
def constructDistancedSequence(self, n: int) -> List[int]:
ans, visited = [0] * (2 * n - 1), [False] * (n + 1)
def backtrack(idx: int) -> bool:
nonlocal ans, visited, n
if idx == len(ans):
return True
if ans[idx] != 0:
return backtrack(idx + 1)
else:
for num in range(n, 0, -1):
if visited[num]:
continue
visited[num], ans[idx] = True, num
if num == 1:
if backtrack(idx + 1):
return True
elif idx + num < len(ans) and ans[idx + num] == 0:
ans[num + idx] = num
if backtrack(idx + 1):
return True
ans[idx + num] = 0
ans[idx], visited[num] = 0, False
return False
backtrack(0)
return ans | construct-the-lexicographically-largest-valid-sequence | Python Backtracking Solution, Faster than 91% | hemantdhamija | 0 | 14 | construct the lexicographically largest valid sequence | 1,718 | 0.516 | Medium | 24,852 |
https://leetcode.com/problems/construct-the-lexicographically-largest-valid-sequence/discuss/1633386/Python-Simple-Greedy-Backtracking | class Solution:
def constructDistancedSequence(self, n: int) -> List[int]:
self.size = 2*n-1 #size of the array
self.arr = [-1]*self.size #construct output array
def solve(i, seen):
if len(seen) == n or i >= self.size: #if we have seen all n numbers or i > self.size return true
return True
if self.arr[i] != -1: #move to next index if current one is taken
return solve(i+1, seen)
for idx in range(n, 0, -1):
if idx in seen: continue #continue if this number has been used
if i+idx >= self.size and idx != 1: continue #continue if this number would be out of index
if idx != 1 and self.arr[i+idx] != -1: continue #continue if the element that in index i+idx (this is the distance) is not available
seen.add(idx)
#add the number to the array
self.arr[i] = idx
if idx != 1:
self.arr[i+idx] = idx
ans = solve(i+1, seen)
if ans: return True #stop once we find the first working sequence
elif idx != 1: self.arr[i+idx] = -1 #if sequence did not work reset the element at index i+idx.
#no need to do this for index i since it will be overwritten next iteration
seen.remove(idx)
self.arr[i] = -1 #reset index if no numbers worked
return False
solve(0, set())
return self.arr | construct-the-lexicographically-largest-valid-sequence | [Python] Simple Greedy Backtracking | LazaroHurt | 0 | 158 | construct the lexicographically largest valid sequence | 1,718 | 0.516 | Medium | 24,853 |
https://leetcode.com/problems/construct-the-lexicographically-largest-valid-sequence/discuss/1062954/Python-Greedy-backtracking-with-explanation-and-comments | class Solution:
def constructDistancedSequence(self, n: int) -> List[int]:
# to check what all numbers have been used
vis = [False] * (n + 1)
# intermediate array to build the final sequence
curr_list = [-1] * (2*n - 1)
li, ans_list = self.recur(vis, curr_list, 0, n, n)
return ans_list
def recur(self, vis, curr_list, curr_ind, n, rem):
# base conditon which is to check that we have used all the 'n' numbers
if rem == 0:
return True, curr_list
# check what index we have to fill in the intermediate array
while(curr_list[curr_ind] != -1 and curr_ind < 2 * n - 1):
curr_ind += 1
ans = False
ans_list = None
for i in range(len(vis) - 1, 0, -1):
addition = i
# special handling of '1'
if i == 1:
addition = 0
# only numbers that are not already used and check for feasibility using the constraints given
if not vis[i] and self.check_feasible(curr_list, curr_ind, addition, n):
vis[i] = True
curr_list[curr_ind] = i
curr_list[curr_ind + addition] = i
is_list, li = self.recur(vis, curr_list, curr_ind + 1, n, rem - 1)
if is_list:
ans = True
ans_list = li
break
curr_list[curr_ind] = -1
curr_list[curr_ind + addition] = -1
vis[i] = False
return ans, ans_list
def check_feasible(self, curr_list, curr_ind, addition, n):
if curr_ind + addition < 2*n - 1 and curr_list[curr_ind] == -1 and curr_list[curr_ind + addition] == -1:
return True
return False | construct-the-lexicographically-largest-valid-sequence | [Python] Greedy backtracking with explanation and comments | vasu6 | 0 | 140 | construct the lexicographically largest valid sequence | 1,718 | 0.516 | Medium | 24,854 |
https://leetcode.com/problems/number-of-ways-to-reconstruct-a-tree/discuss/1128518/Python3-greedy | class Solution:
def checkWays(self, pairs: List[List[int]]) -> int:
graph = {}
for x, y in pairs:
graph.setdefault(x, set()).add(y)
graph.setdefault(y, set()).add(x)
ans = 1
ancestors = set()
for n in sorted(graph, key=lambda x: len(graph[x]), reverse=True):
p = min(ancestors & graph[n], key=lambda x: len(graph[x]), default=None) # immediate ancestor
ancestors.add(n)
if p:
if graph[n] - (graph[p] | {p}): return 0 # impossible to have more than ancestor
if len(graph[n]) == len(graph[p]): ans = 2
elif len(graph[n]) != len(graph)-1: return 0
return ans | number-of-ways-to-reconstruct-a-tree | [Python3] greedy | ye15 | 5 | 330 | number of ways to reconstruct a tree | 1,719 | 0.43 | Hard | 24,855 |
https://leetcode.com/problems/number-of-ways-to-reconstruct-a-tree/discuss/1128518/Python3-greedy | class Solution:
def checkWays(self, pairs: List[List[int]]) -> int:
nodes = set()
graph = {}
degree = {}
for x, y in pairs:
nodes |= {x, y}
graph.setdefault(x, set()).add(y)
graph.setdefault(y, set()).add(x)
degree[x] = 1 + degree.get(x, 0)
degree[y] = 1 + degree.get(y, 0)
if max(degree.values()) < len(nodes) - 1: return 0 # no root
for n in nodes:
if degree[n] < len(nodes)-1:
nei = set()
for nn in graph[n]:
if degree[n] >= degree[nn]: nei |= graph[nn] # brothers & childrens
if nei - {n} - graph[n]: return 0 # impossible
for n in nodes:
if any(degree[n] == degree[nn] for nn in graph[n]): return 2 # brothers
return 1 | number-of-ways-to-reconstruct-a-tree | [Python3] greedy | ye15 | 5 | 330 | number of ways to reconstruct a tree | 1,719 | 0.43 | Hard | 24,856 |
https://leetcode.com/problems/decode-xored-array/discuss/1075067/Python-1-Liner-(List-Comprehension-with-Assignment-Expresion) | class Solution:
def decode(self, encoded: List[int], first: int) -> List[int]:
return [first] + [first:= first ^ x for x in encoded] | decode-xored-array | Python - 1 Liner (List Comprehension with Assignment Expresion) | leeteatsleep | 17 | 957 | decode xored array | 1,720 | 0.86 | Easy | 24,857 |
https://leetcode.com/problems/decode-xored-array/discuss/1056155/Simple-python-3-liner | class Solution:
def decode(self, encoded: List[int], first: int) -> List[int]:
arr = [first]
for i in range(0, len(encoded)):
arr.append(arr[i] ^ encoded[i])
return arr | decode-xored-array | Simple python 3-liner | vanigupta20024 | 5 | 459 | decode xored array | 1,720 | 0.86 | Easy | 24,858 |
https://leetcode.com/problems/decode-xored-array/discuss/1200363/Python3-simple-solution | class Solution:
def decode(self, encoded: List[int], first: int) -> List[int]:
arr = [first]
for i in encoded:
arr.append(i^arr[-1])
return arr | decode-xored-array | Python3 simple solution | EklavyaJoshi | 4 | 321 | decode xored array | 1,720 | 0.86 | Easy | 24,859 |
https://leetcode.com/problems/decode-xored-array/discuss/1055052/Python-3-solution-optimal-space-and-time-complexity | class Solution:
def decode(self, encoded: List[int], first: int) -> List[int]:
ans = [first]
for i in range(len(encoded)):
ans.append(encoded[i] ^ ans[-1])
return ans | decode-xored-array | Python 3 solution optimal space and time complexity | cutequokka | 4 | 344 | decode xored array | 1,720 | 0.86 | Easy | 24,860 |
https://leetcode.com/problems/decode-xored-array/discuss/1055052/Python-3-solution-optimal-space-and-time-complexity | class Solution:
def decode(self, encoded: List[int], first: int) -> List[int]:
encoded.insert(0, first)
for i in range(1, len(encoded)):
encoded[i] = encoded[i-1] ^ encoded[i]
return encoded | decode-xored-array | Python 3 solution optimal space and time complexity | cutequokka | 4 | 344 | decode xored array | 1,720 | 0.86 | Easy | 24,861 |
https://leetcode.com/problems/decode-xored-array/discuss/1625442/Python-O(n)-TC-O(1)-space-complexity-(92-100) | class Solution(object):
def decode(self, encoded, first):
"""
:type encoded: List[int]
:type first: int
:rtype: List[int]
"""
encoded.insert(0, first)
for i in range(1, len(encoded)):
encoded[i] = encoded[i]^encoded[i-1]
return encoded | decode-xored-array | [Python] O(n) TC; O(1) space complexity (92%; 100%) | nelsarrag | 3 | 149 | decode xored array | 1,720 | 0.86 | Easy | 24,862 |
https://leetcode.com/problems/decode-xored-array/discuss/1009783/Python3-scan-O(N) | class Solution:
def decode(self, encoded: List[int], first: int) -> List[int]:
ans = [first]
for x in encoded:
ans.append(ans[-1] ^ x)
return ans | decode-xored-array | [Python3] scan O(N) | ye15 | 3 | 202 | decode xored array | 1,720 | 0.86 | Easy | 24,863 |
https://leetcode.com/problems/decode-xored-array/discuss/1012920/Python-3-Liner-or-Easy-Solution-with-explanation | class Solution:
def decode(self, encoded, first):
res = []
for i in range(0,len(encoded)+1):
res.append(0^first if i==0 else encoded[i-1]^res[i-1])
return res | decode-xored-array | Python 3 Liner | Easy Solution with explanation | hritik5102 | 2 | 161 | decode xored array | 1,720 | 0.86 | Easy | 24,864 |
https://leetcode.com/problems/decode-xored-array/discuss/1794971/python3-or-easy-solution-or-bit-manipulation | class Solution:
def decode(self, encoded: List[int], first: int) -> List[int]:
arr=[first]
for i in encoded:
arr.append(arr[-1]^i)
return arr | decode-xored-array | python3 | easy solution | bit manipulation | Anilchouhan181 | 1 | 78 | decode xored array | 1,720 | 0.86 | Easy | 24,865 |
https://leetcode.com/problems/decode-xored-array/discuss/1306715/Easy-Python-Solution(98.98) | class Solution:
def decode(self, encoded: List[int], first: int) -> List[int]:
a=[]
a.append(first)
x=first
for i in encoded:
x^=i
a.append(x)
return a | decode-xored-array | Easy Python Solution(98.98%) | Sneh17029 | 1 | 311 | decode xored array | 1,720 | 0.86 | Easy | 24,866 |
https://leetcode.com/problems/decode-xored-array/discuss/1140269/Python-3-Solution | class Solution:
def decode(self, encoded: List[int], first: int) -> List[int]:
z = len(encoded) + 1
l = [0]* z
l[0] = first
for i in range(len(encoded)):
l[i+1] = l[i] ^ encoded[i]
return l | decode-xored-array | Python 3 Solution | iamvatsalpatel | 1 | 181 | decode xored array | 1,720 | 0.86 | Easy | 24,867 |
https://leetcode.com/problems/decode-xored-array/discuss/2830855/Decode-xored-array-in-O(1)-space | class Solution:
def decode(self, encoded: List[int], first: int) -> List[int]:
encoded.insert(0, first)
for i in range(1, len(encoded)):
encoded[i] = encoded[i] ^ encoded[i-1]
return encoded | decode-xored-array | Decode xored array in O(1) space | pratiklilhare | 0 | 2 | decode xored array | 1,720 | 0.86 | Easy | 24,868 |
https://leetcode.com/problems/decode-xored-array/discuss/2817279/PYTHON3-BEST | class Solution:
def decode(self, encoded: List[int], first: int) -> List[int]:
r = [first]
for i in encoded:
r.append(r[-1]^i)
return r | decode-xored-array | PYTHON3 BEST | Gurugubelli_Anil | 0 | 2 | decode xored array | 1,720 | 0.86 | Easy | 24,869 |
https://leetcode.com/problems/decode-xored-array/discuss/2770538/oror-Python-easy-solution-oror | class Solution:
def decode(self, encoded: List[int], first: int) -> List[int]:
ans = [first]
for item in encoded:
ans.append(ans[-1] ^ item)
return ans | decode-xored-array | || Python easy solution || | parth_panchal_10 | 0 | 5 | decode xored array | 1,720 | 0.86 | Easy | 24,870 |
https://leetcode.com/problems/decode-xored-array/discuss/2691635/Simple-python-code-with-explanation | class Solution:
def decode(self, encoded, first):
#first 1 in original array is 1
ans = [first]
#main logic
#ans[i] ^ arr[i+1] = encoded [i]
#ans[i+1] = encoded[i] ^ ans[i]
#iterate over the numbers in encoded list
for x in encoded:
#add (last element ^ encoded[i]) at end of ans(original) list
ans.append(ans[-1]^x)
#after iterating over the encoded list
#return original list(and)
return ans | decode-xored-array | Simple python code with explanation | thomanani | 0 | 6 | decode xored array | 1,720 | 0.86 | Easy | 24,871 |
https://leetcode.com/problems/decode-xored-array/discuss/2504126/Python-or-100-faster-submission-or-Very-simple-solution-O(n) | class Solution:
def decode(self, encoded: List[int], first: int) -> List[int]:
arr = [first]
for ele in encoded:
arr.append(arr[-1] ^ ele)
return arr | decode-xored-array | Python | 100% faster submission | Very simple solution O(n) | __Asrar | 0 | 44 | decode xored array | 1,720 | 0.86 | Easy | 24,872 |
https://leetcode.com/problems/decode-xored-array/discuss/1921823/Python-easy-and-beginner-friendly-solution | class Solution:
def decode(self, encoded: List[int], first: int) -> List[int]:
res = [first]
for i in range(len(encoded)):
res.append(encoded[i] ^ res[i])
return res | decode-xored-array | Python easy and beginner friendly solution | alishak1999 | 0 | 121 | decode xored array | 1,720 | 0.86 | Easy | 24,873 |
https://leetcode.com/problems/decode-xored-array/discuss/1854789/Easy-Python-Code | class Solution:
def decode(self, encoded: List[int], first: int) -> List[int]:
finlist = []
finlist.append(first)
x = first
for i in encoded:
x = i^x
finlist.append(x)
return finlist | decode-xored-array | Easy Python Code | natscripts | 0 | 82 | decode xored array | 1,720 | 0.86 | Easy | 24,874 |
https://leetcode.com/problems/decode-xored-array/discuss/1847117/Python-dollarolution | class Solution:
def decode(self, encoded: List[int], first: int) -> List[int]:
v = [first]
for i in encoded:
v.append(v[-1]^i)
return v | decode-xored-array | Python $olution | AakRay | 0 | 41 | decode xored array | 1,720 | 0.86 | Easy | 24,875 |
https://leetcode.com/problems/decode-xored-array/discuss/1829244/3-Lines-Python-Solution-oror-70-Faster-oror-Memory-less-than-60 | class Solution:
def decode(self, encoded: List[int], first: int) -> List[int]:
arr=[first]
for i in range(len(encoded)): arr.append(encoded[i]^arr[-1])
return arr | decode-xored-array | 3-Lines Python Solution || 70% Faster || Memory less than 60% | Taha-C | 0 | 64 | decode xored array | 1,720 | 0.86 | Easy | 24,876 |
https://leetcode.com/problems/decode-xored-array/discuss/1817852/Python-Easy-Solution-to-double-beats-90 | class Solution:
def decode(self, encoded: List[int], first: int) -> List[int]:
yield first
for e in encoded :
first = e ^ first
yield first | decode-xored-array | [Python] Easy Solution to double beats 90% | crazypuppy | 0 | 47 | decode xored array | 1,720 | 0.86 | Easy | 24,877 |
https://leetcode.com/problems/decode-xored-array/discuss/1751126/Easy-Python-Solution | class Solution:
def decode(self, encoded: List[int], first: int) -> List[int]:
encoded.insert(0,first)
for i in range(1,len(encoded)):
encoded[i] = encoded[i]^encoded[i-1]
return encoded | decode-xored-array | Easy Python Solution | MengyingLin | 0 | 41 | decode xored array | 1,720 | 0.86 | Easy | 24,878 |
https://leetcode.com/problems/decode-xored-array/discuss/1556382/Python-Easy-Solution-or-Faster-than-96 | class Solution:
def decode(self, encoded: List[int], first: int) -> List[int]:
arr = [first]
for i in range(len(encoded)):
arr.append(arr[i] ^ encoded[i])
return arr | decode-xored-array | Python Easy Solution | Faster than 96% | leet_satyam | 0 | 195 | decode xored array | 1,720 | 0.86 | Easy | 24,879 |
https://leetcode.com/problems/decode-xored-array/discuss/1439014/Python3-extra-space-O(1) | class Solution:
def decode(self, encoded: List[int], first: int) -> List[int]:
encoded = [first] + encoded
for i in range(1,len(encoded)):
first = first ^ encoded[i]
encoded[i] = first
return encoded | decode-xored-array | Python3 extra space O(1) | rstudy211 | 0 | 101 | decode xored array | 1,720 | 0.86 | Easy | 24,880 |
https://leetcode.com/problems/decode-xored-array/discuss/1262386/Python-or-Runtime%3A-220-ms-faster-than-89.15-or-Memory-Usage%3A-16-MB-less-than-18.72 | class Solution:
def decode(self, encoded: List[int], first: int) -> List[int]:
res = [first]
for i in encoded:
res.append(i ^ res[-1])
return res | decode-xored-array | Python | Runtime: 220 ms, faster than 89.15% | Memory Usage: 16 MB, less than 18.72% | s13rw81 | 0 | 69 | decode xored array | 1,720 | 0.86 | Easy | 24,881 |
https://leetcode.com/problems/decode-xored-array/discuss/1145563/Python-simple-easy-solution | class Solution(object):
def decode(self, encoded, first):
li = [first]
for i in range(0, len(encoded)):
li.append(li[i]^encoded[i])
return li | decode-xored-array | Python simple easy solution | akashadhikari | 0 | 109 | decode xored array | 1,720 | 0.86 | Easy | 24,882 |
https://leetcode.com/problems/decode-xored-array/discuss/1029005/Python-3-Runtime-faster-than-97.34-Memory-less-than-89.07 | class Solution:
def decode(self, encoded, first):
new_array = [first]
for i in encoded:
new_array.append(new_array[-1] ^ i)
return new_array | decode-xored-array | Python 3 Runtime faster than 97.34% Memory less than 89.07% | WiseLin | 0 | 176 | decode xored array | 1,720 | 0.86 | Easy | 24,883 |
https://leetcode.com/problems/decode-xored-array/discuss/1010691/Python-Easy-100-Time-and-100-Space | class Solution:
def decode(self, encoded: List[int], first: int) -> List[int]:
arr = [first]
for i in range(len(encoded)):
arr.append(arr[i]^encoded[i])
return arr | decode-xored-array | Python Easy 100% Time and 100% Space | shubhangi28 | 0 | 129 | decode xored array | 1,720 | 0.86 | Easy | 24,884 |
https://leetcode.com/problems/swapping-nodes-in-a-linked-list/discuss/1911996/Python-Simple-Solution-with-Explanation | class Solution:
def swapNodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
l = head # left node
for _ in range(k-1):
l = l.next
# the rest of the code logic here | swapping-nodes-in-a-linked-list | [Python] Simple Solution with Explanation | zayne-siew | 82 | 2,800 | swapping nodes in a linked list | 1,721 | 0.677 | Medium | 24,885 |
https://leetcode.com/problems/swapping-nodes-in-a-linked-list/discuss/1911996/Python-Simple-Solution-with-Explanation | class Solution:
def swapNodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
# Find kth node from left
l = r = head
for _ in range(k-1):
l = l.next
# Find kth node from right
# by finding tail node
tail = l
while tail.next:
r, tail = r.next, tail.next
# Swap values and return
l.val, r.val = r.val, l.val
return head | swapping-nodes-in-a-linked-list | [Python] Simple Solution with Explanation | zayne-siew | 82 | 2,800 | swapping nodes in a linked list | 1,721 | 0.677 | Medium | 24,886 |
https://leetcode.com/problems/swapping-nodes-in-a-linked-list/discuss/1109117/Python3-easy-soln-Swapping-Nodes-in-a-Linked-List | class Solution:
def swapNodes(self, head: ListNode, k: int) -> ListNode:
res = []
curr = head
while curr is not None:
res.append(curr)
curr = curr.next
res[k-1].val, res[len(res)-k].val = res[len(res)-k].val, res[k-1].val
return head | swapping-nodes-in-a-linked-list | [Python3] easy soln - Swapping Nodes in a Linked List | avEraGeC0der | 4 | 365 | swapping nodes in a linked list | 1,721 | 0.677 | Medium | 24,887 |
https://leetcode.com/problems/swapping-nodes-in-a-linked-list/discuss/1009949/Python3-via-array | class Solution:
def swapNodes(self, head: ListNode, k: int) -> ListNode:
vals = []
node = head
while node:
vals.append(node.val)
node = node.next
vals[k-1], vals[-k] = vals[-k], vals[k-1]
dummy = node = ListNode()
for x in vals:
node.next = node = ListNode(x)
return dummy.next | swapping-nodes-in-a-linked-list | [Python3] via array | ye15 | 4 | 186 | swapping nodes in a linked list | 1,721 | 0.677 | Medium | 24,888 |
https://leetcode.com/problems/swapping-nodes-in-a-linked-list/discuss/1009949/Python3-via-array | class Solution:
def swapNodes(self, head: ListNode, k: int) -> ListNode:
node = n1 = n2 = head
while node:
if k == 1: n1 = node
if k <= 0: n2 = n2.next
node = node.next
k -= 1
n1.val, n2.val = n2.val, n1.val
return head | swapping-nodes-in-a-linked-list | [Python3] via array | ye15 | 4 | 186 | swapping nodes in a linked list | 1,721 | 0.677 | Medium | 24,889 |
https://leetcode.com/problems/swapping-nodes-in-a-linked-list/discuss/1912576/Python-Easy-or-3-Solutions-Explained | class Solution:
def swapNodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
def kFromStartAndlength(head,k):
kthNode,count = None, 0
while head:
count += 1
if count == k: kthNode = head
head = head.next
return kthNode, count
kthNode, length = kFromStartAndlength(head,k)
right = head
for i in range(length - k):
right = right.next
right.val, kthNode.val = kthNode.val, right.val
return head | swapping-nodes-in-a-linked-list | β
Python Easy | 3 Solutions Explained | dhananjay79 | 3 | 224 | swapping nodes in a linked list | 1,721 | 0.677 | Medium | 24,890 |
https://leetcode.com/problems/swapping-nodes-in-a-linked-list/discuss/1912576/Python-Easy-or-3-Solutions-Explained | class Solution:
def swapNodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
kthNodeFromStart = head
for i in range(k-1):
kthNodeFromStart = kthNodeFromStart.next
kthNodeFromEnd, itr = head, kthNodeFromStart
while itr.next:
kthNodeFromEnd = kthNodeFromEnd.next
itr = itr.next
kthNodeFromStart.val, kthNodeFromEnd.val = kthNodeFromEnd.val, kthNodeFromStart.val
return head | swapping-nodes-in-a-linked-list | β
Python Easy | 3 Solutions Explained | dhananjay79 | 3 | 224 | swapping nodes in a linked list | 1,721 | 0.677 | Medium | 24,891 |
https://leetcode.com/problems/swapping-nodes-in-a-linked-list/discuss/1912576/Python-Easy-or-3-Solutions-Explained | class Solution:
def swapNodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
self.left, self.k = ListNode(-1,head), k
def traverse(right):
if right is None: return right
traverse(right.next)
self.k -= 1
self.left = self.left.next
if not self.k: self.left.val, right.val = right.val, self.left.val
return right
return traverse(head) | swapping-nodes-in-a-linked-list | β
Python Easy | 3 Solutions Explained | dhananjay79 | 3 | 224 | swapping nodes in a linked list | 1,721 | 0.677 | Medium | 24,892 |
https://leetcode.com/problems/swapping-nodes-in-a-linked-list/discuss/1912011/Python-or-Simple-and-Easy-Solution | class Solution:
def swapNodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
dummy = tail = ListNode(0, head)
kFromFront = kFromLast = dummy
n = 0
while(tail.next):
n += 1
if(n <= k):
kFromFront = kFromFront.next
if(n >= k):
kFromLast = kFromLast.next
tail = tail.next
kFromFront.val, kFromLast.val = kFromLast.val, kFromFront.val
return dummy.next | swapping-nodes-in-a-linked-list | Python | Simple and Easy Solution | thoufic | 3 | 185 | swapping nodes in a linked list | 1,721 | 0.677 | Medium | 24,893 |
https://leetcode.com/problems/swapping-nodes-in-a-linked-list/discuss/1113048/PythonPython3-Swapping-Nodes-and-not-Value-in-a-Linked-List | class Solution:
def swapNodes(self, head: ListNode, k: int) -> ListNode:
if not head.next: return head
# special case with only 2 nodes where value of k doesn't matter
if not head.next.next:
two = head.next
one = head
two.next = one
one.next = None
return two
# assign variable
one_before = one = two = three_before = three = four = head
# calc the length of LL
len_ll = 0
while head:
head = head.next
len_ll += 1
# reset the head
head = one
# if k is same as len_ll, then set k = 1
# because we have handles that edge case
if len_ll == k:
k = 1
# get (k-1)th node from ahead
for _ in range(k-2):
one_before = one_before.next
# print(one_before.val)
# get kth node from ahead
for _ in range(k-1):
one = one.next
two = two.next
four = four.next
# print(one_before.val, one.val) # kth node from beginning
# get (k+1)th node from behind
while four.next.next:
four = four.next
three_before = three_before.next
# print(three_before.val)
# get kth node from behind
while two.next:
two = two.next
three = three.next
# print(three_before.val, three.val)# kth node from last
# if kth node from behind and kth node from ahead are same
# there is no need for swapping
if one == three:
return head
# return head
# if (k-1)th node from ahead and kth node from ahead are same
# then do this π. Handling special case
if one_before == one:
mid = one.next
# one.next = None
three.next, one.next = one.next, three.next
three_before.next = one
return three
# if all other conditions are false, then do this π
one_before.next, three_before.next = three_before.next, one_before.next
one.next, three.next = three.next, one.next
return head | swapping-nodes-in-a-linked-list | [Python/Python3] Swapping Nodes and not Value in a Linked List | newborncoder | 2 | 292 | swapping nodes in a linked list | 1,721 | 0.677 | Medium | 24,894 |
https://leetcode.com/problems/swapping-nodes-in-a-linked-list/discuss/1914308/Python-Actually-swapping-Nodes-and-not-just-Swapping-of-Data | class Solution:
def swapNodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
dummy = ListNode(0,head)
def lenOfLL(head):
count = 0
temp = head
while temp:
temp = temp.next
count+=1
return count
if lenOfLL(head) <2:
return dummy.next
swap1,swap2 = dummy,dummy
prev1,prev2 = dummy,dummy
for i in range(1,k+1):
prev1 = swap1
swap1 = swap1.next
for i in range(1,lenOfLL(dummy)-k+1):
prev2 = swap2
swap2 = swap2.next
prev1.next,prev2.next = swap2,swap1
swap1.next,swap2.next = swap2.next,swap1.next
return dummy.next | swapping-nodes-in-a-linked-list | [Python] Actually swapping Nodes and not just Swapping of Data | creepypirate | 1 | 14 | swapping nodes in a linked list | 1,721 | 0.677 | Medium | 24,895 |
https://leetcode.com/problems/swapping-nodes-in-a-linked-list/discuss/1913626/Python-or-Easy-Solution-or-Faster-then-100-Submissions | class Solution(object):
def swapNodes(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
a = head
b = head
for i in range(k-1):
a = a.next
x = a
while a.next!=None:
b = b.next
a=a.next
x.val,b.val = b.val,x.val
return head
``` | swapping-nodes-in-a-linked-list | Python | Easy Solution | Faster then 100% Submissions | AkashHooda | 1 | 29 | swapping nodes in a linked list | 1,721 | 0.677 | Medium | 24,896 |
https://leetcode.com/problems/swapping-nodes-in-a-linked-list/discuss/1899941/One-pass-solution-w-comments-in-Python | class Solution:
def swapNodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
cur = head
# find the kth node from the beginning
for _ in range(k - 1):
cur = cur.next
# here we create the other pointer ek from the beggining and move it along cur
# this way ek would be the kth node from the end when cur is exhausted
bk, ek = cur, head
while cur.next:
ek = ek.next
cur = cur.next
# swap them if they're not binded to the same node
if ek is not bk:
bk.val, ek.val = ek.val, bk.val
return head | swapping-nodes-in-a-linked-list | One-pass solution w/ comments in Python | mousun224 | 1 | 39 | swapping nodes in a linked list | 1,721 | 0.677 | Medium | 24,897 |
https://leetcode.com/problems/swapping-nodes-in-a-linked-list/discuss/1387451/Python3-Stacks-1-Pass.-greater90-Fast.-O(N)-time-and-Space-less-cost-on-constant-factors-vs-recursion | class Solution:
def swapNodes(self, head: ListNode, k: int) -> ListNode:
# We can also do with stacks
s = []
cur = head
while cur:
s.append(cur)
cur = cur.next
s[k-1].val, s[-k].val = s[-k].val,s[k-1].val
return head | swapping-nodes-in-a-linked-list | [Python3] Stacks, 1 Pass. >90% Fast. O(N) time & Space, less cost on constant factors vs recursion | whitehatbuds | 1 | 122 | swapping nodes in a linked list | 1,721 | 0.677 | Medium | 24,898 |
https://leetcode.com/problems/swapping-nodes-in-a-linked-list/discuss/1387439/Python3-Recursion-1-Pass-slow-but-accepted-O(N)-time-O(N)-space-due-to-call-stack | class Solution:
def swapNodes(self, head: ListNode, k: int) -> ListNode:
# We can do it in one pass to return both nodes.
# recursion returns => [node1, node2]
# We swap both node values, return head
def recurse(node, swaps, startCount):
if node is None:
return
if startCount == recurse.k:
swaps[0] = node
recurse(node.next, swaps, startCount + 1)
recurse.k -= 1
if recurse.k == 0:
swaps[1] = node
if head is None:
return head
nodes = [None, None]
recurse.k = k
recurse(head, nodes, 1)
nodes[0].val, nodes[1].val = nodes[1].val, nodes[0].val
return head | swapping-nodes-in-a-linked-list | [Python3] Recursion 1 Pass, slow but accepted O(N) time O(N) space due to call stack | whitehatbuds | 1 | 54 | swapping nodes in a linked list | 1,721 | 0.677 | Medium | 24,899 |
Subsets and Splits
Top 2 Solutions by Upvotes
Identifies the top 2 highest upvoted Python solutions for each problem, providing insight into popular approaches.