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/two-sum/discuss/2361743/Python-Simple-Solution-oror-O(n)-Time-oror-O(n)-Space | class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
d = {}
for i, j in enumerate(nums):
r = target - j
if r in d: return [d[r], i]
d[j] = i
# An Upvote will be encouraging | two-sum | Python Simple Solution || O(n) Time || O(n) Space | rajkumarerrakutti | 288 | 21,600 | two sum | 1 | 0.491 | Easy | 0 |
https://leetcode.com/problems/two-sum/discuss/1378197/Simple-oror-100-faster-oror-5-Lines-code-oror-Well-Explained | class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
store = dict()
for i in range(len(nums)):
sec = target - nums[i]
if sec not in store:
store[nums[i]]=i
else:
return [store[sec],i] | two-sum | 🐍 Simple || 100% faster || 5 Lines code || Well-Explained 📌📌 | abhi9Rai | 47 | 6,800 | two sum | 1 | 0.491 | Easy | 1 |
https://leetcode.com/problems/two-sum/discuss/1378197/Simple-oror-100-faster-oror-5-Lines-code-oror-Well-Explained | class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
tmp = sorted(nums)
n, i, j = len(nums), 0, (n-1)
while True:
s = tmp[i]+tmp[j]
if s>target:
j-=1
elif s<target:
i+=1
else:
break
return [nums.index(tmp[i]),n-(nums[::-1].index(tmp[j]))-1] | two-sum | 🐍 Simple || 100% faster || 5 Lines code || Well-Explained 📌📌 | abhi9Rai | 47 | 6,800 | two sum | 1 | 0.491 | Easy | 2 |
https://leetcode.com/problems/two-sum/discuss/2045849/1LINER-O(n)timeBEATS-99.97-MEMORYSPEED-0ms-MAY-2022 | class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
seen = {}
for i, value in enumerate(nums): #1
remaining = target - nums[i] #2
if remaining in seen: #3
return [i, seen[remaining]] #4
else:
seen[value] = i #5 | two-sum | [1LINER] O(n)time/BEATS 99.97% MEMORY/SPEED 0ms MAY 2022 | cucerdariancatalin | 21 | 4,800 | two sum | 1 | 0.491 | Easy | 3 |
https://leetcode.com/problems/two-sum/discuss/1680976/Python-Simple-O(n)-time-solution-with-explanation-and-Big-O-analysis | class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
prevTable = {}
for i,currVal in enumerate(nums):
complement = target - currVal
if complement in prevTable:
return [prevTable[complement],i]
prevTable[currVal] = i | two-sum | Python Simple O(n) time solution, with explanation and Big O analysis | kenanR | 20 | 2,400 | two sum | 1 | 0.491 | Easy | 4 |
https://leetcode.com/problems/two-sum/discuss/1855612/Python3-direct-solution-faster-than-85.68-online-submissions-greater-O(n) | class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
map = {}
for i,n in enumerate(nums):
diff = target - n
if diff in map:
return [map[diff],i]
map[n] = i | two-sum | Python3 direct solution faster than 85.68% online submissions -> O(n) | MaxKingson | 13 | 1,100 | two sum | 1 | 0.491 | Easy | 5 |
https://leetcode.com/problems/two-sum/discuss/2806290/Python-4-Line-simple-solution | class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
dict_nums = {}
for i, v in enumerate(nums):
if v in dict_nums: return [i, dict_nums[v]]
dict_nums[target - v] = i | two-sum | 😎 Python 4-Line simple solution | Pragadeeshwaran_Pasupathi | 7 | 2,200 | two sum | 1 | 0.491 | Easy | 6 |
https://leetcode.com/problems/two-sum/discuss/2391581/python3-O(n)-and-O(n2)-both-made-easy.-simple | class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
for i in range(len(nums)-1):
for j in range(len(nums)):
if j!=i:
if (target == nums[i]+nums[j]):
return i,j | two-sum | python3 O(n) and O(n2) both made easy. simple | md-thayyib | 7 | 734 | two sum | 1 | 0.491 | Easy | 7 |
https://leetcode.com/problems/two-sum/discuss/2391581/python3-O(n)-and-O(n2)-both-made-easy.-simple | class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
lookup = {}
for position, number in enumerate(nums):
if target - number in lookup:
return lookup[target-number],position
else: lookup[number]=position | two-sum | python3 O(n) and O(n2) both made easy. simple | md-thayyib | 7 | 734 | two sum | 1 | 0.491 | Easy | 8 |
https://leetcode.com/problems/two-sum/discuss/1744681/100-Python3-or-Faster-Solution-or-Easiest | class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
checked={}
for index , item in enumerate(nums):
remaining = target - nums[index]
if remaining in checked:
return [index, checked[remaining]]
checked[item] = index | two-sum | ✔ 100% Python3 | Faster Solution | Easiest | Anilchouhan181 | 7 | 933 | two sum | 1 | 0.491 | Easy | 9 |
https://leetcode.com/problems/two-sum/discuss/1634584/Python-Easy-Solution-or-Simple-Approach | class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
res = {}
for idx, val in enumerate(nums):
remn = target-val
if remn in res:
return [res[remn], idx]
res[val] = idx | two-sum | Python Easy Solution | Simple Approach ✔ | leet_satyam | 7 | 1,400 | two sum | 1 | 0.491 | Easy | 10 |
https://leetcode.com/problems/two-sum/discuss/1503197/Move-from-O(N2)-to-O(N)-oror-Thought-Process-Explained | class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
#Brute Force way of thinking
#Generate all subarrays and as soon as we find the condition getting fulfilled, append it to our answer
#Note - as per question, only 1 valid answer exists, so repetition will not be an issue
#If at all there was repetition, it can be avoided by traversing as below
#O(N^2) Time -- Accepted Solution
n = len(nums)
answer = list()
for i in range(n):
for j in range(i+1,n):
if (nums[i] + nums[j] == target):
answer.append(i)
answer.append(j)
return answer
#Let us try to optimize
#NOTE - We CANNOT SORT THIS array as we have to retrieve the indices and sorting it
#would change the original indices at which elements are present
#If the given array would have already been sorted, this would have worked completely fine
#if we fix one of the numbers as arr[i], so other would be arr[j] = (target - arr[i])
#now, we simply have to see if this arr[j] exists in the given array or not
#O(N) Time --- Accepted Solution (TAKEN HELP FROM DISCUSSION SECTION)
#NOTE - Looking up an element in a dictionary is O(1) and not O(N)
n = len(nums)
seen = {} #empty dictionary
for index, value in enumerate(nums):
remaining = target - value
#here, value is nums[i]
#we are looking for this remaining, which is nums[j]
#we have to find if remaining or nums[j] is present in the given array or not
#this equation comes from the fact that as per question :
#nums[i] + nums[j] = target
if remaining in seen:
#if nums[j] is present in dictionary
#just return index of nums[i] and nums[j]
return [index, seen[remaining]]
#index represents index of nums[i] and seen[remaining] will
#hold index of nums[j]
else:
#otherwise, add the value corresponding to its index in the dictionary
#so, if it searched again, we can directly retrieve its index
seen[value] = index | two-sum | Move from O(N^2) to O(N) || Thought Process Explained | aarushsharmaa | 7 | 890 | two sum | 1 | 0.491 | Easy | 11 |
https://leetcode.com/problems/two-sum/discuss/2287919/Easy-python3-using-enumerate(updated) | class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
prevMap = {}
for i, n in enumerate(nums):
diff = target - n
if diff in prevMap:
return [prevMap[diff], i]
prevMap[n] = i | two-sum | Easy python3 using enumerate(updated) | __Simamina__ | 6 | 513 | two sum | 1 | 0.491 | Easy | 12 |
https://leetcode.com/problems/two-sum/discuss/1812148/PythonJava-Hash-Map-of-Inverses-or-Beats-99 | class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
inverses = {}
for i, num in enumerate(nums):
if num in inverses:
return [inverses[num], i]
inverses[target-num] = i | two-sum | [Python/Java] Hash Map of Inverses | Beats 99% | hari19041 | 6 | 650 | two sum | 1 | 0.491 | Easy | 13 |
https://leetcode.com/problems/two-sum/discuss/1400832/Python-or-Easy-or-O(n) | class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
#two pointer technique with sorting -> time -> O(nlogn)
#hashing technique -> time -> O(n)
di = {}
for i in range(len(nums)):
if target-nums[i] in di:
return [di[target-nums[i]], i]
else:
di[nums[i]] = i
#no need we will find solution in loop itself acc. to the question | two-sum | Python | Easy | O(n) | sathwickreddy | 6 | 1,600 | two sum | 1 | 0.491 | Easy | 14 |
https://leetcode.com/problems/two-sum/discuss/1837631/Accepted-Python3-solution-with-2-lines | class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
for i in nums:
if target - i in nums[nums.index(i) + 1:]: return [nums.index(i), nums[nums.index(i) + 1:].index(target - i) + nums.index(i) + 1] | two-sum | Accepted Python3 solution with 2 lines | ElizaZoldyck | 5 | 608 | two sum | 1 | 0.491 | Easy | 15 |
https://leetcode.com/problems/two-sum/discuss/1769992/Python-solution-using-hash-map-with-O(n)-complexity | class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
# construnct a empty hash map
val_index_map = {}
# hasmpa { value: index}
# iterate through given array with count, I used enumerate for count you guys can also add its mannually
for count, num in enumerate(nums):
# first i check the diff btw target and current value
req_diff = target - num
# if required difrence is exist in hashmap, then we are done
if req_diff in val_index_map:
# so current_value + required_diff = Traget
# mission accomplished
return [val_index_map.get(req_diff), count]
else:
# if required diff is not present in the hasmap then we add current number as a value and its index as a key
val_index_map[num] = count
return | two-sum | Python solution using hash map with O(n) complexity | rajat4665 | 5 | 929 | two sum | 1 | 0.491 | Easy | 16 |
https://leetcode.com/problems/two-sum/discuss/2737044/Python-Hash-table-O(n)-or-Full-explanation | class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
"""Take each number and check if its complement has been seen before. If not,
add it to the list of known complements along with its index.
Args:
nums (List[int]): Input array of integers
target (int): Target integer
Returns:
List[int]: Indices of the two integers that sum to target
"""
# Initialise hash map to store known integers
complements = {}
# Iterate through the list
for i in range(len(nums)):
# Check if the current number's complement has been seen before
complement = target - nums[i]
if complement in complements:
return [complements[complement], i]
# Add the current number to the list of known complements
complements[nums[i]] = i | two-sum | 🥇 [Python] Hash table - O(n) | Full explanation ✨ | LloydTao | 4 | 613 | two sum | 1 | 0.491 | Easy | 17 |
https://leetcode.com/problems/two-sum/discuss/2737044/Python-Hash-table-O(n)-or-Full-explanation | class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
"""Take each pair of numbers and see if they add up to the target.
Args:
nums (List[int]): Input array of integers
target (int): Target integer
Returns:
List[int]: Indices of the two integers that sum to target
"""
# Get length of input array
n = len(nums)
# Iterate over all pairs (i,j)
for i in range(n):
for j in range(i + 1, n):
# Check if this pair equals the target
if nums[i] + nums[j] == target:
return [i, j] | two-sum | 🥇 [Python] Hash table - O(n) | Full explanation ✨ | LloydTao | 4 | 613 | two sum | 1 | 0.491 | Easy | 18 |
https://leetcode.com/problems/two-sum/discuss/2603308/easy-python-solution | class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
for i in range(len(nums)) :
num1 = nums[i]
if (target - num1) in nums[i+1:] :
return [i, (nums[i+1:].index((target - num1)))+i+1] | two-sum | easy python solution | sghorai | 4 | 806 | two sum | 1 | 0.491 | Easy | 19 |
https://leetcode.com/problems/two-sum/discuss/2570856/SIMPLE-PYTHON3-SOLUTION | class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
for i in range(len(nums)):
try:
if i != nums.index(target - nums[i]): return [i, nums.index(target - nums[i])]
except ValueError:
continue | two-sum | ✅✔ SIMPLE PYTHON3 SOLUTION ✅✔ | rajukommula | 4 | 339 | two sum | 1 | 0.491 | Easy | 20 |
https://leetcode.com/problems/two-sum/discuss/2546192/Simple-dictionary-solution | class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
pairs = {}
for i, v in enumerate(nums):
if target-v in pairs:
return [pairs[target-v], i]
else:
pairs[v] = i | two-sum | 📌 Simple dictionary solution | croatoan | 4 | 226 | two sum | 1 | 0.491 | Easy | 21 |
https://leetcode.com/problems/two-sum/discuss/2542771/1.-Two-Sum | class Solution:
def twoSum(self, nums: list[int], target: int) -> list[int]:
s =defaultdict(int)
for i, n in enumerate(nums):
if target - n in s:
return [i, s[target - n]]
s[n] =i | two-sum | 1. Two Sum | warrenruud | 4 | 543 | two sum | 1 | 0.491 | Easy | 22 |
https://leetcode.com/problems/two-sum/discuss/2454524/Optimal-PYTHON-3-Solution | class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
hashmap = {} # val : index
for i, n in enumerate(nums):
#if n<=target:
diff = target-n
if diff in hashmap:
return [hashmap[diff],i]
hashmap[n]=i
return | two-sum | Optimal PYTHON 3 Solution | WhiteBeardPirate | 4 | 473 | two sum | 1 | 0.491 | Easy | 23 |
https://leetcode.com/problems/two-sum/discuss/1691722/**-Python-code%3A-using-HashMap | class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
checked={}
for index , item in enumerate(nums):
remaining = target - nums[index]
if remaining in checked:
return [index, checked[remaining]]
checked[item] = index | two-sum | ** Python code: using HashMap | Anilchouhan181 | 4 | 407 | two sum | 1 | 0.491 | Easy | 24 |
https://leetcode.com/problems/two-sum/discuss/444887/Python3C%2B%2B-hash-table | class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
seen = dict() #hash table of value-index pair
for i, num in enumerate(nums):
x = target - num #residual
if x in seen: return [seen[x], i]
seen[num] = i
return None | two-sum | [Python3/C++] hash table | ye15 | 4 | 774 | two sum | 1 | 0.491 | Easy | 25 |
https://leetcode.com/problems/two-sum/discuss/398550/Two-Solutions-in-Python-3-(Dictionary)-(-O(n)-) | class Solution:
def twoSum(self, N: List[int], t: int) -> List[int]:
D = {n:i for i,n in enumerate(N)}
for i,n in enumerate(N):
x = t - n
if x in D and D[x] != i: return [i,D[x]] | two-sum | Two Solutions in Python 3 (Dictionary) ( O(n) ) | junaidmansuri | 4 | 1,800 | two sum | 1 | 0.491 | Easy | 26 |
https://leetcode.com/problems/two-sum/discuss/398550/Two-Solutions-in-Python-3-(Dictionary)-(-O(n)-) | class Solution:
def twoSum(self, N: List[int], t: int) -> List[int]:
D = {}
for i,n in enumerate(N):
if n not in D: D[n] = i
x = t - n
if x in D and D[x] != i: return [i,D[x]]
- Junaid Mansuri
(LeetCode ID)@hotmail.com | two-sum | Two Solutions in Python 3 (Dictionary) ( O(n) ) | junaidmansuri | 4 | 1,800 | two sum | 1 | 0.491 | Easy | 27 |
https://leetcode.com/problems/two-sum/discuss/384034/super-basic-question... | class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]: | two-sum | super basic question... | jstarrk | 4 | 815 | two sum | 1 | 0.491 | Easy | 28 |
https://leetcode.com/problems/two-sum/discuss/2762217/Python-Simple-Solution-oror-Easy-to-Understand | class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
for i in range(len(nums)-1):
for j in range(i+1,len(nums)):
if nums[i]+nums[j]==target: return [i,j] | two-sum | 🐍🐍Python Simple Solution || Easy to Understand✅✅ | sourav638 | 3 | 43 | two sum | 1 | 0.491 | Easy | 29 |
https://leetcode.com/problems/two-sum/discuss/2724248/Python's-Simple-and-Easy-to-Understand-Solution-Using-Dictionary-or-99-Faster | class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
# Creating Dictonary for Lookup
lookup = {}
for i in range(len(nums)):
# if target-n in lookup return n index and current index
if target-nums[i] in lookup:
return [lookup[target-nums[i]], i]
lookup[nums[i]] = i | two-sum | ✔️ Python's Simple and Easy to Understand Solution Using Dictionary | 99% Faster 🔥 | pniraj657 | 3 | 639 | two sum | 1 | 0.491 | Easy | 30 |
https://leetcode.com/problems/two-sum/discuss/2671221/Python-three-solutions | class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
if nums[i] + nums[j] == target:
return [i, j] | two-sum | ✔️ Python three solutions | QuiShimo | 3 | 460 | two sum | 1 | 0.491 | Easy | 31 |
https://leetcode.com/problems/two-sum/discuss/2671221/Python-three-solutions | class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
for i in range(len(nums)):
find_num = target - nums[i]
if find_num in nums and nums.index(find_num) != i:
return [i, nums.index(find_num)] | two-sum | ✔️ Python three solutions | QuiShimo | 3 | 460 | two sum | 1 | 0.491 | Easy | 32 |
https://leetcode.com/problems/two-sum/discuss/2671221/Python-three-solutions | class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
nums_dict = {}
for i, j in enumerate(nums):
find_number = target - nums[i]
if find_number in nums_dict:
return [nums_dict[find_number], i]
nums_dict[j] = i | two-sum | ✔️ Python three solutions | QuiShimo | 3 | 460 | two sum | 1 | 0.491 | Easy | 33 |
https://leetcode.com/problems/two-sum/discuss/2269969/Python3-solution-using-enumerate | class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
prevMap = {}
for i, n in enumerate(nums):
diff = target - n
if diff in prevMap:
return [prevMap[diff], i]
prevMap[n] = i | two-sum | Python3 solution using enumerate | __Simamina__ | 3 | 451 | two sum | 1 | 0.491 | Easy | 34 |
https://leetcode.com/problems/two-sum/discuss/2073481/Python-easy-to-understand-and-read-or-sorting | class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
arr = []
for i, num in enumerate(nums):
arr.append([i, num])
arr.sort(key=lambda x:x[1])
ans = []
i, j = 0, len(arr)-1
while i < j:
sums = arr[i][1] + arr[j][1]
if sums == target:
return [arr[i][0], arr[j][0]]
if sums > target:
j = j-1
else:
i = i+1 | two-sum | Python easy to understand and read | sorting | sanial2001 | 3 | 635 | two sum | 1 | 0.491 | Easy | 35 |
https://leetcode.com/problems/two-sum/discuss/1753486/brute-force | class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
if nums[i] + nums[j] == target:
return [i, j] | two-sum | brute force | ggeeoorrggee | 3 | 238 | two sum | 1 | 0.491 | Easy | 36 |
https://leetcode.com/problems/two-sum/discuss/1653823/O(n)-Solution-using-dictionary-in-Python | class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
# O(n) solution using HashMap or Dictionary
dict_nums = {}
for idx in range(0, len(nums)):
curr_num = nums[idx]
diff = target - curr_num
if diff in dict_nums:
return [idx, dict_nums[diff]]
else:
dict_nums[curr_num] = idx
# # Brute Force - O(n2)
# for i in range(0, len(nums)-1):
# for j in range(i+1, len(nums)):
# if nums[i] + nums[j] == target:
# return [i, j]
``` | two-sum | O(n) Solution using dictionary in Python | coddify | 3 | 275 | two sum | 1 | 0.491 | Easy | 37 |
https://leetcode.com/problems/two-sum/discuss/1630535/Python-3-oror-brute-force | class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
for i in range(len(nums)):
for j in range(i):
if nums[i]+nums[j]==target: return [i,j] | two-sum | Python 3 || brute force | anon_python_coder | 3 | 820 | two sum | 1 | 0.491 | Easy | 38 |
https://leetcode.com/problems/two-sum/discuss/1392824/Python3-96-faster-(52-ms)-Hash-Table-Solution | class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
D = {}
for i in range(len(nums)):
temp = target-nums[i]
if temp in D:
return [i, D[temp]]
else:
D[nums[i]] = i | two-sum | [Python3] 96% faster (52 ms) - Hash Table Solution | Loqz | 3 | 1,800 | two sum | 1 | 0.491 | Easy | 39 |
https://leetcode.com/problems/two-sum/discuss/1124970/Python3-Solution-using-Hashmap-by-dictionary | class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
map = {}
for i in range(len(nums)):
map[nums[i]] = i
for i in range(len(nums)):
value = target - nums[i]
if value in map and map[value] != i:
return [i, map[value]] | two-sum | Python3 Solution using Hashmap by dictionary | vtthanh99 | 3 | 487 | two sum | 1 | 0.491 | Easy | 40 |
https://leetcode.com/problems/two-sum/discuss/967361/Python3-O(n)-with-explanation | class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
seen = {}
for i in range(len(nums)):
key = target-nums[i]
if key in seen:
return [seen[key], i]
seen[nums[i]] = i | two-sum | [Python3] O(n) with explanation | gdm | 3 | 527 | two sum | 1 | 0.491 | Easy | 41 |
https://leetcode.com/problems/two-sum/discuss/2426335/Python-Solution | class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
hashMap = {}
for i in range(len(nums)):
hashMap[nums[i]] = i
for i in range(len(nums)):
rem = target -nums[i]
if rem in hashMap and hashMap[rem] != i:
return [i,hashMap[rem]]
#Upvote will be encouraging. | two-sum | Python Solution | anshsharma17 | 2 | 341 | two sum | 1 | 0.491 | Easy | 42 |
https://leetcode.com/problems/two-sum/discuss/2000886/Python-3-Solution-oror-Three-Approaches | class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
# For storing answers in one hashmap also will check if any value exists in nums
checker = {}
for i, n in enumerate(nums):
diff_value = target - n
# If value already in answer checker
if diff_value in checker:
return [checker[diff_value],i]
checker[n] = i | two-sum | ✅ Python 3 Solution || Three Approaches | mitchell000 | 2 | 459 | two sum | 1 | 0.491 | Easy | 43 |
https://leetcode.com/problems/two-sum/discuss/2000886/Python-3-Solution-oror-Three-Approaches | class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
# For storing answers in one set also will check if any value exists in nums
checker = set()
for i in range(len(nums)):
# If value already in answer checker
if nums[i] in checker:
return [nums.index(target-nums[i]),i]
else:
checker.add(target-nums[i]) | two-sum | ✅ Python 3 Solution || Three Approaches | mitchell000 | 2 | 459 | two sum | 1 | 0.491 | Easy | 44 |
https://leetcode.com/problems/two-sum/discuss/2000886/Python-3-Solution-oror-Three-Approaches | class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
left = 0
right = len(nums)
while left < right:
if target-nums[left] in nums and nums.index(target-nums[left]) != left:
return [left,nums.index(target-nums[left])]
else:
left+=1 | two-sum | ✅ Python 3 Solution || Three Approaches | mitchell000 | 2 | 459 | two sum | 1 | 0.491 | Easy | 45 |
https://leetcode.com/problems/add-two-numbers/discuss/1835217/Python3-DUMMY-CARRY-(-**-)-Explained | class Solution:
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
res = dummy = ListNode()
carry = 0
while l1 or l2:
v1, v2 = 0, 0
if l1: v1, l1 = l1.val, l1.next
if l2: v2, l2 = l2.val, l2.next
val = carry + v1 + v2
res.next = ListNode(val%10)
res, carry = res.next, val//10
if carry:
res.next = ListNode(carry)
return dummy.next | add-two-numbers | ✔️ [Python3] DUMMY CARRY ( •⌄• ू )✧, Explained | artod | 44 | 7,100 | add two numbers | 2 | 0.398 | Medium | 46 |
https://leetcode.com/problems/add-two-numbers/discuss/452442/Python-3%3A-recursion | class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
_ = l1.val + l2.val
digit, tenth = _ % 10, _ // 10
answer = ListNode(digit)
if any((l1.next, l2.next, tenth)):
l1 = l1.next if l1.next else ListNode(0)
l2 = l2.next if l2.next else ListNode(0)
l1.val += tenth
answer.next = self.addTwoNumbers(l1, l2)
return answer | add-two-numbers | Python 3: recursion | deleted_user | 39 | 4,200 | add two numbers | 2 | 0.398 | Medium | 47 |
https://leetcode.com/problems/add-two-numbers/discuss/486839/Python-Simple-Solution-8-Liner | class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
sumval = 0
root = curr = ListNode(0)
while l1 or l2 or sumval:
if l1: sumval += l1.val; l1 = l1.next
if l2: sumval += l2.val; l2 = l2.next
curr.next = curr = ListNode(sumval % 10)
sumval //= 10
return root.next | add-two-numbers | Python - Simple Solution - 8 Liner | mmbhatk | 18 | 4,600 | add two numbers | 2 | 0.398 | Medium | 48 |
https://leetcode.com/problems/add-two-numbers/discuss/2024907/Simple-Python3-Solution | class Solution:
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
dummy = ListNode()
cur = dummy
carry = 0
while l1 or l2 or carry:
v1 = l1.val if l1 else 0
v2 = l2.val if l2 else 0
# new digit val
val = v1 + v2 + carry
carry = val // 10
val = val % 10
cur.next = ListNode(val) # as in one place we have to put a single digit
# update pointers
cur = cur.next
l1 = l1.next if l1 else None
l2 = l2.next if l2 else None
return dummy.next
# Time: O(n + m)
# Space: O(n + m) | add-two-numbers | Simple Python3 Solution✨ | samirpaul1 | 11 | 1,000 | add two numbers | 2 | 0.398 | Medium | 49 |
https://leetcode.com/problems/add-two-numbers/discuss/1353295/Python-Runtime-60ms | class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
start = curr = ListNode(0)
carry = 0
while(l1 or l2 or carry):
x = l1.val if l1 else 0
y = l2.val if l2 else 0
carry, val = divmod(x + y + carry, 10)
curr.next = ListNode(val)
curr = curr.next
l1 = l1.next if l1 else None
l2 = l2.next if l2 else None
return start.next | add-two-numbers | [Python] Runtime 60ms | yadvendra | 11 | 1,200 | add two numbers | 2 | 0.398 | Medium | 50 |
https://leetcode.com/problems/add-two-numbers/discuss/2383456/Fastest-Solution-Explained0ms100-O(n)time-complexity-O(n)space-complexity | class Solution:
def addTwoNumbers(self, l1, l2):
list1 = make_list_from_ListNode(l1)
list2 = make_list_from_ListNode(l2)
### RIGHT PAD WITH ZEROES
len_list1 = len(list1)
len_list2 = len(list2)
if len_list1 > len_list2:
pad = len_list1 - len_list2
list2 = list2 + [0,] * pad
elif len_list2 > len_list1:
pad = len_list2 - len_list1
list1 = list1 + [0,] * pad
### DO THE MATH
d = 0
the_sum = list()
for x,y in zip(list1, list2):
d, m = divmod(x + y + d, 10)
the_sum.append(m)
if d != 0:
the_sum.append(d)
return make_ListNode_from_list(the_sum) | add-two-numbers | [Fastest Solution Explained][0ms][100%] O(n)time complexity O(n)space complexity | cucerdariancatalin | 10 | 1,700 | add two numbers | 2 | 0.398 | Medium | 51 |
https://leetcode.com/problems/add-two-numbers/discuss/1636945/Python3-O(1)-Space-or-1-pass-or-Optimal-or-Beats-100 | class Solution:
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
carry, head = 0, l1
while l1 or l2:
if not l1.next and l2: l1.next, l2.next = l2.next, l1.next
val1 = l1.val if l1 else 0
val2 = l2.val if l2 else 0
carry, l1.val = divmod(val1 + val2 + carry, 10)
prev = l1
if l1: l1 = l1.next
if l2: l2 = l2.next
if carry: prev.next = ListNode(carry)
return head | add-two-numbers | [Python3] O(1) Space | 1 pass | Optimal | Beats 100% | PatrickOweijane | 9 | 814 | add two numbers | 2 | 0.398 | Medium | 52 |
https://leetcode.com/problems/add-two-numbers/discuss/1784472/Python-3-greater-Simple-solution-that-was-asked-in-real-interview | class Solution:
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
carryOver = 0
result = ListNode(-1)
resultTail = result
while l1 or l2:
total = 0
if l1:
total += l1.val
l1 = l1.next
if l2:
total += l2.val
l2 = l2.next
total += carryOver
carryOver, remainder = divmod(total, 10)
resultTail.next = ListNode(remainder)
resultTail = resultTail.next
if carryOver > 0:
resultTail.next = ListNode(carryOver)
return result.next | add-two-numbers | Python 3 -> Simple solution that was asked in real interview | mybuddy29 | 8 | 637 | add two numbers | 2 | 0.398 | Medium | 53 |
https://leetcode.com/problems/add-two-numbers/discuss/468242/Easy-to-follow-Python3-solution-(faster-than-96-and-memory-usage-less-than-100) | class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
r = None
p = None
c = 0
while l1 or l2 or c != 0:
v = (l1.val if l1 else 0) + (l2.val if l2 else 0) + c
c = v // 10
n = ListNode(v % 10)
if r is None:
r = n
if p is not None:
p.next = n
p = n
l1 = l1.next if l1 else None
l2 = l2.next if l2 else None
return r | add-two-numbers | Easy-to-follow Python3 solution (faster than 96% & memory usage less than 100%) | gizmoy | 7 | 1,400 | add two numbers | 2 | 0.398 | Medium | 54 |
https://leetcode.com/problems/add-two-numbers/discuss/1836636/Python-Easy-Solution-or-Explained | class Solution:
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
head = sm = ListNode() # head: we get the start to return, sm: to iterate and link the new sum nodes.
carry = 0 # carry starts with zero
while l1 or l2: # we are using or, because list sizes might not be equal.
if l1: carry, l1 = carry + l1.val, l1.next # if l1 is not null, add it to carry and update l1 to its next.
if l2: carry, l2 = carry + l2.val, l2.next # if l2 is not null, add it to carry and update l2 to its next.
sm.next = sm = ListNode(val = carry % 10) # make a new node with carry % 10(because carry can be greater than 9, ie two digits) and link the sm.next to it and now this new node is our sm
carry //= 10 # if carry is greater than 9, means we have to add it in next iteration
if carry: sm.next = ListNode(val = carry) # what if there is non zero carry left to be added.
return head.next # return head.next bcoz head is pointing to dummy node. | add-two-numbers | ✅ Python Easy Solution | Explained | dhananjay79 | 5 | 397 | add two numbers | 2 | 0.398 | Medium | 55 |
https://leetcode.com/problems/add-two-numbers/discuss/2308917/Python3-using-two-pointers | class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
dummy = ListNode()
cur = dummy
carry = 0
while l1 or l2 or carry:
v1 = l1.val if l1 else 0
v2 = l2.val if l2 else 0
val = v1 + v2 + carry
carry = val // 10
val = val % 10
cur.next = ListNode(val)
cur = cur.next
l1 = l1.next if l1 else None
l2 = l2.next if l2 else None
return dummy.next | add-two-numbers | Python3 using two pointers | __Simamina__ | 4 | 249 | add two numbers | 2 | 0.398 | Medium | 56 |
https://leetcode.com/problems/add-two-numbers/discuss/1369722/python-3-solution-easyy | class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
carry=0
h=ListNode()
head=h
while l1 or l2 or carry:
result=0
if l1:
result+=l1.val
l1=l1.next
if l2:
result+=l2.val
l2=l2.next
if carry:
result+=carry
val=result%10
carry=result//10
head.next=ListNode(val)
head=head.next
return h.next | add-two-numbers | python 3 solution easyy | minato_namikaze | 4 | 535 | add two numbers | 2 | 0.398 | Medium | 57 |
https://leetcode.com/problems/add-two-numbers/discuss/1515075/Python-solution-explained-(linked-list-greater-list-and-slice) | class Solution:
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
list_l1 = []
list_l1_int = ''
list_l2 = []
list_l2_int = ''
# convert linked lists to lists
while l1:
list_l1.append(l1.val)
l1 = l1.next
while l2:
list_l2.append(l2.val)
l2 = l2.next
# iterate thru lists in reverse and recreate int from list
for x in list_l1[::-1]:
list_l1_int += str(x)
for x in list_l2[::-1]:
list_l2_int += str(x)
# sum
list_sum = int(list_l1_int) + int(list_l2_int)
# now create list node from the sum (use s, t to return linked list at right iteration)
s = t = ListNode()
# conv to str, iterate thru items in reverse, create linked list
for x in str(list_sum)[::-1]:
s.next = ListNode(x)
s = s.next
return t.next | add-two-numbers | Python solution explained (linked list -> list & slice) | jjluxton | 3 | 964 | add two numbers | 2 | 0.398 | Medium | 58 |
https://leetcode.com/problems/add-two-numbers/discuss/1222978/python3-%3A-Easy-to-understand-and-straight-forward-approach | class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
# base cases
if l1==None:
return l2
if l2==None:
return l1
curr = ListNode(0)
head = curr
carry = 0
while l1 and l2:
total = 0
total += carry + l1.val + l2.val
curr.next = ListNode(total%10)
carry = total // 10
curr = curr.next
l1 = l1.next
l2 = l2.next
while (l1):
total = 0
total += carry + l1.val
curr.next = ListNode(total%10)
carry = total // 10
curr = curr.next
l1 = l1.next
while (l2):
total = 0
total += carry + l2.val
curr.next = ListNode(total%10)
carry = total // 10
curr = curr.next
l2 = l2.next
if carry:
curr.next = ListNode(carry)
return head.next | add-two-numbers | python3 : Easy to understand and straight forward approach | nandanabhishek | 3 | 353 | add two numbers | 2 | 0.398 | Medium | 59 |
https://leetcode.com/problems/add-two-numbers/discuss/1081524/python3-easy-solution-with-detailed-comments-faster-than-96.55 | class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
# Keep a dummy head for your return
sentinel = ListNode(0)
curr = sentinel
# Initializes two pointers pointing to two lists seperately
node1, node2 = l1, l2
# Check if we need add '1' to next calculation
carry = False
while node1 or node2:
# Calculate the current sum, if node is None then initializes to 0
i = node1.val if node1 else 0
y = node2.val if node2 else 0
total = i + y
# Check carry and update current sum
if carry:
total += 1
carry = False
# Modify total sum to one digit number and update carry
if total >= 10:
carry = True
total -= 10
# Initializes a new node based on current sum and link to the dummy head
to_add = ListNode(total)
curr.next = to_add
curr = to_add
# Update node1 and node2 for next calculation
node1 = node1.next if node1 else None
node2 = node2.next if node2 else None
# Check carry at the end of calculation
if carry:
extraDigit = ListNode(1)
curr.next = extraDigit
return sentinel.next | add-two-numbers | python3 easy solution with detailed comments, faster than 96.55% | IssacZ | 3 | 554 | add two numbers | 2 | 0.398 | Medium | 60 |
https://leetcode.com/problems/add-two-numbers/discuss/972330/Python3-solution | class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
first_num=[]
second_num=[]
while l1 is not None:
first_num.append(l1.val)
l1=l1.next
while l2 is not None:
second_num.append(l2.val)
l2=l2.next
first_num.reverse()
second_num.reverse()
res1=int(''.join(map(str,first_num)))
res2=int(''.join(map(str,second_num)))
res3=str(res1+res2)
l3=None
for i in res3:
data=int(i)
newnode=ListNode(data)
if not l3:
l3=newnode
else:
newnode.next=l3
l3=newnode
return l3 | add-two-numbers | Python3 solution | samarthnehe | 3 | 453 | add two numbers | 2 | 0.398 | Medium | 61 |
https://leetcode.com/problems/add-two-numbers/discuss/2214565/Python3-or-Easy-to-Understand-or-Simple | class Solution:
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
result = ListNode()
result_tail = result
carry = 0
while l1 or l2 or carry:
val1 = l1.val if l1 else 0
val2 = l2.val if l2 else 0
out = (val1 + val2 + carry) % 10
carry = (val1 + val2 + carry) // 10
result_tail.next = ListNode(out)
result_tail = result_tail.next
l1 = l1.next if l1 else None
l2 = l2.next if l2 else None
return result.next | add-two-numbers | ✅Python3 | Easy to Understand | Simple | thesauravs | 2 | 120 | add two numbers | 2 | 0.398 | Medium | 62 |
https://leetcode.com/problems/add-two-numbers/discuss/2127776/EASY-Python-Solution-O(n) | class Solution:
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
s1, s2 = '', ''
while l1:
s1 += str(l1.val)
l1 = l1.next
while l2:
s2 += str(l2.val)
l2 = l2.next
s1 = int(s1[::-1])
s2 = int(s2[::-1])
total = str(s1 + s2)
head = None
for c in total:
n = ListNode(c)
n.next = head
head = n
return head | add-two-numbers | EASY Python Solution O(n) | anselchacko | 2 | 406 | add two numbers | 2 | 0.398 | Medium | 63 |
https://leetcode.com/problems/add-two-numbers/discuss/2079491/Python-Very-Intuitive-Solution | class Solution:
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
int_1 = int_2 = 0
i = 0
while l1 or l2:
if l1:
int_1 += l1.val * (10 ** i)
l1 = l1.next
if l2:
int_2 += l2.val * (10 ** i)
l2 = l2.next
i += 1
int_sum = int_1 + int_2
for i, char in enumerate(list(str(int_sum))):
if i == 0:
node = ListNode(int(char), None)
else:
node = ListNode(int(char), node)
return node | add-two-numbers | Python Very Intuitive Solution | codeee5141 | 2 | 378 | add two numbers | 2 | 0.398 | Medium | 64 |
https://leetcode.com/problems/add-two-numbers/discuss/1837667/Accepted-Python3-solution-DUMMY-DUMMY | class Solution:
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
if l1 == None and l2 == None:
return ListNode(0)
a = b = i = 0
while l1 != None:
a += l1.val * (10 ** i)
i += 1
l1 = l1.next
i = 0
while l2 != None:
b += l2.val * (10 ** i)
i += 1
l2 = l2.next
ans = a + b
x = [int(l) for l in str(ans)][::-1]
ansll = dummy = ListNode()
for i in x[:-1]:
ansll.val = i
ansll.next = ListNode()
ansll = ansll.next
ansll.val = x[-1]
return dummy | add-two-numbers | Accepted Python3 solution DUMMY DUMMY | ElizaZoldyck | 2 | 54 | add two numbers | 2 | 0.398 | Medium | 65 |
https://leetcode.com/problems/add-two-numbers/discuss/1811728/PythonJava-Simple-Addition-Algorithm-or-Digit-by-Digit | class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
temp = ListNode(0)
ptr1 = l1; ptr2 = l2
curr = temp; carry = 0
while ptr1 or ptr2:
x = ptr1.val if ptr1 else 0
y = ptr2.val if ptr2 else 0
s = x+y+carry
carry = s//10
curr.next = ListNode(s%10)
curr = curr.next
if ptr1:
ptr1 = ptr1.next
if ptr2:
ptr2 = ptr2.next
if carry:
curr.next = ListNode(carry)
return temp.next | add-two-numbers | [Python/Java] Simple Addition Algorithm | Digit by Digit | hari19041 | 2 | 537 | add two numbers | 2 | 0.398 | Medium | 66 |
https://leetcode.com/problems/add-two-numbers/discuss/1684721/Python-O(n)-and-in-place-beat-96 | class Solution:
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
# O(n) and O(1)
head = l1
carry, l1.val = divmod(l1.val + l2.val, 10)
while l1.next and l2.next:
l1 = l1.next
l2 = l2.next
carry, l1.val = divmod(l1.val + l2.val + carry, 10)
if l2.next:
l1.next = l2.next
while l1.next:
l1 = l1.next
carry, l1.val = divmod(l1.val + carry, 10)
if carry:
l1.next = ListNode(carry)
return head | add-two-numbers | Python, O(n) and in-place, beat 96% | yaok09 | 2 | 546 | add two numbers | 2 | 0.398 | Medium | 67 |
https://leetcode.com/problems/add-two-numbers/discuss/1409756/python-and-c%2B%2B-solution-(O(n)-most-efficient-solution-in-both-space-and-time-) | class Solution:
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
ans=ListNode()
current=ans
carry=0
while l1 and l2 :
add=l1.val+l2.val+carry
val=add%10
carry=add//10
current.next=ListNode(val)
current=current.next
l1=l1.next
l2=l2.next
current.next=l1 or l2
while carry>0:
if current.next :
current=current.next
else:
current.next=ListNode(carry)
carry=0
add=carry+current.val
val=add%10
carry=add//10
current.val=val
return ans.next | add-two-numbers | python and c++ solution ,(O(n) most efficient solution in both space and time ) | sagarhparmar12345 | 2 | 270 | add two numbers | 2 | 0.398 | Medium | 68 |
https://leetcode.com/problems/add-two-numbers/discuss/1401366/Python-easy-or-O(n)-or-Without-extra-space | class Solution:
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
h1, h2, prev = l1, l2, None
carry = 0
while h1 != None and h2 != None:
sm = h1.val+h2.val+carry
carry = sm//10
h1.val = sm%10
prev = h1
h1 = h1.next
h2 = h2.next
if h2!=None:
h1 = h2
#since we are overriding the first linked list, so our priority is on head1
if prev!=None:
#if case will handle this edge case l1 = [] l2 = [1,2,3]
prev.next = h2
while h1!=None:
sm = h1.val+carry
carry = sm//10
h1.val = sm%10
prev = h1
h1 = h1.next
if carry:
prev.next = ListNode(carry)
return l1 | add-two-numbers | Python easy | O(n) | Without extra space | sathwickreddy | 2 | 909 | add two numbers | 2 | 0.398 | Medium | 69 |
https://leetcode.com/problems/add-two-numbers/discuss/262494/Python-faster-than-100-and-easy-to-read | class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode, over=0) -> ListNode:
if l1 is None and l2 is None:
if over > 0:
return ListNode(over)
return None
num = over
next1 = None
next2 = None
if not l1 is None:
num += l1.val
next1 = l1.next
if not l2 is None:
num += l2.val
next2 = l2.next
node = ListNode(num)
over = 0
if node.val > 9:
over = 1
node.val -= 10
node.next = self.addTwoNumbers(next1, next2, over)
return node | add-two-numbers | Python faster than 100% and easy to read | mpSchrader | 2 | 595 | add two numbers | 2 | 0.398 | Medium | 70 |
https://leetcode.com/problems/add-two-numbers/discuss/2642238/Python-O(n)-Time-Space-Solution | class Solution: # Time: O(n) and Space: O(n)
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
dummy = cur = ListNode() # Creating a new node to store l1 + l2 values, dummy will give us head address & cur will be used to append new nodes
carry = 0
while l1 or l2 or carry: # we will continue till either one of these have positive values left
v1 = l1.val if l1 else 0
v2 = l2.val if l2 else 0
# Addition: New digits
val = v1 + v2 + carry # in 1st iteration carry will be 0, but in next iterations previous iter generated carry will be added
carry = val // 10 # if val = 15 then 15//10 = 1 ie. (1.5)
val = val % 10 # 15 % 10 = 5
cur.next = ListNode(val) # dummy/cur --> val
# Update pointers
cur = cur.next # dummy --> val/cur
l1 = l1.next if l1 else None
l2 = l2.next if l2 else None
return dummy.next | add-two-numbers | Python O(n) Time-Space Solution | DanishKhanbx | 1 | 221 | add two numbers | 2 | 0.398 | Medium | 71 |
https://leetcode.com/problems/add-two-numbers/discuss/1957325/python3-or-99.16-faster-and-O(n)-time-complexity | class Solution:
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
dummy = curr = ListNode(0)
carry = 0
while l1 and l2 :
tsum = l1.val + l2.val + carry
num = tsum % 10
curr.next = ListNode(num)
curr = curr.next
carry = tsum // 10
l1 = l1.next
l2 = l2.next
while l1:
tsum = l1.val + carry
if tsum > 9:
num = tsum % 10
curr.next = ListNode(num)
carry = tsum // 10
else:
curr.next = ListNode(tsum)
carry = 0
curr = curr.next
l1 = l1.next
while l2:
tsum = l2.val + carry
if tsum > 9:
num = tsum % 10
curr.next = ListNode(num)
carry = tsum // 10
else:
curr.next = ListNode(tsum)
carry = 0
curr = curr.next
l2 = l2.next
if carry > 0:
curr.next = ListNode(carry)
return dummy.next | add-two-numbers | python3 | 99.16% faster and O(n) time complexity | sanketsans | 1 | 187 | add two numbers | 2 | 0.398 | Medium | 72 |
https://leetcode.com/problems/add-two-numbers/discuss/1836620/Python-Simple-Solution | class Solution:
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
res = 0
ans = ListNode()
cur = ans
while l1 and l2:
d = l1.val + l2.val + res
res = d//10
cur.next = ListNode(d%10)
cur = cur.next
l1 = l1.next
l2 = l2.next
cur1 = l2
if l1:
cur1 = l1
while cur1:
d = cur1.val + res
res = d//10
cur.next = ListNode(d%10)
cur = cur.next
cur1 = cur1.next
if res:
cur.next = ListNode(res)
return ans.next | add-two-numbers | [Python] Simple Solution | zouhair11elhadi | 1 | 65 | add two numbers | 2 | 0.398 | Medium | 73 |
https://leetcode.com/problems/add-two-numbers/discuss/1761128/Easy-to-Understand-Python-Solution | class Solution:
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
vals1 = []
vals2 = []
cur = dummy = ListNode(0)
while l1 is not None:
vals1.append(str(l1.val))
l1 = l1.next
while l2 is not None:
vals2.append(str(l2.val))
l2 = l2.next
vals1.reverse()
vals2.reverse()
c = int("".join(vals1))
d = int("".join(vals2))
amount = list(str(c + d))
amount.reverse()
for i in amount:
cur.next = ListNode(int(i))
cur = cur.next
return dummy.next | add-two-numbers | Easy to Understand Python Solution | newcomerlearn | 1 | 304 | add two numbers | 2 | 0.398 | Medium | 74 |
https://leetcode.com/problems/add-two-numbers/discuss/1757973/Brief-and-pythonic | class Solution:
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
def lstIter(lst):
while lst is not None:
yield lst.val
lst = lst.next
head = prev = ListNode(0)
carry = 0
for x in (ListNode(sum(x)) for x in zip_longest(lstIter(l1), lstIter(l2), fillvalue=0)):
prev.next = prev = x
x.val, carry = (carry + x.val) % 10, (carry + x.val) // 10
if carry:
prev.next = ListNode(carry)
return head.next | add-two-numbers | Brief and pythonic | Lrnx | 1 | 110 | add two numbers | 2 | 0.398 | Medium | 75 |
https://leetcode.com/problems/add-two-numbers/discuss/1582607/Python-Solution | class Solution:
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
output = curr = ListNode()
o = 0 #overflow
while l1 or l2:
n1, n2 = 0, 0
if l1:
n1 = l1.val
l1 = l1.next
if l2:
n2 = l2.val
l2 = l2.next
if n1 + n2 + o >= 10:
curr.next = ListNode(n1+n2+o-10)
o = 1
else:
curr.next = ListNode(n1+n2+o)
o = 0
curr = curr.next
if o:
curr.next = ListNode(o)
return output.next | add-two-numbers | Python Solution | overzh_tw | 1 | 178 | add two numbers | 2 | 0.398 | Medium | 76 |
https://leetcode.com/problems/longest-substring-without-repeating-characters/discuss/742926/Simple-Explanation-or-Concise-or-Thinking-Process-and-Example | class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int abcabcbb
"""
if len(s) == 0:
return 0
seen = {}
left, right = 0, 0
longest = 1
while right < len(s):
if s[right] in seen:
left = max(left,seen[s[right]]+1)
longest = max(longest, right - left + 1)
seen[s[right]] = right
right += 1
print(left, right, longest)
return longest | longest-substring-without-repeating-characters | Simple Explanation | Concise | Thinking Process & Example | ivankatrump | 290 | 13,100 | longest substring without repeating characters | 3 | 0.338 | Medium | 77 |
https://leetcode.com/problems/longest-substring-without-repeating-characters/discuss/2132954/Python-Simple-Solution-w-Explanation-or-Brute-Force-%2B-Sliding-Window | class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
res = 0
seen = set()
for start_idx in range(len(s)):
seen.clear()
end_idx = start_idx
while end_idx < len(s):
if s[end_idx] in seen:
break
seen.add(s[end_idx])
end_idx += 1
res = max(res, end_idx - start_idx)
return res | longest-substring-without-repeating-characters | ✅ [Python] Simple Solution w/ Explanation | Brute-Force + Sliding Window | r0gue_shinobi | 26 | 1,900 | longest substring without repeating characters | 3 | 0.338 | Medium | 78 |
https://leetcode.com/problems/longest-substring-without-repeating-characters/discuss/2132954/Python-Simple-Solution-w-Explanation-or-Brute-Force-%2B-Sliding-Window | class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
prev = [-1] * 128
res, start_idx = 0, 0
for end_idx, char in enumerate(s):
if prev[ord(char)] >= start_idx:
start_idx = prev[ord(char)] + 1
prev[ord(char)] = end_idx
res = max(res, end_idx - start_idx + 1)
return res | longest-substring-without-repeating-characters | ✅ [Python] Simple Solution w/ Explanation | Brute-Force + Sliding Window | r0gue_shinobi | 26 | 1,900 | longest substring without repeating characters | 3 | 0.338 | Medium | 79 |
https://leetcode.com/problems/longest-substring-without-repeating-characters/discuss/2132791/Python-Easy-2-approaches | class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
counter = defaultdict(int) # track counts of each character
l=0
max_length=0
for r, c in enumerate(s):
counter[c]+=1
if counter[c] > 1:
while l<r and counter[c]>1: # iterate until window is valid
counter[s[l]]-=1
l+=1
max_length=max(max_length, r-l+1)
return max_length | longest-substring-without-repeating-characters | Python Easy 2 approaches ✅ | constantine786 | 21 | 2,000 | longest substring without repeating characters | 3 | 0.338 | Medium | 80 |
https://leetcode.com/problems/longest-substring-without-repeating-characters/discuss/2132791/Python-Easy-2-approaches | class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
last_seen = {}
l=0
max_length=0
for r in range(len(s)):
if s[r] in last_seen:
l=max(last_seen[s[r]], l)
last_seen[s[r]]=r+1
max_length=max(max_length, r-l+1)
return max_length | longest-substring-without-repeating-characters | Python Easy 2 approaches ✅ | constantine786 | 21 | 2,000 | longest substring without repeating characters | 3 | 0.338 | Medium | 81 |
https://leetcode.com/problems/longest-substring-without-repeating-characters/discuss/2799840/Python-or-Easy-Solution | class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
output = 0
count = {}
pos = -1
for index, letter in enumerate(s):
if letter in count and count[letter] > pos:
pos = count[letter]
count[letter] = index
output = max(output,index-pos)
return output | longest-substring-without-repeating-characters | Python | Easy Solution✔ | manayathgeorgejames | 18 | 2,800 | longest substring without repeating characters | 3 | 0.338 | Medium | 82 |
https://leetcode.com/problems/longest-substring-without-repeating-characters/discuss/1526581/Simplest-way-(with-explanation)-97-faster | class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
string = s
max_length = 0 # we set max_length to 0 because string may be empty.
seen_character = '' # a empty string to store the character that we have already seen.
for letter in string: # we are checking every letter/character in string...
if letter not in seen_character:
seen_character += letter # if letter not in there then we add to it.
else:
## now if the letter is already in seen_character then we get the index of that letter by using seen_character.index() and then we slice the string from that index+1 to last, so that the the first seen letter will be removed.
# for example - 'abcabbd' # here after 'abc' , again "a" was there so we get the index of first "a" and slice the string then be get string = "bc" .
seen_character = seen_character[seen_character.index(letter) + 1:] + letter
# and then we add the letter "a" to the last. so the string will become "bca"
max_length = max(max_length, len(seen_character)) # here we use a function max() that everytime return the maximum value between two number. it sets max_length each time the loop runs.
return max_length # finally return the maximum length.
#by - Tony Stark | longest-substring-without-repeating-characters | Simplest way (with explanation) [97% faster] | tony_stark_47 | 16 | 1,000 | longest substring without repeating characters | 3 | 0.338 | Medium | 83 |
https://leetcode.com/problems/longest-substring-without-repeating-characters/discuss/2219528/Simple-Python-Solution-oror-Sliding-Window | class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
set_ = set()
res = 0
l = 0
for r in range(len(s)):
while s[r] in set_:
set_.remove(s[l])
l += 1
set_.add(s[r])
res = max(res, r-l+1)
return res
# An Upvote will be encouraging | longest-substring-without-repeating-characters | Simple Python Solution || Sliding Window | rajkumarerrakutti | 13 | 687 | longest substring without repeating characters | 3 | 0.338 | Medium | 84 |
https://leetcode.com/problems/longest-substring-without-repeating-characters/discuss/1074783/Python-Interview-Thought-Process%3A-O(2n)-greater-O(n) | class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
queue = collections.deque([])
window = set()
result = 0
for c in s:
if c in window:
while queue:
prev = queue.popleft()
window.remove(prev)
if prev == c:
break
queue.append(c)
window.add(c)
result = max(result, len(window))
return result | longest-substring-without-repeating-characters | Python Interview Thought Process: O(2^n) -> O(n) | dev-josh | 11 | 1,300 | longest substring without repeating characters | 3 | 0.338 | Medium | 85 |
https://leetcode.com/problems/longest-substring-without-repeating-characters/discuss/1953837/Python-Easiest-Solution-With-Explanation-or-92.68-Fasteror-Beg-to-advor-Sliding-Window | class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
left = 0
res = 0
charSet = set() # taking set to have unique values.
for right in range(len(s)):
while s[right] in charSet: # if we are getting duplication character then we have to update our set.
charSet.remove(s[left])
left+=1
charSet.add(s[right]) # once duplicate value is removed we are going to add right most element to the set
res = max(res,right-left+1) # at this stage we are sure that we dont have any duplicate , so lets update the res variable now.
return res | longest-substring-without-repeating-characters | Python Easiest Solution With Explanation | 92.68 % Faster| Beg to adv| Sliding Window | rlakshay14 | 9 | 362 | longest substring without repeating characters | 3 | 0.338 | Medium | 86 |
https://leetcode.com/problems/longest-substring-without-repeating-characters/discuss/1431722/Python-easy-solution-using-hashMap | class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
if s is None:
return 0
if len(s) <= 1:
return len(s)
charMap = dict()
start = 0
longest = 0
for i,c in enumerate(s):
if c in charMap:
start = max(start, charMap[c]+1)
longest = max(longest, i-start+1)
charMap[c] = i
return longest | longest-substring-without-repeating-characters | Python easy solution using hashMap | bTest2 | 9 | 1,100 | longest substring without repeating characters | 3 | 0.338 | Medium | 87 |
https://leetcode.com/problems/longest-substring-without-repeating-characters/discuss/1325444/easiest-solution-python-3......fastest | class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
start = 0
end = 0
max_len = 0
d={}
while end<len(s):
if s[end] in d and d[s[end]] >= start:
start = d[s[end]]+1
max_len = max(max_len , end-start+1)
d[s[end]] = end
end+=1
return(max_len) | longest-substring-without-repeating-characters | easiest solution python 3......fastest | pravishbajpai06 | 9 | 2,100 | longest substring without repeating characters | 3 | 0.338 | Medium | 88 |
https://leetcode.com/problems/longest-substring-without-repeating-characters/discuss/2166571/Python-Sliding-Window-(Thought-Process) | class Solution:
def lengthOfLongestSubstring(self, str: str) -> int:
# Handle empty input
if not str:
return 0
# Define result, start/end pointers, hashmap for seen characters
length = 1
start = 0
end = 0
seen = {}
# Iterate through string using sliding window technique
while end < len(str):
# You don't have to do this, but slightly cleaner
startChar = str[start]
endChar = str[end]
# If our end character has already been seen...
if endChar in seen:
# We should reset our start to the new end (+1), or the new start (if our last seen "end" char is before our current start)
start = max(start, seen[endChar] + 1)
# We set the length of our longest known substring w/out repeating characters
length = max(length, end - start + 1)
# We reset the index we've last seen end char at (or add it, if never seen before)
seen[endChar] = end
# Expand our window
end += 1
# Return our longest substring w/ no repeating characters
return length | longest-substring-without-repeating-characters | [Python] Sliding Window (Thought Process) | ernestshackleton | 8 | 424 | longest substring without repeating characters | 3 | 0.338 | Medium | 89 |
https://leetcode.com/problems/longest-substring-without-repeating-characters/discuss/1245216/Python-32ms-simple-and-easy | class Solution:
def lengthOfLongestSubstring(self, s):
unique=""
a=0
for c in s:
if c not in unique:
unique+=c
else:
unique = unique[unique.index(c)+1:]+c
a = max(a,len(unique))
return a | longest-substring-without-repeating-characters | Python- 32ms simple and easy | akashadhikari | 8 | 664 | longest substring without repeating characters | 3 | 0.338 | Medium | 90 |
https://leetcode.com/problems/longest-substring-without-repeating-characters/discuss/1595492/Python3-40-ms-faster-than-99.69 | class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
res = 0
longest_substr = ''
for ch in s:
if ch not in longest_substr:
longest_substr += ch
if len(longest_substr) > res:
res += 1
else:
i = longest_substr.find(ch)
longest_substr = longest_substr[i+1:] + ch
return res | longest-substring-without-repeating-characters | [Python3] 40 ms, faster than 99.69% | larysa_sh | 6 | 576 | longest substring without repeating characters | 3 | 0.338 | Medium | 91 |
https://leetcode.com/problems/longest-substring-without-repeating-characters/discuss/1256739/Python3-simple-solution-using-sliding-window-and-set | class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
left = right = ans = 0
char = set()
res = 0
while right < len(s):
if s[right] not in char:
char.add(s[right])
right += 1
else:
char.remove(s[left])
res = max(res, right-left)
left += 1
res = max(res, right - left)
return res | longest-substring-without-repeating-characters | Python3 simple solution using sliding-window and set | EklavyaJoshi | 6 | 342 | longest substring without repeating characters | 3 | 0.338 | Medium | 92 |
https://leetcode.com/problems/longest-substring-without-repeating-characters/discuss/240337/Python3-Simple-O(n)-Solution-68ms-runtime(99.52)-and-memory(100) | class Solution:
def lengthOfLongestSubstring(self, s: 'str') -> 'int':
max_sequence = ""
current_sequence = ""
for ch in s:
if ch in current_sequence:
if len(current_sequence) > len(max_sequence):
max_sequence = current_sequence
current_sequence = current_sequence[current_sequence.index(ch) + 1:] + ch
else:
current_sequence += ch
return max(len(max_sequence), len(current_sequence)) | longest-substring-without-repeating-characters | Python3 - Simple O(n) Solution 68ms, runtime(99.52%) and memory(100%) | nikhil_g777 | 6 | 559 | longest substring without repeating characters | 3 | 0.338 | Medium | 93 |
https://leetcode.com/problems/longest-substring-without-repeating-characters/discuss/1453922/Python3-Hashmap-easy-solution-or-faster-than-99.94 | class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
start = -1 # start index of current substring
longest = 0 # length of the longest substring
hash_map = dict() # hash map is to store the latest index of char
for i in range(len(s)):
if s[i] in hash_map and start < hash_map[s[i]]:
start = hash_map[s[i]]
hash_map[s[i]] = i
if i - start > longest:
longest = i - start
return longest | longest-substring-without-repeating-characters | Python3 Hashmap easy solution | faster than 99.94% | Janetcxy | 5 | 607 | longest substring without repeating characters | 3 | 0.338 | Medium | 94 |
https://leetcode.com/problems/longest-substring-without-repeating-characters/discuss/2283305/Python-Sliding-Window-O(n)-beats-96.91-(Explanation) | class Solution(object):
def lengthOfLongestSubstring(self, s):
mostRecentIndexofChar = {}
longest = 0
firstGoodIndex = 0
for index in range(len(s)):
if firstGoodIndex > index:
continue
if s[index] in mostRecentIndexofChar:
firstGoodIndex = max(firstGoodIndex, mostRecentIndexofChar[s[index]])
longest = max(longest, index - firstGoodIndex + 1)
mostRecentIndexofChar[s[index]] = index + 1
return longest | longest-substring-without-repeating-characters | [Python] Sliding Window O(n) beats 96.91% (Explanation) | Derek_Shimoda | 4 | 356 | longest substring without repeating characters | 3 | 0.338 | Medium | 95 |
https://leetcode.com/problems/longest-substring-without-repeating-characters/discuss/2133403/Python3-WINDOW-with-SET-(-*).-Explained | class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
hset, start, ans = set(), 0, 0
for ch in s:
while ch in hset:
hset.remove(s[start])
start += 1
hset.add(ch)
ans = max(ans, len(hset))
return max(ans, len(hset)) | longest-substring-without-repeating-characters | ✔️ [Python3] WINDOW with SET (^-^*)/. Explained | artod | 4 | 153 | longest substring without repeating characters | 3 | 0.338 | Medium | 96 |
https://leetcode.com/problems/longest-substring-without-repeating-characters/discuss/1788064/Python3-oror-Strings-oror-98-Faster | class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
max_length = 0
non_rep_sub_str = ""
for i in s:
if i in non_rep_sub_str:
non_rep_sub_str = non_rep_sub_str.split(i)[1] + i
else:
non_rep_sub_str += i
max_length = max(max_length, len(non_rep_sub_str))
return max_length | longest-substring-without-repeating-characters | Python3 || Strings || 98% Faster | cherrysri1997 | 4 | 396 | longest substring without repeating characters | 3 | 0.338 | Medium | 97 |
https://leetcode.com/problems/longest-substring-without-repeating-characters/discuss/1621748/Python3-Sliding-Window-%2B-Hashmap-or-9-Lines-Short-or-O(n)-Time-and-Space | class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
maxSize = l = 0
window = {}
for r, char in enumerate(s):
l = window[char] + 1 if char in window and window[char] >= l else l
window[char] = r
maxSize = max(maxSize, r - l + 1)
return maxSize | longest-substring-without-repeating-characters | [Python3] Sliding Window + Hashmap | 9 Lines Short | O(n) Time & Space | PatrickOweijane | 4 | 701 | longest substring without repeating characters | 3 | 0.338 | Medium | 98 |
https://leetcode.com/problems/longest-substring-without-repeating-characters/discuss/1539793/Python-Runtime-52-ms-94%2B%2B-Faster-Solution | class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
key = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '!', ' ','0','1','2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '!', '"', '#', '$', '%', '&', "'", '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '<', '=', '>', '?', '@', '[', '\\', ']', '^', '_', '`', '{', '|', '}', '~']
value = True
counter = dict.fromkeys(key, value)
i = j = r = 0
while True:
try:
if counter.get(s[j]):
counter[s[j]] = False
j += 1
else:
counter[s[i]] = True
l = j - i
i += 1
if l > r:
r = l
except:
l = j - i
return l if l > r else r | longest-substring-without-repeating-characters | Python Runtime 52 ms 94%++ Faster Solution | aaffriya | 4 | 697 | longest substring without repeating characters | 3 | 0.338 | Medium | 99 |
End of preview. Expand
in Dataset Viewer.
YAML Metadata
Warning:
empty or missing yaml metadata in repo card
(https://huggingface.co/docs/hub/datasets-cards)
- Downloads last month
- 8