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/arranging-coins/discuss/1849942/Python-Simple-Solution! | class Solution(object):
def arrangeCoins(self, coins):
stairs = 0
while stairs <= coins:
coins -= stairs
stairs += 1
return stairs-1 | arranging-coins | Python - Simple Solution! | domthedeveloper | 0 | 34 | arranging coins | 441 | 0.462 | Easy | 7,800 |
https://leetcode.com/problems/arranging-coins/discuss/1838610/Python3oror-TC%3A-O(log-N)-oror-Binary-Search | class Solution:
def arrangeCoins(self, n: int) -> int:
#sum of first k natural numbers -> (k*(k+1)) // 2
low, high = 0, n
while low <= high:
mid = low + (high - low) // 2
coins = (mid*(mid+1)) // 2
if coins == n:
return mid
elif coins < n:
ans = mid
low = mid + 1
else:
high = mid - 1
return ans
#TC: O(logN) | arranging-coins | Python3|| TC: O(log N) || Binary Search | s_m_d_29 | 0 | 39 | arranging coins | 441 | 0.462 | Easy | 7,801 |
https://leetcode.com/problems/arranging-coins/discuss/1587003/Python-O(1)-algebra | class Solution:
def arrangeCoins(self, n: int) -> int:
from math import sqrt, floor
cand = int(floor(sqrt(2*n)))
if 2*n-cand>=cand**2:
return cand
return cand-1 | arranging-coins | [Python] O(1), algebra | stefaMVP | 0 | 56 | arranging coins | 441 | 0.462 | Easy | 7,802 |
https://leetcode.com/problems/arranging-coins/discuss/1567219/python3-Binary-Search-solution-Faster-than-90 | class Solution:
def arrangeCoins(self, n: int) -> int:
#O(logn) time complexity
low,high = 1,n
while low <= high:
mid = (low+high)//2
if ((mid)*(mid+1))/2 > n:
high = mid-1
else:
low = mid+1
return high | arranging-coins | python3 Binary Search solution - Faster than 90% | sonali1597 | 0 | 52 | arranging coins | 441 | 0.462 | Easy | 7,803 |
https://leetcode.com/problems/arranging-coins/discuss/1561301/Python3-or-Simple-for-loop-Solution-or-Easy-To-Understand | class Solution:
def arrangeCoins(self, n: int) -> int:
coin = 0
for index in range(1,n+1):
coin += index
if coin >= n:
break
if coin > n:
index -= 1
return index | arranging-coins | Python3 | Simple for loop Solution | Easy To Understand | Call-Me-AJ | 0 | 35 | arranging coins | 441 | 0.462 | Easy | 7,804 |
https://leetcode.com/problems/arranging-coins/discuss/1560443/Python-Solution-Brute-Force | class Solution:
def arrangeCoins(self, n: int) -> int:
if n == 1:
return 1
if n == 0:
return 0
stairs = []
i = 0
while i < n:
if not stairs:
stairs.append(1)
i += 1
else:
curr_step = stairs[-1] + 1
if n - i > curr_step:
stairs.append(curr_step)
i += curr_step
else:
stairs.append(n-i)
i += n - i
complete_steps = len(stairs)
if complete_steps > 1:
if stairs[-1] == stairs[-2] + 1:
return complete_steps
else:
return complete_steps - 1
else:
if stairs[-1] == 1:
return 1
else:
return 0 | arranging-coins | Python Solution - Brute Force | japhethmutai | 0 | 30 | arranging coins | 441 | 0.462 | Easy | 7,805 |
https://leetcode.com/problems/arranging-coins/discuss/1560406/Python-iterative-solution | class Solution:
def arrangeCoins(self, n: int) -> int:
count = Sum = 0
while Sum <= n:
count += 1
Sum += count
return count - 1 | arranging-coins | Python iterative solution | abkc1221 | 0 | 19 | arranging coins | 441 | 0.462 | Easy | 7,806 |
https://leetcode.com/problems/arranging-coins/discuss/1461347/Simple-or-python-3 | class Solution:
def arrangeCoins(self, n: int) -> int:
for i in range(1, n+1):
n -= i
if n == 0:
return i
if n < 0:
return i - 1 | arranging-coins | Simple | python 3 | deep765 | 0 | 208 | arranging coins | 441 | 0.462 | Easy | 7,807 |
https://leetcode.com/problems/arranging-coins/discuss/1461347/Simple-or-python-3 | class Solution:
def arrangeCoins(self, n: int) -> int:
left, right = 0, n
while left <= right:
k = (right + left) // 2
curr = k * (k + 1) // 2
if curr == n:
return k
if n < curr:
right = k - 1
else:
left = k + 1
return right | arranging-coins | Simple | python 3 | deep765 | 0 | 208 | arranging coins | 441 | 0.462 | Easy | 7,808 |
https://leetcode.com/problems/arranging-coins/discuss/1172616/Python3-Simplest-One-Line-Approach-with-Explanation | class Solution:
def arrangeCoins(self, n: int) -> int:
'''
1. We need to find an integer x such that 1+2+3+...+x = n-p where p is minimum
2. Using the formula of summation of series, the sum of series 1+2+3+...+x = x(x+1)/2
3. Solve the equation, x(x+1)/2 = n
- using solution of quadratic equation (i.e. ax^2+bx+c=0), in this case x = (-1+square_root(1+8n))/2
- as x must be positive integer, take floor of square root of (1+8n) to calculate x and then take floor of x
'''
return int((-1+int((1+8*n)**0.5))//2) | arranging-coins | Python3 Simplest One Line Approach with Explanation | bPapan | 0 | 47 | arranging coins | 441 | 0.462 | Easy | 7,809 |
https://leetcode.com/problems/arranging-coins/discuss/1005788/Why-so-slow | class Solution:
def arrangeCoins(self, n: int) -> int:
if n<=1:
return n
x=0
sum1=0
while n>=sum1:
x+=1
sum1+=x
return x-1 | arranging-coins | Why so slow?? | thisisakshat | 0 | 80 | arranging coins | 441 | 0.462 | Easy | 7,810 |
https://leetcode.com/problems/arranging-coins/discuss/714720/Python3-two-approaches-O(logN)-and-O(1) | class Solution:
def arrangeCoins(self, n: int) -> int:
lo, hi = 0, n
while lo <= hi:
mid = (lo+hi)//2
if mid*(mid+1)//2 <= n: lo = mid + 1
else: hi = mid - 1
return hi | arranging-coins | [Python3] two approaches O(logN) & O(1) | ye15 | 0 | 55 | arranging coins | 441 | 0.462 | Easy | 7,811 |
https://leetcode.com/problems/arranging-coins/discuss/714720/Python3-two-approaches-O(logN)-and-O(1) | class Solution:
def arrangeCoins(self, n: int) -> int:
return int((sqrt(8*n + 1) - 1)//2) | arranging-coins | [Python3] two approaches O(logN) & O(1) | ye15 | 0 | 55 | arranging coins | 441 | 0.462 | Easy | 7,812 |
https://leetcode.com/problems/arranging-coins/discuss/524663/Python-3-Simple-O(n)-time-complexity-use-While-loop-not-Math | class Solution:
def arrangeCoins(self, n: int) -> int:
stairCase = 1
while n >= stairCase:
n -= stairCase
stairCase += 1
return stairCase-1 | arranging-coins | [Python 3] Simple, O(n) time complexity, use While loop, not Math | smiile8888 | 0 | 270 | arranging coins | 441 | 0.462 | Easy | 7,813 |
https://leetcode.com/problems/arranging-coins/discuss/362161/Solution-in-Python-3-(beats-~98)-(one-line) | class Solution:
def arrangeCoins(self, n: int) -> int:
return int(((1+8*n)**.5 - 1)/2)
- Junaid Mansuri
(LeetCode ID)@hotmail.com | arranging-coins | Solution in Python 3 (beats ~98%) (one line) | junaidmansuri | 0 | 272 | arranging coins | 441 | 0.462 | Easy | 7,814 |
https://leetcode.com/problems/arranging-coins/discuss/336759/Python-solution-using-math-and-binary-search | class Solution:
def arrangeCoins(self, n: int) -> int:
if n < 1:
return 0
low = 0
high = n
mid = 0
while low <= hi
mid = low + (high - low) // 2
s = (mid**2 + mid) >> 1
if s > n:
high = mid - 1
elif s < n:
low = mid + 1
else:
return mid
if (mid**2 + mid) >> 1 > n:
mid -= 1
return mid
``` | arranging-coins | Python solution using math and binary search | ultrablue | 0 | 125 | arranging coins | 441 | 0.462 | Easy | 7,815 |
https://leetcode.com/problems/arranging-coins/discuss/1444929/Python3-One-Line-Math-Solution-Faster-Than-96.32 | class Solution:
def arrangeCoins(self, n: int) -> int:
return int((2 * n + (1 / 4)) ** 0.5 - 1 / 2) | arranging-coins | Python3 One-Line Math Solution Faster Than 96.32% | Hejita | -1 | 54 | arranging coins | 441 | 0.462 | Easy | 7,816 |
https://leetcode.com/problems/arranging-coins/discuss/1175510/WEEB-DOES-MATH-WITH-BINARY-SEACH | class Solution:
def arrangeCoins(self, n: int) -> int:
low, high = 1, 65536
while low < high:
mid = low + (high-low)//2
if 0.5 * mid**2 + 0.5 * mid == n:
return mid
if 0.5 * mid**2 + 0.5 * mid > n:
high = mid
else:
low = mid + 1
return low - 1 | arranging-coins | WEEB DOES MATH WITH BINARY SEACH | Skywalker5423 | -3 | 171 | arranging coins | 441 | 0.462 | Easy | 7,817 |
https://leetcode.com/problems/find-all-duplicates-in-an-array/discuss/396890/Two-Solutions-in-Python-3-(-O(n)-time-)-(-O(1)-space-) | class Solution:
def findDuplicates(self, N: List[int]) -> List[int]:
S, A = set(), []
for n in N:
if n in S: A.append(n)
else: S.add(n)
return A | find-all-duplicates-in-an-array | Two Solutions in Python 3 ( O(n) time ) ( O(1) space ) | junaidmansuri | 9 | 1,700 | find all duplicates in an array | 442 | 0.734 | Medium | 7,818 |
https://leetcode.com/problems/find-all-duplicates-in-an-array/discuss/396890/Two-Solutions-in-Python-3-(-O(n)-time-)-(-O(1)-space-) | class Solution:
def findDuplicates(self, N: List[int]) -> List[int]:
A = []
for n in N:
if N[abs(n)-1] > 0: N[abs(n)-1] = -N[abs(n)-1]
else: A.append(abs(n))
return A
- Junaid Mansuri
(LeetCode ID)@hotmail.com | find-all-duplicates-in-an-array | Two Solutions in Python 3 ( O(n) time ) ( O(1) space ) | junaidmansuri | 9 | 1,700 | find all duplicates in an array | 442 | 0.734 | Medium | 7,819 |
https://leetcode.com/problems/find-all-duplicates-in-an-array/discuss/2830285/using-defaultdict | class Solution:
def findDuplicates(self, nums: List[int]) -> List[int]:
dc=defaultdict(lambda:0)
for a in nums:
dc[a]+=1
ans=[]
for a in dc:
if(dc[a]==2):
ans.append(a)
return ans | find-all-duplicates-in-an-array | using defaultdict | droj | 4 | 47 | find all duplicates in an array | 442 | 0.734 | Medium | 7,820 |
https://leetcode.com/problems/find-all-duplicates-in-an-array/discuss/2726787/Python-oror-O(1)-oror-Beginners-Solution-oror-Easy | class Solution:
def findDuplicates(self, nums: List[int]) -> List[int]:
ans = []
for i in range(len(nums)):
if nums[abs(nums[i])-1]>0:
nums[abs(nums[i])-1] = -nums[abs(nums[i])-1]
else:
ans.append(abs(nums[i]))
return ans | find-all-duplicates-in-an-array | Python || O(1) || Beginners Solution || Easy | its_iterator | 3 | 542 | find all duplicates in an array | 442 | 0.734 | Medium | 7,821 |
https://leetcode.com/problems/find-all-duplicates-in-an-array/discuss/1433147/Python-O(n)-without-extra-space | class Solution:
def findDuplicates(self, nums: List[int]) -> List[int]:
for i in range(len(nums)):
index = (nums[i]%len(nums))-1 #As value from 1-n
nums[index]+=len(nums)
output = []
for i,v in enumerate(nums):
if v>2*len(nums):
output.append(i+1)
return output | find-all-duplicates-in-an-array | Python O(n) without extra space | abrarjahin | 2 | 263 | find all duplicates in an array | 442 | 0.734 | Medium | 7,822 |
https://leetcode.com/problems/find-all-duplicates-in-an-array/discuss/2213708/Python-solution-with-in-depth-explanation-of-the-algorithm-and-comments-for-each-line-of-code | class Solution:
def findDuplicates(self, nums: List[int]) -> List[int]:
# output result array (which won't be counted as per description of the given problem.)
res = []
# Iterating through each element in the given array
for num in nums:
at_index = abs(num) - 1 # Getting the index one point less since index starts with zero than the current element for e.g.: n = 4 , so index = 4 - 1 = 3 so on and so forth. (for more in depth explanation read algorithm part at the top)
if nums[at_index] < 0: # checking if the current number is already negative then the current element is a duplicate
res.append(abs(num)) # Hence add it to the result array
else:
nums[abs(num) - 1] *= -1 # If it's not a negative then we're visiting it for the first time hence mark it visited by making element a negative number
return res | find-all-duplicates-in-an-array | Python solution with in-depth explanation of the algorithm and comments for each line of code | pawelborkar | 1 | 69 | find all duplicates in an array | 442 | 0.734 | Medium | 7,823 |
https://leetcode.com/problems/find-all-duplicates-in-an-array/discuss/775662/Python-or-Easy-2-solutions-(1-Line-and-using-dict) | class Solution(object):
def findDuplicates(self, nums):
letter,res = {},[]
for i in nums:
if i not in letter:
letter[i]=1
else:
letter[i]+=1
for i,j in letter.items():
if j>1:
res.append(i)
return res | find-all-duplicates-in-an-array | Python | Easy 2 solutions (1 Line and using dict) | rachitsxn292 | 1 | 418 | find all duplicates in an array | 442 | 0.734 | Medium | 7,824 |
https://leetcode.com/problems/find-all-duplicates-in-an-array/discuss/775662/Python-or-Easy-2-solutions-(1-Line-and-using-dict) | class Solution:
def findDuplicates(self, nums: List[int]) -> List[int]:
return [x for x, y in Counter(nums).items() if y> 1] | find-all-duplicates-in-an-array | Python | Easy 2 solutions (1 Line and using dict) | rachitsxn292 | 1 | 418 | find all duplicates in an array | 442 | 0.734 | Medium | 7,825 |
https://leetcode.com/problems/find-all-duplicates-in-an-array/discuss/242426/Python-2-line | class Solution:
def findDuplicates(self, nums: List[int]) -> List[int]:
count = collections.Counter(nums)
return [key for key,val in count.items() if val == 2] | find-all-duplicates-in-an-array | Python 2 line | tinaaggarwal | 1 | 377 | find all duplicates in an array | 442 | 0.734 | Medium | 7,826 |
https://leetcode.com/problems/find-all-duplicates-in-an-array/discuss/2814615/Medium-seriously | class Solution:
def findDuplicates(self, nums: List[int]) -> List[int]:
d = Counter(nums)
res = []
for k, v in d.items():
if v == 2: res.append(k)
return res | find-all-duplicates-in-an-array | Medium, seriously? | mediocre-coder | 0 | 3 | find all duplicates in an array | 442 | 0.734 | Medium | 7,827 |
https://leetcode.com/problems/find-all-duplicates-in-an-array/discuss/2804234/python3-O(n)-time-O(1)-space-with-down-to-earth-explanation | class Solution:
# the requirement of 1 <= nums[i] <= n is crucial. because
# of this requirement, we can move each val to its own position.
# say we have [3,1,2], then for value 3 we expect it to move to
# nums[3], value 2 at nums[2], etc. so result would be
# [0,1,2,3]. each value stays at its own place, you gotta know
# your place man. If you are trying to move to your place, but
# your duplicate occupied it first, like if we have [0,3,2,3],
# you are nums[1] == 3, and you are trying to move to nums[3]
# but nums[3] == 3 is already there, then you know
# he is a duplicate and you kick him to result.
def findDuplicates(self, nums: List[int]) -> List[int]:
res = []
nums.append(0)
for i in range(len(nums)):
while nums[i] and nums[i] != i:
if nums[nums[i]] == nums[i]:
res.append(nums[i])
nums[i] = 0
else:
nums[nums[i]], nums[i] = nums[i], nums[nums[i]]
return res | find-all-duplicates-in-an-array | python3 O(n) time, O(1) space with down to earth explanation | tinmanSimon | 0 | 3 | find all duplicates in an array | 442 | 0.734 | Medium | 7,828 |
https://leetcode.com/problems/find-all-duplicates-in-an-array/discuss/2797121/PYTHON3-BEST | class Solution:
def findDuplicates(self, nums: List[int]) -> List[int]:
a=[]
for i in nums:
i = abs(i)
if nums[i-1] < 0:
a.append(i)
else:
nums[i-1] = -nums[i-1]
return a | find-all-duplicates-in-an-array | PYTHON3 BEST | Gurugubelli_Anil | 0 | 3 | find all duplicates in an array | 442 | 0.734 | Medium | 7,829 |
https://leetcode.com/problems/find-all-duplicates-in-an-array/discuss/2785861/Beats-100-constant-space | class Solution:
def findDuplicates(self, nums: List[int]) -> List[int]:
ans = []
for i in range(len(nums)):
if nums[abs(nums[i])-1] <0 :
ans.append(abs(nums[i]))
nums[abs(nums[i])-1] *= -1
return ans | find-all-duplicates-in-an-array | Beats 100% constant space | sanskar_ | 0 | 10 | find all duplicates in an array | 442 | 0.734 | Medium | 7,830 |
https://leetcode.com/problems/find-all-duplicates-in-an-array/discuss/2778666/Python-solution-using-dictionary. | class Solution:
def findDuplicates(self, nums: List[int]) -> List[int]:
dic={}
ans=[]
for i in nums:
if i in dic:
dic[i]=dic[i]+1
else:
dic[i]=1
for i in dic:
if dic[i]>1:
ans.append(i)
return ans | find-all-duplicates-in-an-array | Python solution using dictionary. | zaeden9 | 0 | 1 | find all duplicates in an array | 442 | 0.734 | Medium | 7,831 |
https://leetcode.com/problems/find-all-duplicates-in-an-array/discuss/2758456/Official-solution-is-wrong-REAL-O(1)-space-Solution | class Solution:
def findDuplicates(self, nums: List[int]) -> List[int]:
# Pointer to write our result into nums
j = 0
# Mark a number x as seen, by inverting the value at index x
for x in nums:
# If seen before, it is part of our result
if nums[abs(x)-1] < 0:
# The value at j may carry information about another number
# so we should not change the sign
nums[j] = abs(x) if nums[j] > 0 else -abs(x)
j+=1
else:
nums[abs(x)-1] *= -1
# Once we processed all numbers, it is safe to override all signs
for i in range(j):
nums[i] = abs(nums[i])
return nums[:j] | find-all-duplicates-in-an-array | Official solution is wrong - REAL O(1) space Solution | LongQ | 0 | 4 | find all duplicates in an array | 442 | 0.734 | Medium | 7,832 |
https://leetcode.com/problems/find-all-duplicates-in-an-array/discuss/2731291/Easy-python-solution-using-dictionary | class Solution:
def findDuplicates(self, nums: List[int]) -> List[int]:
d = {}
for i in nums:
d[i] = d.get(i, 0) + 1
ans = [x for x, v in d.items() if v == 2]
return ans | find-all-duplicates-in-an-array | Easy python solution using dictionary | _debanjan_10 | 0 | 4 | find all duplicates in an array | 442 | 0.734 | Medium | 7,833 |
https://leetcode.com/problems/find-all-duplicates-in-an-array/discuss/2725771/Python-5-Lines-solution-or-99.51-Faster-or-Easy-solution!!! | class Solution:
def findDuplicates(self, nums: List[int]) -> List[int]:
d=Counter(nums)
l = list(map(lambda x:x[0],filter(lambda x:x[1]>1,d.items())))
return l | find-all-duplicates-in-an-array | Python 5 Lines solution | 99.51% Faster | Easy solution!!! | sanjay24685 | 0 | 6 | find all duplicates in an array | 442 | 0.734 | Medium | 7,834 |
https://leetcode.com/problems/find-all-duplicates-in-an-array/discuss/2708557/Python-Easy-Solution-or-O(n)-timeor-Hashmap | class Solution:
def findDuplicates(self, nums: List[int]) -> List[int]:
dictionary={}
res=[]
for n in nums:
if dictionary.get(n,0)==0:
dictionary[n]=1
else:
res.append(n)
return res
``` | find-all-duplicates-in-an-array | Python Easy Solution | O(n) time| Hashmap | mjk22071998 | 0 | 6 | find all duplicates in an array | 442 | 0.734 | Medium | 7,835 |
https://leetcode.com/problems/find-all-duplicates-in-an-array/discuss/2691358/Python-solution | class Solution:
def findDuplicates(self, nums: List[int]) -> List[int]:
arr = dict()
listof =[]
for i in range(len(nums)+1):
arr[i] =0
for num in nums:
if num in arr:
arr[num]+=1
else:
arr[num] =1
for key, val in arr.items():
if val > 1:
listof.append(key)
return listof | find-all-duplicates-in-an-array | Python solution | Sheeza | 0 | 3 | find all duplicates in an array | 442 | 0.734 | Medium | 7,836 |
https://leetcode.com/problems/find-all-duplicates-in-an-array/discuss/2686156/Two-Pointer-and-Cyclic-Sort-Solutions | #-Two Pointer Solution----------------------------------------------
class Solution:
def findDuplicates(self, nums: List[int]) -> List[int]:
nums.sort()
back = 0
count = 0
for front in range(0, len(nums) - 1):
if nums[front] == nums[front + 1]:
nums[back] = nums[front]
back += 1
count += 1
return nums[: count]
#-Cyclic Sort Solution-----------------------------------------------
class Solution:
def findDuplicates(self, nums: List[int]) -> List[int]:
N = len(nums)
index = 0
# 1) Perform Cyclic Sort, value at index should (index + 1)
while index < N:
temp = nums[index] - 1
if nums[index] != nums[temp]:
nums[index], nums[temp] = nums[temp], nums[index]
else:
index += 1
back = 0
# 2) If after sort, (index + 1) value is not present at index,
# then store the value in the left of the array.
for i in range(len(nums)):
if i + 1 != nums[i]:
nums[back] = nums[i]
back += 1
return (nums[ : back][::-1]) | find-all-duplicates-in-an-array | Two Pointer and Cyclic Sort Solutions | user6770yv | 0 | 9 | find all duplicates in an array | 442 | 0.734 | Medium | 7,837 |
https://leetcode.com/problems/find-all-duplicates-in-an-array/discuss/2666828/3-line-answer-using-Counter-and-list-comprehension | class Solution:
def findDuplicates(self, nums: List[int]) -> List[int]:
# Counter to get the frequency of the elements.
occurance = Counter(nums)
# If frequency is 2 then add the elements in the list.
ans = [x for x in occurance.keys() if occurance[x] == 2]
return ans | find-all-duplicates-in-an-array | 3 line answer using Counter and list comprehension | 24Neha | 0 | 28 | find all duplicates in an array | 442 | 0.734 | Medium | 7,838 |
https://leetcode.com/problems/find-all-duplicates-in-an-array/discuss/2660809/Python3-or-cyclicsort | class Solution:
def findDuplicates(self, nums: List[int]) -> List[int]:
i=0
#sorting nums by ignoring duplicates
while i<len(nums):
crt=nums[i]-1
if nums[i]<=len(nums) and nums[crt]!=nums[i]:
nums[crt],nums[i]=nums[i],nums[crt]
else:
i+=1
print(nums)
#checking where index=value-1 ==> nums[i]=i+1
s=[]
for i in range(len(nums)):
if nums[i]!=i+1:
s.append(nums[i])
return s | find-all-duplicates-in-an-array | Python3 | cyclicsort | 19pa1a1257 | 0 | 22 | find all duplicates in an array | 442 | 0.734 | Medium | 7,839 |
https://leetcode.com/problems/find-all-duplicates-in-an-array/discuss/2658372/easy-using-counter | class Solution:
def findDuplicates(self, nums: List[int]) -> List[int]:
c=Counter(nums)
res=[]
for i,j in c.items():
if(j >1):
res.append(i)
return res | find-all-duplicates-in-an-array | easy using counter | Raghunath_Reddy | 0 | 2 | find all duplicates in an array | 442 | 0.734 | Medium | 7,840 |
https://leetcode.com/problems/find-all-duplicates-in-an-array/discuss/2601989/Python-Solution-using-Counter | class Solution:
def findDuplicates(self, nums: List[int]) -> List[int]:
myDic = Counter(nums)
ans = []
for i in myDic:
if myDic[i] == 2:
ans.append(i)
return ans | find-all-duplicates-in-an-array | Python Solution using Counter | mayank0936 | 0 | 68 | find all duplicates in an array | 442 | 0.734 | Medium | 7,841 |
https://leetcode.com/problems/find-all-duplicates-in-an-array/discuss/2545502/python-simple-solution | class Solution:
def findDuplicates(self, nums: List[int]) -> List[int]:
d = defaultdict(int)
for n in nums:
d[n] += 1
output = []
for i in d:
if d[i] > 1:
output.append(i)
return output | find-all-duplicates-in-an-array | python simple solution | gasohel336 | 0 | 79 | find all duplicates in an array | 442 | 0.734 | Medium | 7,842 |
https://leetcode.com/problems/find-all-duplicates-in-an-array/discuss/2523338/constant-space-solution | class Solution:
# one method for constant space and linear time
# def findDuplicates(self, nums: List[int]) -> List[int]:
# result = []
# for i in range(len(nums)):
# if nums[abs(nums[i])-1] < 0:
# result.append(abs(nums[i]))
# else:
# nums[abs(nums[i])-1] *= -1
# return result
#other method for constant space and linear time
#we will add array_length to particular index element is index element has the value more than two times of the array index than that index element is duplicate
# convert array elements same as index element but this step is not necessary
def findDuplicates(self, nums: List[int]) -> List[int]:
result = []
length_nums = len(nums)
for i in range(length_nums):
nums[i] -= 1
for i in range(length_nums):
index = nums[i] % length_nums
nums[index] += length_nums
for i in range(length_nums):
if nums[i] >= 2*length_nums:
result.append(i+1)
return result | find-all-duplicates-in-an-array | constant space solution | pg902421 | 0 | 57 | find all duplicates in an array | 442 | 0.734 | Medium | 7,843 |
https://leetcode.com/problems/find-all-duplicates-in-an-array/discuss/2507507/Simple-python-code-with-explanation | class Solution:
#if you find word --> (duplicates) in question best way to approach that question most of the times is using --> dictionary
def findDuplicates(self, nums: List[int]) -> List[int]:
#create an empty dictionary using culy braces
thoma = {}
#store the keys of dictionary(thoma) in variable -->(k)
k = thoma.keys()
#iterate over the elements in array --> nums
for i in nums:
#if element not in k(keys of dictionary)
if i not in k:
#it means it is new element \
#assingn val 1 to that element
thoma[i] = 1
#if element is in k(keys of dictionary)
else:
#that means it is occured already one time or few times
#increase the val 1 to that element which is already having a value
thoma[i] = thoma[i] + 1
#create a new list
koushik = []
#iterate over the keys in dictionary -->(thoma)
for i in thoma:
#if the value of key is greater than one
if thoma[i] > 1:
#it means that it occured more than once
#so add that element to the list --> (koushik)
koushik.append(i)
#after adding all the elements which are repeating more than once
#return the list -->(koushik)
return koushik | find-all-duplicates-in-an-array | Simple python code with explanation | thomanani | 0 | 53 | find all duplicates in an array | 442 | 0.734 | Medium | 7,844 |
https://leetcode.com/problems/find-all-duplicates-in-an-array/discuss/2474330/Python-Solution | class Solution:
def findDuplicates(self, nums: List[int]) -> List[int]:
ansList = []
for i in range(len(nums)):
index = abs(nums[i])-1
if nums[index] < 0:
ansList.append(index+1)
else:
nums[index] = -1 * nums[index]
return ansList | find-all-duplicates-in-an-array | Python Solution | DietCoke777 | 0 | 40 | find all duplicates in an array | 442 | 0.734 | Medium | 7,845 |
https://leetcode.com/problems/find-all-duplicates-in-an-array/discuss/2365320/easy-python-solution | class Solution:
def findDuplicates(self, nums: List[int]) -> List[int]:
unique, duplicate = {}, []
for num in nums :
if num not in unique.keys() :
unique[num] = 1
else :
duplicate.append(num)
return duplicate | find-all-duplicates-in-an-array | easy python solution | sghorai | 0 | 84 | find all duplicates in an array | 442 | 0.734 | Medium | 7,846 |
https://leetcode.com/problems/find-all-duplicates-in-an-array/discuss/2350931/Python-or-Generator-or-Constant-extra-space | class Solution:
def findDuplicates(self, nums: List[int]) -> List[int]:
def duplicator(nums):
for idx in range(len(nums)):
cur = abs(nums[idx]) - 1
if nums[cur] < 0:
yield abs(nums[idx])
nums[cur] *= -1
return [num for num in duplicator(nums)] | find-all-duplicates-in-an-array | Python | Generator | Constant extra space | Sonic0588 | 0 | 65 | find all duplicates in an array | 442 | 0.734 | Medium | 7,847 |
https://leetcode.com/problems/find-all-duplicates-in-an-array/discuss/2296799/O(1)-space-and-O(n)-time-using-heterogeneous-list-of-characters-(no-auxoutput-array) | class Solution:
def findDuplicates(self, nums: List[int]) -> List[int]:
#print(id(nums))
# use fact that lists can contain heterogeneous values
seen_twice=0
# mark the index corresponding to a value between 1 and n
# make it -1* original value if it's seen once
# make it a character if it's seen twice
# numbers seen 0 times will be unchanged
for idx,n in enumerate(nums):
# if the value has been seen twice for this index
if isinstance(n,str):
nval=ord(n)-ord('a')
# if the value has been seen fewer than 2 times
else:
nval = n
# get the value in the array so we can update the corresponding array index
absn = abs(nval)
pos=absn-1
if nums[pos] > 0 :
nums[pos]*=-1
else:
# turn the value into a char
nums[pos]=chr(abs(nums[pos])+ord('a'))
seen_twice+=1
# if all items have been seen once
if seen_twice == 0:
return []
# remap chars to indexes, and non-chars to 0 value (input values start from 1)
for idx, i in enumerate(nums):
if isinstance(i,str):
nums[idx]=idx+1
else:
nums[idx]=0
# use two pointers move the repeated elements to the front of the list
# so list can be popped from the back without allocating more memory
next_free = 0
next_repeated = len(nums)-1
while next_free < next_repeated:
while nums[next_free] > 0:
next_free+=1
while nums[next_repeated] < 1:
next_repeated-=1
if next_free < next_repeated:
nums[next_free],nums[next_repeated]=nums[next_repeated],nums[next_free]
# get ready for the next iteration
next_free+=1
next_repeated-=1
else:
break
# pop from the back, leaving only elements seen twice
while len(nums) > seen_twice:
nums.pop()
#print(id(nums))
return nums | find-all-duplicates-in-an-array | O(1) space and O(n) time using heterogeneous list of characters (no aux/output array) | Tsjfienod | 0 | 73 | find all duplicates in an array | 442 | 0.734 | Medium | 7,848 |
https://leetcode.com/problems/find-all-duplicates-in-an-array/discuss/2197419/Python3-HashMap-%2B-Heap | class Solution:
def findDuplicates(self, nums: List[int]) -> List[int]:
s={}
k=[]
for i in range(len(nums)):
if nums[i] not in s:
s[nums[i]] = 1
else:
heapq.heappush(k,nums[i])
return k | find-all-duplicates-in-an-array | Python3 HashMap + Heap | aditya_maskar | 0 | 25 | find all duplicates in an array | 442 | 0.734 | Medium | 7,849 |
https://leetcode.com/problems/find-all-duplicates-in-an-array/discuss/2156966/Python-one-line-solution | class Solution:
def findDuplicates(self, nums: List[int]) -> List[int]:
return [k for k,v in Counter(nums).items() if v>1] | find-all-duplicates-in-an-array | Python one line solution | writemeom | 0 | 75 | find all duplicates in an array | 442 | 0.734 | Medium | 7,850 |
https://leetcode.com/problems/find-all-duplicates-in-an-array/discuss/2156966/Python-one-line-solution | class Solution:
def findDuplicates(self, nums: List[int]) -> List[int]:
freq = Counter(nums)
return [i for i in freq if freq[i]==2] | find-all-duplicates-in-an-array | Python one line solution | writemeom | 0 | 75 | find all duplicates in an array | 442 | 0.734 | Medium | 7,851 |
https://leetcode.com/problems/find-all-duplicates-in-an-array/discuss/2131155/Python-conventional-method-but-slow | class Solution:
def findDuplicates(self, nums: List[int]) -> List[int]:
output=[]
dic ={}
for num in nums:
if num not in dic:
dic[num]=1
else:
dic[num]+=1
for key in dic:
if dic[key]==2:
output.append(key)
return output | find-all-duplicates-in-an-array | Python conventional method but slow | M_D | 0 | 24 | find all duplicates in an array | 442 | 0.734 | Medium | 7,852 |
https://leetcode.com/problems/find-all-duplicates-in-an-array/discuss/2131147/Very-slow-python-method | class Solution:
def findDuplicates(self, nums: List[int]) -> List[int]:
output=[]
for i in range(len(nums)):
pointi= abs(nums[i])-1
nums[pointi]=-nums[pointi]
if nums[pointi]>0:
output.append(pointi+1) #真正要return的是这个位置上的数+1
return output
''' | find-all-duplicates-in-an-array | Very slow python method | M_D | 0 | 17 | find all duplicates in an array | 442 | 0.734 | Medium | 7,853 |
https://leetcode.com/problems/find-all-duplicates-in-an-array/discuss/2045280/Python-3-Solution-O(n)-Time-and-O(1)-Space | class Solution:
def findDuplicates(self, nums: List[int]) -> List[int]:
dups = list()
for i in nums:
idx = abs(i) - 1
if nums[idx] < 0:
dups.append(abs(i))
else:
nums[idx] *= -1
return dups | find-all-duplicates-in-an-array | Python 3 Solution, O(n) Time and O(1) Space | AprDev2011 | 0 | 65 | find all duplicates in an array | 442 | 0.734 | Medium | 7,854 |
https://leetcode.com/problems/find-all-duplicates-in-an-array/discuss/1863685/Ez-oror-O(n)-TC-oror-O(1)-SC | class Solution:
def findDuplicates(self, nums: List[int]) -> List[int]:
nums.append(0)
n=len(nums)
for i in range(n):
nums[nums[i]%n]+=n
for i in range(n):
if nums[i]//n>1:
yield(i) | find-all-duplicates-in-an-array | Ez || O(n) TC || O(1) SC | ashu_py22 | 0 | 26 | find all duplicates in an array | 442 | 0.734 | Medium | 7,855 |
https://leetcode.com/problems/find-all-duplicates-in-an-array/discuss/1849032/Python-Solution(memory-less-than-98)-oror-6-lines | class Solution:
def findDuplicates(self, nums: List[int]) -> List[int]:
nums.sort()
ans = []
for i in range(1,len(nums)):
if nums[i] == nums[i-1]:
ans.append(nums[i])
return ans | find-all-duplicates-in-an-array | Python Solution(memory less than 98%) || 6 lines | MS1301 | 0 | 124 | find all duplicates in an array | 442 | 0.734 | Medium | 7,856 |
https://leetcode.com/problems/find-all-duplicates-in-an-array/discuss/1748338/Similar-to-find-the-duplicate-number | class Solution:
def findDuplicates(self, nums: List[int]) -> List[int]:
# Creating a list to return
_return = []
# Going through all the list
for i, j in enumerate(nums):
# Making the index +ve if negative
if j < 0:
j *= -1
# Making the value there -ve [We can have only +ve values]
nums[j-1] *= -1
# Checking if it is still +ve; means we found the number
if nums[j-1] > 0:
_return.append(j)
return _return | find-all-duplicates-in-an-array | Similar to find the duplicate number | funnybacon | 0 | 125 | find all duplicates in an array | 442 | 0.734 | Medium | 7,857 |
https://leetcode.com/problems/find-all-duplicates-in-an-array/discuss/1628007/Python-3-solution | class Solution:
def findDuplicates(self, nums: List[int]) -> List[int]:
res = []
nums.sort()
for i in range(len(nums)-1):
if nums[i] == nums[i+1]:
res.append(nums[i])
return res | find-all-duplicates-in-an-array | Python 3 solution | user8445t | 0 | 47 | find all duplicates in an array | 442 | 0.734 | Medium | 7,858 |
https://leetcode.com/problems/find-all-duplicates-in-an-array/discuss/1506347/Faster-than-99.9-using-Counter | class Solution:
def findDuplicates(self, nums: List[int]) -> List[int]:
ans = []
for i,j in Counter(nums).items():
if j == 2: ans.append(i)
return ans | find-all-duplicates-in-an-array | Faster than 99.9% using Counter | dikshant14 | 0 | 29 | find all duplicates in an array | 442 | 0.734 | Medium | 7,859 |
https://leetcode.com/problems/find-all-duplicates-in-an-array/discuss/1506135/2-Simple-Python-Solutions-You-Can-Actually-Understand!-Constant-extra-space-in-one-of-them! | class Solution:
def findDuplicates(self, nums: List[int]) -> List[int]:
for n in nums:
key = abs(int(n)) - 1
nums[key] *= -1
if nums[key] > 0:
nums[key] += 0.1
return [i + 1 for i, n in enumerate(nums) if n > 0 and n % 1] | find-all-duplicates-in-an-array | 2 Simple Python Solutions You Can Actually Understand! Constant extra space in one of them! 🚀 | Cavalier_Poet | 0 | 72 | find all duplicates in an array | 442 | 0.734 | Medium | 7,860 |
https://leetcode.com/problems/find-all-duplicates-in-an-array/discuss/1506135/2-Simple-Python-Solutions-You-Can-Actually-Understand!-Constant-extra-space-in-one-of-them! | class Solution:
def findDuplicates(self, nums: List[int]) -> List[int]:
return collections.Counter(nums) - collections.Counter(set(nums)) | find-all-duplicates-in-an-array | 2 Simple Python Solutions You Can Actually Understand! Constant extra space in one of them! 🚀 | Cavalier_Poet | 0 | 72 | find all duplicates in an array | 442 | 0.734 | Medium | 7,861 |
https://leetcode.com/problems/find-all-duplicates-in-an-array/discuss/1038430/simple-of-simple | class Solution:
def findDuplicates(self, nums: List[int]) -> List[int]:
# 1. put hash set
# 2. if exist then add result list
s = set()
result = []
for n in nums:
if n in s:
result.append(n)
else:
s.add(n)
return result
# time: O(N)
# space: O(N) | find-all-duplicates-in-an-array | simple of simple | seunggabi | 0 | 88 | find all duplicates in an array | 442 | 0.734 | Medium | 7,862 |
https://leetcode.com/problems/find-all-duplicates-in-an-array/discuss/779229/Python3-(faster-than-99) | class Solution:
def findDuplicates(self, nums: List[int]) -> List[int]:
d = collections.Counter(nums)
ans=[]
for num,count in d.items():
if count==2:
ans.append(num)
return ans | find-all-duplicates-in-an-array | Python3 (faster than 99%) | harshitCode13 | 0 | 62 | find all duplicates in an array | 442 | 0.734 | Medium | 7,863 |
https://leetcode.com/problems/find-all-duplicates-in-an-array/discuss/779229/Python3-(faster-than-99) | class Solution:
def findDuplicates(self, nums: List[int]) -> List[int]:
ans=[]
for num in nums:
if nums[abs(num)-1]>0:
nums[abs(num)-1] = -nums[abs(num)-1]
else:
ans.append(abs(num))
return ans | find-all-duplicates-in-an-array | Python3 (faster than 99%) | harshitCode13 | 0 | 62 | find all duplicates in an array | 442 | 0.734 | Medium | 7,864 |
https://leetcode.com/problems/find-all-duplicates-in-an-array/discuss/777028/Easy-Python-Solution-380ms-Faster-than-80 | class Solution:
def findDuplicates(self, nums: List[int]) -> List[int]:
res = []
nums.sort()
for i in range(len(nums)-1):
if nums[i] == nums[i+1]:
res.append(nums[i])
return res | find-all-duplicates-in-an-array | Easy Python Solution, 380ms Faster than 80% | Venezsia1573 | 0 | 40 | find all duplicates in an array | 442 | 0.734 | Medium | 7,865 |
https://leetcode.com/problems/string-compression/discuss/1025555/Python3-Simple-and-Intuitive | class Solution:
def compress(self, chars: List[str]) -> int:
if not chars:
return 0
mychar = chars[0]
count = 0
length = len(chars)
chars.append(" ") # Append a space so last char group is not left out in loop
for i in range(length+1): #+1 for extra space char we added
char = chars.pop(0)
if char == mychar: #if same character then just increase the count
count += 1
else:
if count == 1: #if not same then append the char to chars
chars.append(mychar) #if count is 1 don't append count
elif count > 1:
chars.append(mychar)
chars += (list(str(count))) #if count > 1 append count as a string
mychar = char #update mychar as the new different char in chars
count = 1 #reset count to 1 as we have already read the new char
return len(chars) #since all previous are popped, only the answer remains in chars now | string-compression | Python3 Simple and Intuitive | upenj | 10 | 1,800 | string compression | 443 | 0.489 | Medium | 7,866 |
https://leetcode.com/problems/string-compression/discuss/2830228/constant-space-complexity | class Solution:
def compress(self, chars: List[str]) -> int:
if(len(chars)==1):
return 1
ans=[]
c=None
ct=0
i=0
for a in chars:
if(a!=c):
if(ct>1):
x=str(ct)
for m in x:
chars[i]=m
i+=1
chars[i]=a
i+=1
ct=1
c=a
else:
ct+=1
if(ct==1):
return i
x=str(ct)
for m in x:
chars[i]=m
i+=1
return i | string-compression | constant space complexity | droj | 5 | 85 | string compression | 443 | 0.489 | Medium | 7,867 |
https://leetcode.com/problems/string-compression/discuss/1549116/Python-%3A-3-pointers-solution | class Solution:
def compress(self, chars: List[str]) -> int:
res=l=r=0
while l<len(chars):
while r<len(chars) and chars[l]==chars[r]:
r+=1
temp=chars[l]+str(r-l) if r-l>1 else chars[l]
for c in temp:
chars[res]=c
res+=1
l=r
return res | string-compression | Python : 3 pointers solution | SeraphNiu | 2 | 273 | string compression | 443 | 0.489 | Medium | 7,868 |
https://leetcode.com/problems/string-compression/discuss/1396473/98-faster-Python-solution-(easy-understand) | class Solution:
def compress(self, chars):
if len(chars) < 2: return len(chars)
outputs, last_char, count = [chars[0]], chars[0], 1
for char in chars[1:]:
if last_char == char: count += 1
else:
if count > 1: outputs.append(str(count))
outputs.append(char)
count = 1
last_char = char
if count > 1: outputs.append(str(count))
out = list(''.join(outputs))
for i in range(len(out)): chars[i] = out[i]
return len(out) | string-compression | 98% faster Python solution (easy understand) | bob23 | 2 | 603 | string compression | 443 | 0.489 | Medium | 7,869 |
https://leetcode.com/problems/string-compression/discuss/1396473/98-faster-Python-solution-(easy-understand) | class Solution:
def compress(self, chars):
if len(chars) < 2: return len(chars)
last_char, count, idx = chars[0], 1, 1
for char in chars[1:]:
if last_char == char: count += 1
else:
if count > 1:
chars[idx:idx+len(str(count))] = str(count)
idx += len(str(count))
chars[idx], idx, count = char, idx + 1, 1
last_char = char
if count > 1:
chars[idx:idx+len(str(count))] = str(count)
idx += len(str(count))
return idx | string-compression | 98% faster Python solution (easy understand) | bob23 | 2 | 603 | string compression | 443 | 0.489 | Medium | 7,870 |
https://leetcode.com/problems/string-compression/discuss/1711624/python3-two-pointers-sliding-window-easy-to-understand-linear-time-O(n)-in-place | class Solution:
def compress(self, chars: List[str]) -> int:
left = right = 0
n = len(chars)
count = 0
result = []
index = 0
while right < n:
if chars[right] == chars[left]:
count += 1
right += 1
else:
chars[index] = chars[left]
if count > 1:
for c in str(count):
index += 1
chars[index] = c
index += 1
count = 0
left = right
chars[index] = chars[left]
if count > 1:
for c in str(count):
index += 1
chars[index] = c
if index < n - 1:
del chars[index + 1 :]
return len(chars) | string-compression | python3 two pointers sliding window, easy to understand, linear time O(n) in place | carlo_duan | 1 | 105 | string compression | 443 | 0.489 | Medium | 7,871 |
https://leetcode.com/problems/string-compression/discuss/1526721/2-Simple-Python-solutions-with-comments-O(N)-time-and-O(1)-space-(-2-pointer-solutions) | class Solution:
def compress(self, chars: List[str]) -> int:
s=""
if len(chars)<=1: return len(chars)
p1=writePointer=0
p2=1
count=1 #initial count set to 1
while p2<=len(chars):
if p2!=len(chars) and chars[p2]==chars[p1] : #if same char as previous just increment count
count+=1
else:
chars[writePointer]=chars[p1] #if p2!=len(chars) else chars[p2-1]
writePointer+=1
if count>1: #now add the count since its bigger than 1
stringCount=(str(count))
for i in range(len(stringCount)): #for loop for cases like ["a","b","12"] --> should be ["a","b","1","2"]
chars[writePointer]=stringCount[i]
writePointer+=1
p1=p2 #now new previous is p2
count=1 #restart count
p2+=1
return writePointer | string-compression | 2 Simple Python 🐍 solutions with comments O(N) time and O(1) space ( 2-pointer solutions) | InjySarhan | 1 | 390 | string compression | 443 | 0.489 | Medium | 7,872 |
https://leetcode.com/problems/string-compression/discuss/1526721/2-Simple-Python-solutions-with-comments-O(N)-time-and-O(1)-space-(-2-pointer-solutions) | class Solution:
def compress(self, chars: List[str]) -> int:
s=""
if len(chars)<=1: return len(chars)
p1=0
p2=1
count=1 #initial count set to 1
while p2<len(chars):
if chars[p2]==chars[p1]: #if same char as previous just increment count
count+=1
else:
s=s+chars[p1]+str(count) if count>1 else s+chars[p1] #now add the char to s if count==1 dont add count
p1=p2 #now new previous is p2
count=1 #restart count
p2+=1
s=s+chars[p2-1]+str(count) if count>1 else s+chars[p2-1] #because the last char and count where not added as we exit the loop before adding it
for i in range(len(s)): #this is just to change the input array and then return len(s) as required in the problem
chars[i]=s[i]
return len(s) | string-compression | 2 Simple Python 🐍 solutions with comments O(N) time and O(1) space ( 2-pointer solutions) | InjySarhan | 1 | 390 | string compression | 443 | 0.489 | Medium | 7,873 |
https://leetcode.com/problems/string-compression/discuss/1437530/Python3Python-Simple-intuitive-solution-w-comments | class Solution:
def compress(self, chars: List[str]) -> int:
n = len(chars)
if n > 1:
# insert counts like one char/digit at a time
def insertCounts(chars: List[str], counts: int):
if counts > 1: # only insert more than one occurence
for count in str(counts):
chars.append(str(count))
return
# Add compressed data at the end of the
# given array
counts = 1
prev = ""
while n: # scan for original data
# first character is always the next
# character, as we are deleting character
# which is scanned
if prev != chars[0]:
insertCounts(chars, counts)
chars.append(chars[0])
prev = chars[0]
counts = 1
else:
counts = counts + 1
# Delete the scanned character
del chars[0]
# Decrement
n = n-1
# Last operation
insertCounts(chars, counts)
# update length
n = len(chars)
return n | string-compression | [Python3/Python] Simple intuitive solution w/ comments | ssshukla26 | 1 | 403 | string compression | 443 | 0.489 | Medium | 7,874 |
https://leetcode.com/problems/string-compression/discuss/846755/Python3-two-pointers | class Solution:
def compress(self, chars: List[str]) -> int:
i = ii = 0
cnt = 1
for i in range(len(chars)):
if i+1 == len(chars) or chars[i] != chars[i+1]:
chars[ii] = chars[i]
ii += 1
if cnt > 1: chars[ii: (ii := ii+len(str(cnt)))] = str(cnt)
cnt = 0
cnt += 1
return ii | string-compression | [Python3] two pointers | ye15 | 1 | 166 | string compression | 443 | 0.489 | Medium | 7,875 |
https://leetcode.com/problems/string-compression/discuss/2845142/Better-than-99-Python-Solution | class Solution:
def compress(self, chars: List[str]) -> int:
i = 0
length = len(chars)
if length == 1:
return len(chars)
s = ""
while i < length:
cnt = 1
j = i + 1
s += chars[i]
while j < length and chars[i] == chars[j]:
cnt += 1
j += 1
if cnt > 1:
s += str(cnt)
i = j
chars[:] = list(s)
return len(chars) | string-compression | Better than 99% Python Solution | khaled_achech | 0 | 3 | string compression | 443 | 0.489 | Medium | 7,876 |
https://leetcode.com/problems/string-compression/discuss/2705877/90-faster-python-solution | class Solution:
def compress(self, chars: List[str]) -> int:
res=[]
count=1
res.append(chars[0])
for i in range(1,len(chars)):
if chars[i]==chars[i-1]:
count+=1
if i==len(chars)-1:
if count>=10:
dummy=[]
while count>0:
tmp=count%10
dummy.insert(0,tmp)
count=count//10
res.extend(dummy)
else:
res.append(count)
else:
if count>1:
if count>=10:
dummy=[]
while count>0:
tmp=count%10
dummy.insert(0,tmp)
count=count//10
res.extend(dummy)
else:
res.append(count)
res.append(chars[i])
else:
res.append(chars[i])
count=1
for i in range(0,len(res)):
chars[i]=str(res[i])
return len(res) | string-compression | 90% faster python solution | kowshick17 | 0 | 8 | string compression | 443 | 0.489 | Medium | 7,877 |
https://leetcode.com/problems/string-compression/discuss/2704405/constant-space-solution-explained | class Solution:
def compress(self, chars: List[str]) -> int:
back=0#first occurance of a new character
ind=0#current length of the list to be returned
n =len(chars)#length of list
#print(chars)
for pos , char in enumerate(chars): #iterating pos =index and char is the char at index=pos
if pos==n-1 or char!=chars[pos+1]: #if it is the last character cahracter in the list or the repetion of a character ends here
chars[ind]=char #add the char to the list at the current legth
ind+=1 #increase in the length of ans
if pos>back: #if a chacter is repeated
times=pos-back+1 #no of times a character appeared repeatedly
st_time=str(times) #string converson of no of times
for i in st_time:
chars[ind]=i #add the char in num of repeated times
ind+=1 #increase in length
back=pos+1 #the start of occurance of new char
return ind #return the length of the list
#print(chars) | string-compression | constant space solution explained | abhayCodes | 0 | 7 | string compression | 443 | 0.489 | Medium | 7,878 |
https://leetcode.com/problems/string-compression/discuss/2694364/99-Accepted-or-Two-Solutions-or-Easy-to-Understand-or-Python | class Solution(object):
def compress(self, chars):
currIdx, currStr, currCount = 0, chars[0], 1
for i in range(1, len(chars)):
if chars[i] == currStr:
currCount += 1
else:
if currCount == 1:
chars[currIdx] = currStr
currIdx += 1
elif currCount < 10:
chars[currIdx] = currStr
chars[currIdx + 1] = str(currCount)
currIdx += 2
else:
currCount = str(currCount)
chars[currIdx] = currStr
currIdx += 1
for j in range(len(currCount)):
chars[currIdx] = currCount[j]
currIdx += 1
currStr = chars[i]
currCount = 1
if currCount == 1:
chars[currIdx] = currStr
currIdx += 1
elif currCount < 10:
chars[currIdx] = currStr
chars[currIdx + 1] = str(currCount)
currIdx += 2
else:
currCount = str(currCount)
chars[currIdx] = currStr
currIdx += 1
for j in range(len(currCount)):
chars[currIdx] = currCount[j]
currIdx += 1
return currIdx | string-compression | 99% Accepted | Two Solutions | Easy to Understand | Python | its_krish_here | 0 | 20 | string compression | 443 | 0.489 | Medium | 7,879 |
https://leetcode.com/problems/string-compression/discuss/2694364/99-Accepted-or-Two-Solutions-or-Easy-to-Understand-or-Python | class Solution(object):
def compress(self, chars):
ansList = []
currStr = chars[0]
count = 1
for i in range(1, len(chars)):
if currStr == chars[i]: count += 1
else:
if count == 1:
ansList.append(currStr)
elif len(str(count)) > 1:
count = str(count)
ansList.append(currStr)
for j in range(len(count)):
ansList.append(count[j])
else:
ansList.append(currStr)
ansList.append(str(count))
count = 1
currStr = chars[i]
if count == 1:
ansList.append(currStr)
elif len(str(count)) > 1:
count = str(count)
ansList.append(currStr)
for i in range(len(count)):
ansList.append(count[i])
else:
ansList.append(currStr)
ansList.append(str(count))
for i in range(len(ansList)):
chars[i] = ansList[i]
return len(ansList) | string-compression | 99% Accepted | Two Solutions | Easy to Understand | Python | its_krish_here | 0 | 20 | string compression | 443 | 0.489 | Medium | 7,880 |
https://leetcode.com/problems/string-compression/discuss/2630209/Python-faster-than-65-easy-to-understand | class Solution:
def compress(self, chars: List[str]) -> int:
s = ''
ptr = 0
ptr_next = 0
while ptr < len(chars):
letter_counter = 0
while (ptr_next < len(chars) and chars[ptr] == chars[ptr_next]):
letter_counter += 1
ptr_next += 1
if letter_counter > 1:
s += str(chars[ptr]) + str(letter_counter)
ptr += 1
for num in str(letter_counter):
chars[ptr] = num
ptr += 1
else:
s += str(chars[ptr])
ptr += 1
ptr = ptr_next
chars[:] = s
return len(s) | string-compression | Python faster than 65% - easy to understand | roslan | 0 | 35 | string compression | 443 | 0.489 | Medium | 7,881 |
https://leetcode.com/problems/string-compression/discuss/2600909/Python3-Simple-Solution | class Solution:
def compress(self, chars: List[str]) -> int:
pre = ""
res = []
count = 1
for c in chars:
if c != pre:
if count != 1:
for i in str(count):
res.append(i)
res.append(c)
pre = c
count = 1
else:
count += 1
if count != 1:
for i in str(count):
res.append(i)
n = len(res)
chars[:] = res
return n | string-compression | Python3 Simple Solution | kchiranjeevi | 0 | 161 | string compression | 443 | 0.489 | Medium | 7,882 |
https://leetcode.com/problems/string-compression/discuss/2150014/python-3-oror-simple-solution-oror-O(n)O(1) | class Solution:
def compress(self, chars: List[str]) -> int:
insert = 0
groupLength = 1
chars.append(' ')
for i in range(1, len(chars)):
if chars[i] == chars[i - 1]:
groupLength += 1
continue
chars[insert] = chars[i - 1]
insert += 1
if groupLength== 1:
continue
for digit in str(groupLength):
chars[insert] = digit
insert += 1
groupLength = 1
return insert | string-compression | python 3 || simple solution || O(n)/O(1) | dereky4 | 0 | 301 | string compression | 443 | 0.489 | Medium | 7,883 |
https://leetcode.com/problems/string-compression/discuss/1916418/Python-easy-understanding-solution-with-comment | class Solution:
def compress(self, chars: List[str]) -> int:
chars += [None] # Trick to deal with the last element.
cur = chars[0]
count = 0 # count: record the times one element had appeared.
slow = 0 # slow: the idx ready to be modified.
for i, char in enumerate(chars):
if char != cur: # When we meet a new element,
chars[slow] = cur # we modify char[slow] to cur.
cur = char # Update cur to new element.
slow += 1 # Update the position of slow.
if count == 1: # If the previous element only appear once, skip below.
continue
for c in str(count): # Modify chars[slow] to appear times.
chars[slow] = c
slow += 1
count = 1 # Reset count = 1 because we met the new element.
elif char == cur:
count += 1
return slow | string-compression | Python easy - understanding solution with comment | byroncharly3 | 0 | 219 | string compression | 443 | 0.489 | Medium | 7,884 |
https://leetcode.com/problems/string-compression/discuss/1630901/Easy-pyhton3-solution | class Solution:
def compress(self, chars: List[str]) -> int:
n=len(chars)
i=0
j=0
while j<len(chars):
while j<len(chars)-1 and chars[j]==chars[j+1]:
j+=1
freq=(j-i+1)
if i==j:
j+=1
i=j
continue
while j-i!=0:
chars.pop(j)
j-=1
for val in str(freq):
j+=1
chars.insert(j,val)
j+=1
i=j
return len(chars) | string-compression | Easy pyhton3 solution | Karna61814 | 0 | 125 | string compression | 443 | 0.489 | Medium | 7,885 |
https://leetcode.com/problems/string-compression/discuss/1560592/Python3-Two-pointers-solution | class Solution:
def compress(self, chars: List[str]) -> int:
idx = 0
last_idx_for_insert = 0
while idx < len(chars):
char_cnt = 1
while idx < len(chars) - 1 and chars[idx] == chars[idx + 1]:
char_cnt += 1
idx += 1
chars[last_idx_for_insert] = chars[idx]
last_idx_for_insert += 1
char_cnt_lst = [d for d in str(char_cnt)]
if len(char_cnt_lst) > 1 or char_cnt_lst[0] != '1':
for digit_str in char_cnt_lst:
chars[last_idx_for_insert] = digit_str
last_idx_for_insert += 1
idx += 1
return len(chars[:last_idx_for_insert]) | string-compression | [Python3] Two-pointers solution | maosipov11 | 0 | 143 | string compression | 443 | 0.489 | Medium | 7,886 |
https://leetcode.com/problems/string-compression/discuss/1358129/Python-Comprehension | class Solution:
def compress(self, chars: List[str]) -> int:
res = []
count = 1
for i in range(1, len(chars)):
if chars[i - 1] == chars[i]:
count += 1
else:
res.append(chars[i - 1])
if count > 1:
L = [_ for _ in str(count)]
res += L
count = 1
res.append(chars[-1])
if count > 1:
L = [_ for _ in str(count)]
res += L
count = 1
chars[:] = res
return len(chars) | string-compression | [Python] Comprehension | Sai-Adarsh | 0 | 158 | string compression | 443 | 0.489 | Medium | 7,887 |
https://leetcode.com/problems/string-compression/discuss/343081/Python-3-(beats-~100)-(-O(n)-speed-)-(-O(1)-space-)-(-in-place-)-(seven-lines) | class Solution:
def compress(self, C: List[str]) -> int:
if len(C) <= 1: return
c, i, _ = 1, 0, C.append(" ")
while C[i] != " ":
if C[i] == C[i+1]: c += 1
elif c > 1: C[i+2-c:i+1], i, c = list(str(c)), i + 1 - c + len(list(str(c))), 1
i += 1
del C[-1]
- Junaid Mansuri | string-compression | Python 3 (beats ~100%) ( O(n) speed ) ( O(1) space ) ( in place ) (seven lines) | junaidmansuri | 0 | 891 | string compression | 443 | 0.489 | Medium | 7,888 |
https://leetcode.com/problems/add-two-numbers-ii/discuss/486730/Python-Using-One-Stack-Memory-Usage%3A-Less-than-100 | class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
n1 = n2 = 0
ptr1, ptr2 = l1, l2
stack = []
while ptr1: n1 += 1; ptr1 = ptr1.next
while ptr2: n2 += 1; ptr2 = ptr2.next
max_len = max(n1, n2)
while max_len:
a = b = 0
if max_len <= n1: a = l1.val; l1 = l1.next
if max_len <= n2: b = l2.val; l2 = l2.next
stack.append(a + b)
max_len -= 1
sumval, head = 0, None
while stack or sumval:
if stack: sumval += stack.pop()
node = ListNode(sumval % 10)
node.next = head
head = node
sumval //= 10
return head | add-two-numbers-ii | Python - Using One Stack [Memory Usage: Less than 100%] | mmbhatk | 11 | 766 | add two numbers ii | 445 | 0.595 | Medium | 7,889 |
https://leetcode.com/problems/add-two-numbers-ii/discuss/846777/Python3-two-approaches | class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
def fn(node):
"""Return number represented by linked list."""
ans = 0
while node:
ans = 10*ans + node.val
node = node.next
return ans
dummy = node = ListNode()
for x in str(fn(l1) + fn(l2)):
node.next = ListNode(int(x))
node = node.next
return dummy.next | add-two-numbers-ii | [Python3] two approaches | ye15 | 6 | 522 | add two numbers ii | 445 | 0.595 | Medium | 7,890 |
https://leetcode.com/problems/add-two-numbers-ii/discuss/846777/Python3-two-approaches | class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
def fn(node):
"""Reverse a linked list."""
prev = None
while node: prev, node.next, node = node, prev, node.next
return prev
l1, l2 = fn(l1), fn(l2) # reverse l1 & l2
carry = 0
dummy = node = ListNode()
while carry or l1 or l2:
if l1:
carry += l1.val
l1 = l1.next
if l2:
carry += l2.val
l2 = l2.next
carry, x = divmod(carry, 10)
node.next = node = ListNode(x)
return fn(dummy.next) | add-two-numbers-ii | [Python3] two approaches | ye15 | 6 | 522 | add two numbers ii | 445 | 0.595 | Medium | 7,891 |
https://leetcode.com/problems/add-two-numbers-ii/discuss/1707722/Python-Simple-Stack-Solution-oror-85-Runtime | class Solution:
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
stack1, stack2, curr1, curr2, head, carry = [], [], l1, l2, ListNode(), 0
while curr1 is not None:
stack1.append(curr1.val)
curr1 = curr1.next
while curr2 is not None:
stack2.append(curr2.val)
curr2 = curr2.next
l1, l2 = len(stack1), len(stack2)
for _ in range(max(l1, l2)):
a = 0 if l1 <= 0 else stack1.pop()
b = 0 if l2 <= 0 else stack2.pop()
l1 -= 1
l2 -= 1
sum = a+b+carry
carry = sum//10
temp = ListNode(sum%10, head.next)
head.next = temp
if carry != 0:
temp = ListNode(carry, head.next)
head.next = temp
return head.next | add-two-numbers-ii | Python Simple Stack Solution || 85% Runtime | anCoderr | 3 | 204 | add two numbers ii | 445 | 0.595 | Medium | 7,892 |
https://leetcode.com/problems/add-two-numbers-ii/discuss/333986/Python-faster-than-99.88-(64ms) | class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
num1 = ""
num2 = ""
# loop through the first linked list, storing the values in the num1 variable
while l1 is not None:
num1 += str(l1.val)
l1 = l1.next
# follows same process as above
while l2 is not None:
num2 += str(l2.val)
l2 = l2.next
# calculate the sum of the values that we just obtained and store it as a string
summation = str(int(num1) + int(num2))
# make the head of the node the first number in the summation string
head = ListNode(summation[0])
# create a new reference to the head so we can manipulate the linked list but not lose the original reference to the head
temp = head
# loop through the remaining numbers in the summation string, each time creating a new node
for val in summation[1:]:
temp.next = ListNode(val)
temp = temp.next
# return the original reference to the head
return head | add-two-numbers-ii | Python faster than 99.88% (64ms) | softbabywipes | 3 | 679 | add two numbers ii | 445 | 0.595 | Medium | 7,893 |
https://leetcode.com/problems/add-two-numbers-ii/discuss/2661663/Three-different-solutions-python.-HE-COULD-DO-THIS-FOR-WEEKS-SEE-THE-CONTINUATION-IN-THE-SOURCE. | class Solution1:
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
def down_up(c1, c2):
if c1.next:
tail, rem = down_up(c1.next, c2.next)
else:
tail, rem = None, 0
if c1.val >= 0 and c2.val >= 0:
s = c1.val + c2.val + rem
elif c1.val >= 0:
s = c1.val + rem
else:
s = c2.val + rem
if s > 9:
h, rem = ListNode(s - 10), 1
else:
h, rem = ListNode(s), 0
h.next = tail
return h, rem
len_1, len_2 = 0, 0
l1_c, l2_c = l1, l2
while l1_c:
l1_c = l1_c.next
len_1 += 1
while l2_c:
l2_c = l2_c.next
len_2 += 1
if len_1 != len_2:
dummy_h = dummy = ListNode(-1)
for i in range(abs(len_1 - len_2) - 1):
dummy.next = ListNode(-1)
dummy = dummy.next
if len_1 < len_2:
dummy.next = l1
l1 = dummy_h
elif len_2 < len_1:
dummy.next = l2
l2 = dummy_h
l, rem = down_up(l1, l2)
if rem:
head = ListNode(1, l)
else:
head = l
return head
class Solution2:
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
def linked2ordinary(l):
l_l = []
while l:
l_l.append(l.val)
l = l.next
return l_l
l1_l, l2_l = linked2ordinary(l1)[::-1], linked2ordinary(l2)[::-1]
answer = []
reminder = 0
i, j = 0, 0
while i < len(l1_l) and j < len(l2_l):
s = l1_l[i] + l2_l[j] + reminder
if s > 9:
answer.append(s - 10)
reminder = 1
else:
answer.append(s)
reminder = 0
i, j = i + 1, j + 1
while i < len(l1_l):
s = l1_l[i] + reminder
if s > 9:
answer.append(s - 10)
reminder = 1
else:
answer.append(s)
reminder = 0
i += 1
while j < len(l2_l):
s = l2_l[j] + reminder
if s > 9:
answer.append(s - 10)
reminder = 1
else:
answer.append(s)
reminder = 0
j += 1
if reminder:
answer.append(1)
head = curr = ListNode()
answer = answer[::-1]
for i in range(len(answer)):
curr.val = answer[i]
if i < len(answer) - 1:
curr.next = ListNode()
curr = curr.next
return head
class Solution3:
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
def reverse(l):
h = curr = l
prev = None
while curr:
tmp = curr.next
curr.next = prev
prev, curr = curr, tmp
return prev
l1, l2 = reverse(l1), reverse(l2)
head = ListNode()
curr = head
while l1 and l2:
curr.val = l1.val + l2.val
if l1.next and l2.next:
curr.next = ListNode()
curr = curr.next
l1, l2 = l1.next, l2.next
if l1 or l2:
curr.next = l1 or l2
curr = head
last_item = None
reminder = 0
while curr:
if reminder + curr.val > 9:
curr.val = reminder + curr.val - 10
reminder = 1
else:
curr.val += reminder
reminder = 0
if not curr.next:
last_item = curr
curr = curr.next
if reminder:
last_item.next = ListNode(1)
return reverse(head) | add-two-numbers-ii | Three different solutions python. HE COULD DO THIS FOR WEEKS, SEE THE CONTINUATION IN THE SOURCE. | Yaro1 | 2 | 181 | add two numbers ii | 445 | 0.595 | Medium | 7,894 |
https://leetcode.com/problems/add-two-numbers-ii/discuss/1817560/Python-3-Easy-to-understand | class Solution:
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
# 2. Add Two Numbers
dummy = ListNode(0)
curr = dummy
carry = 0
# reverse l1 and l2
l1, l2 = self.reverse(l1), self.reverse(l2)
while l1 or l2 or carry:
v1 = l1.val if l1 else 0
v2 = l2.val if l2 else 0
# new digit
val = v1 + v2 + carry
carry, val = val // 10, val % 10
curr.next = ListNode(val)
# update pointer
l1 = l1.next if l1 else None
l2 = l2.next if l2 else None
curr = curr.next
# reverse back the result
return self.reverse(dummy.next)
# 206. Reverse Linked List
def reverse(self, head):
prev, curr = None, head
while curr:
# swap node
nxt = curr.next
curr.next = prev
# update pointers
prev, curr = curr, nxt
return prev | add-two-numbers-ii | [Python 3] Easy to understand | flatwhite | 1 | 81 | add two numbers ii | 445 | 0.595 | Medium | 7,895 |
https://leetcode.com/problems/add-two-numbers-ii/discuss/1177372/Python-or-Faster-than-99.47 | class Solution:
def list2int(self, lst):
num = ""
while lst:
num += str(lst.val)
lst = lst.next
return int(num)
def int2list(self, num):
lst = list(map(int, str(num)))
begin = ListNode(0)
end = begin
for i in lst:
end.next = ListNode(i)
end = end.next
return begin.next
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
num1 = self.list2int(l1)
num2 = self.list2int(l2)
ans = num1 + num2
return self.int2list(ans) | add-two-numbers-ii | Python | Faster than 99.47% | AriefPA | 1 | 87 | add two numbers ii | 445 | 0.595 | Medium | 7,896 |
https://leetcode.com/problems/add-two-numbers-ii/discuss/1064322/Python-solution-using-two-stacks.-Beats-95 | class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
s1 = []
s2 = []
res = ListNode(0)
while l1:
s1.append(l1.val)
l1 = l1.next
while l2:
s2.append(l2.val)
l2 = l2.next
sum_n = 0
carry = 0
while s1 or s2:
n1 = s1.pop() if s1 else 0
n2 = s2.pop() if s2 else 0
sum_n = carry + n1 + n2
carry = sum_n // 10
res.val = sum_n % 10
head = ListNode(sum_n // 10)
head.next = res
res = head
return res.next if res.val == 0 else res | add-two-numbers-ii | Python solution using two stacks. Beats 95% | Pseudocoder_Ravina | 1 | 94 | add two numbers ii | 445 | 0.595 | Medium | 7,897 |
https://leetcode.com/problems/add-two-numbers-ii/discuss/2751034/Python-and-Golang-Solution | class Solution:
def reverse(self, head: ListNode) -> ListNode:
current_node = head
previous_node = None
while current_node:
next_node = current_node.next
current_node.next = previous_node
previous_node = current_node
current_node = next_node
return previous_node
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
reversed_l1 = self.reverse(l1)
reversed_l2 = self.reverse(l2)
result = ListNode(-1)
dummy = result
increment = 0
while reversed_l1 and reversed_l2:
total = reversed_l1.val + reversed_l2.val + increment
increment = 0
if 10 <= total:
increment += 1
total -= 10
dummy.next = ListNode(total)
while dummy.next:
dummy = dummy.next
reversed_l1 = reversed_l1.next
reversed_l2 = reversed_l2.next
while reversed_l1:
total = reversed_l1.val + increment
increment = 0
if 10 <= total:
increment += 1
total -= 10
dummy.next = ListNode(total)
while dummy.next:
dummy = dummy.next
reversed_l1 = reversed_l1.next
while reversed_l2:
total = reversed_l2.val + increment
increment = 0
if 10 <= total:
increment += 1
total -= 10
dummy.next = ListNode(total)
while dummy.next:
dummy = dummy.next
reversed_l2 = reversed_l2.next
if 0 < increment:
dummy.next = ListNode(1)
return self.reverse(result.next) | add-two-numbers-ii | Python and Golang Solution | namashin | 0 | 3 | add two numbers ii | 445 | 0.595 | Medium | 7,898 |
https://leetcode.com/problems/add-two-numbers-ii/discuss/2681077/Python-O(1)-space-O(N)-time-recursion. | class Solution:
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
def _get_length(node1, node2):
n1 = 1
n2 = 1
while node1.next or node2.next:
if node1.next:
n1 += 1
node1 = node1.next
if node2.next:
n2 += 1
node2 = node2.next
return n1, n2
def _helper(n1, n2, nn1, nn2, depth):
if n1.next is None and n2.next is None:
n1.val += n2.val
elif n1.next is not None or n2.next is not None:
if depth <= nn1 - nn2:
carry = _helper(n1.next, n2, nn1, nn2, depth + 1)
else:
carry = _helper(n1.next, n2.next, nn1, nn2, depth + 1)
n1.val += n2.val
n1.val += carry
carry = n1.val // 10
n1.val %= 10
return carry
ln1, ln2 = _get_length(l1, l2)
flag = ln1 > ln2
carry = (_helper(l1, l2, ln1, ln2, 1) if flag else _helper(l2, l1, ln2, ln1, 1))
if not carry:
return (l1 if flag else l2)
ans = ListNode(val=carry, next=(l1 if flag else l2))
return ans | add-two-numbers-ii | Python O(1) space, O(N) time, recursion. | jithindmathew56 | 0 | 33 | add two numbers ii | 445 | 0.595 | Medium | 7,899 |
Subsets and Splits