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/maximum-average-subarray-i/discuss/1041268/Python-One-liner-and-Two-liner-that-both-time-out. | class Solution:
def findMaxAverage(self, nums: List[int], k: int) -> float:
if len(nums) <= k:
return sum(nums)/len(nums)
# allsubarrs = [nums[i:i+k] for i in range(len(nums)) if len(nums[i:i+k]) == k]
# allavgs = list(map(lambda x: sum(x)/len(x),allsubarrs))
allsubarrs = [sum(nums[i:i+k]) for i in range(len(nums)) if len(nums[i:i+k]) == k]
return max(allsubarrs)/k | maximum-average-subarray-i | Python One-liner and Two-liner that both time out. | mehrotrasan16 | 0 | 73 | maximum average subarray i | 643 | 0.438 | Easy | 10,700 |
https://leetcode.com/problems/maximum-average-subarray-i/discuss/664179/Better-than-90-python | class Solution:
def findMaxAverage(self, nums: List[int], k: int) -> float:
avg = max_avg = sum(nums[0:0+k]) / k
first_val = 0
for i in range(0+k,len(nums)):
avg = (avg*k + nums[i] - nums[first_val])/k
first_val +=1
if avg > max_avg:
max_avg = avg
return max_avg | maximum-average-subarray-i | Better than 90% python | soham9 | 0 | 70 | maximum average subarray i | 643 | 0.438 | Easy | 10,701 |
https://leetcode.com/problems/maximum-average-subarray-i/discuss/455360/Python3-super-simple-solution-with-comments-faster-than-99.67 | class Solution:
def findMaxAverage(self, nums: List[int], k: int) -> float:
s = sum(nums[:k]) # sum of first k elements
temp = s
for i in range(k,len(nums)):
s += nums[i] - nums[i-k] # add the next element and subtract the i-k element
if temp < s:
temp = s
return temp/k | maximum-average-subarray-i | Python3 super simple solution with comments, faster than 99.67% | jb07 | 0 | 116 | maximum average subarray i | 643 | 0.438 | Easy | 10,702 |
https://leetcode.com/problems/maximum-average-subarray-i/discuss/401819/Python-Floating-window | class Solution:
def findMaxAverage(self, nums: List[int], k: int) -> float:
if len(nums)==1:
return nums[0]
currsum = sum(nums[:k])
maxsum = currsum
for i in range(1,(len(nums)-k+1)):
currsum += (nums[i+k-1] - nums[i-1])
if currsum>maxsum:
maxsum = currsum
return maxsum/k | maximum-average-subarray-i | Python Floating window | saffi | 0 | 163 | maximum average subarray i | 643 | 0.438 | Easy | 10,703 |
https://leetcode.com/problems/maximum-average-subarray-i/discuss/1818300/Python-easy-to-read-and-understand | class Solution:
def findMaxAverage(self, nums: List[int], k: int) -> float:
sums, ans = 0, float("-inf")
i = 0
for j in range(len(nums)):
sums += nums[j]
if j-i+1 == k:
ans = max(ans, sums)
sums -= nums[i]
i = i+1
return ans / k | maximum-average-subarray-i | Python easy to read and understand | sanial2001 | -1 | 102 | maximum average subarray i | 643 | 0.438 | Easy | 10,704 |
https://leetcode.com/problems/set-mismatch/discuss/2733971/Easy-Python-Solution | class Solution:
def findErrorNums(self, nums: List[int]) -> List[int]:
c=Counter(nums)
l=[0,0]
for i in range(1,len(nums)+1):
if c[i]==2:
l[0]=i
if c[i]==0:
l[1]=i
return l | set-mismatch | Easy Python Solution | Vistrit | 14 | 966 | set mismatch | 645 | 0.43 | Easy | 10,705 |
https://leetcode.com/problems/set-mismatch/discuss/1351092/Python-Faster-than-90 | class Solution:
def findErrorNums(self, nums: List[int]) -> List[int]:
n = len(nums)
true_sum = n*(n+1)//2
actual_sum = sum(nums)
set_sum = sum(set(nums))
return [actual_sum - set_sum, true_sum - set_sum] | set-mismatch | Python - Faster than 90% | _Mansiii_ | 8 | 608 | set mismatch | 645 | 0.43 | Easy | 10,706 |
https://leetcode.com/problems/set-mismatch/discuss/2538868/Python-Solution-or-Simple-Logic-or-Math-Based | class Solution:
def findErrorNums(self, nums: List[int]) -> List[int]:
toRemove = sum(nums) - sum(set(nums))
actualMissing = sum(range(1, len(nums)+1)) - sum(set(nums))
return [toRemove, actualMissing] | set-mismatch | Python Solution | Simple Logic | Math Based | Gautam_ProMax | 5 | 276 | set mismatch | 645 | 0.43 | Easy | 10,707 |
https://leetcode.com/problems/set-mismatch/discuss/1089519/Python.-faster-than-99.50-O(n)-time.-3-lines.-Explain.-math.-Super-simple. | class Solution:
def findErrorNums(self, nums: List[int]) -> List[int]:
l, s = len(nums), sum(set(nums))
l = l * ( 1 + l ) // 2
return [sum(nums) - s, l - s] | set-mismatch | Python. faster than 99.50% O(n) time. 3-lines. Explain. math. Super simple. | m-d-f | 5 | 469 | set mismatch | 645 | 0.43 | Easy | 10,708 |
https://leetcode.com/problems/set-mismatch/discuss/1089732/Python.-O(1)-space.-O(n)-time.-Tricky.-Super-simple | class Solution(object):
def findErrorNums(self, nums):
l, dup, mis = len(nums), 0, 0
for num in nums:
if nums[abs(num) - 1] < 0 :
dup = abs(num)
else: nums[abs(num) - 1] *= -1
for index in range(l):
if nums[index] > 0:
mis = index + 1
break
return [dup, mis] | set-mismatch | Python. O(1) space. O(n) time. Tricky. Super-simple | m-d-f | 3 | 412 | set mismatch | 645 | 0.43 | Easy | 10,709 |
https://leetcode.com/problems/set-mismatch/discuss/2736246/PYTHON-oror-One-Liner | class Solution:
def findErrorNums(self, nums: List[int]) -> List[int]:
return [sum(nums)-sum(set(nums)), list(set([x for x in range(1, len(nums)+1)])-set(nums))[0]] | set-mismatch | PYTHON || One Liner | SuganthSugi | 2 | 76 | set mismatch | 645 | 0.43 | Easy | 10,710 |
https://leetcode.com/problems/set-mismatch/discuss/1937231/Python-Clean-and-Simple! | class Solution:
def findErrorNums(self, nums):
missing, normal, duplicate = set(range(1,len(nums)+1)), set(), set()
for num in nums:
if num in missing:
missing.remove(num)
normal.add(num)
elif num in normal:
normal.remove(num)
duplicate.add(num)
return [duplicate.pop(), missing.pop()] | set-mismatch | Python - Clean and Simple! | domthedeveloper | 2 | 207 | set mismatch | 645 | 0.43 | Easy | 10,711 |
https://leetcode.com/problems/set-mismatch/discuss/1937231/Python-Clean-and-Simple! | class Solution:
def findErrorNums(self, nums):
duplicate, missing = None, None
for num in nums:
visited = nums[abs(num)-1] < 0
if not visited: nums[abs(num)-1] *= -1
else: duplicate = abs(num)
for i,num in enumerate(nums):
visited = nums[i] < 0
if not visited: missing = i+1; break
return [duplicate, missing] | set-mismatch | Python - Clean and Simple! | domthedeveloper | 2 | 207 | set mismatch | 645 | 0.43 | Easy | 10,712 |
https://leetcode.com/problems/set-mismatch/discuss/1136162/Mathematical-approach-for-solving-without-using-loops-98-faster-and-understandable | class Solution:
def findErrorNums(self, nums: List[int]) -> List[int]:
n = len(nums)
sumoftotal = n*(n+1)/2
res = []
numsset = set(nums)
res.append(sum(nums) - sum(list(numsset)))
res.append(int(sumoftotal - sum(list(numsset))))
return res | set-mismatch | Mathematical approach for solving without using loops 98% faster and understandable | vashisht7 | 2 | 169 | set mismatch | 645 | 0.43 | Easy | 10,713 |
https://leetcode.com/problems/set-mismatch/discuss/1089634/Set-MismatchPython-Using-Counter() | class Solution:
def findErrorNums(self, nums: List[int]) -> List[int]:
d = collections.Counter(nums)
ans = 2*[0]
for i in range(1,len(nums)+1):
if d[i]>1:
ans[0] = i
if i not in d.keys():
ans[1] = i
return ans | set-mismatch | [Set Mismatch][Python] Using Counter() | sahilnishad | 2 | 138 | set mismatch | 645 | 0.43 | Easy | 10,714 |
https://leetcode.com/problems/set-mismatch/discuss/2734684/Python-97.8-Runtime-with-explanation | class Solution:
def findErrorNums(self, nums: List[int]) -> List[int]:
# Actual list -> [1,2,3,4], Duplicated from Actual list but with errors -> [1,2,2,4].
# 2 is the error and you can see 3 is supposed to be there
# sum of Duplicated list with errors [1+2+2+4] is 10, sum set which will only add unique numbers [1+2+4] ->
# To find the error which was 2, you can just find the difference between both sums.
duplicate = sum(nums)-sum(set(nums))
n = len(nums)
# Since you have len of the list with errors, you can find the sum of the original list with no errors
# With the formula of sum of first n natural numbers, N*(N+1)/2.
# To find the missing 3 -> Error (2) + Sum of Actual List - Sum of List with Errors
missing = duplicate + ((n*(n+1))//2) - sum(nums)
return duplicate, missing | set-mismatch | Python 97.8% Runtime with explanation | zooxdata | 1 | 54 | set mismatch | 645 | 0.43 | Easy | 10,715 |
https://leetcode.com/problems/set-mismatch/discuss/2734102/Python's-2-Simple-and-Easy-Way-to-Solve-or-99-Faster | class Solution:
def findErrorNums(self, nums: List[int]) -> List[int]:
counts = Counter(nums)
op = [0,0]
for i in range(1, len(nums)+1):
if counts[i]==2:
op[0]=i
if counts[i]==0:
op[1]=i
return op | set-mismatch | ✔️ Python's 2 Simple and Easy Way to Solve | 99% Faster 🔥 | pniraj657 | 1 | 92 | set mismatch | 645 | 0.43 | Easy | 10,716 |
https://leetcode.com/problems/set-mismatch/discuss/2734102/Python's-2-Simple-and-Easy-Way-to-Solve-or-99-Faster | class Solution:
def findErrorNums(self, nums: List[int]) -> List[int]:
length = len(nums)
total_sum = sum(nums)
set_sum = sum(set(nums))
total_n_sum = length*(length+1)//2
return [total_sum - set_sum, total_n_sum - set_sum] | set-mismatch | ✔️ Python's 2 Simple and Easy Way to Solve | 99% Faster 🔥 | pniraj657 | 1 | 92 | set mismatch | 645 | 0.43 | Easy | 10,717 |
https://leetcode.com/problems/set-mismatch/discuss/2264154/Python3-CyclicSortoror-O(n)-oror-O(1)-Runtime%3A-236ms-79.68-oror-Memory%3A-15.3mb-93.57 | class Solution:
# O(n) || O(1)
# Runtime: 236ms 79.68% || Memory: 15.3mb 93.57%
def findErrorNums(self, nums: List[int]) -> List[int]:
if not nums:
return nums
def cyclicSort(array):
i = 0
while i < len(array):
check = array[i] - 1
if array[i] != array[check]:
array[i], array[check] = array[check], array[i]
else:
i += 1
cyclicSort(nums)
result = []
for i in range(len(nums)):
if i + 1 != nums[i]:
result += [nums[i], i + 1]
return result | set-mismatch | Python3 CyclicSort|| O(n) || O(1)# Runtime: 236ms 79.68% || Memory: 15.3mb 93.57% | arshergon | 1 | 62 | set mismatch | 645 | 0.43 | Easy | 10,718 |
https://leetcode.com/problems/set-mismatch/discuss/1787794/Pytohn3-accepted-one-liner-solution | class Solution:
def findErrorNums(self, nums: List[int]) -> List[int]:
return [sum(nums) - sum(set(nums))] + [sum([i for i in range(1,len(nums)+1)]) - sum(set(nums))] | set-mismatch | Pytohn3 accepted one-liner solution | sreeleetcode19 | 1 | 94 | set mismatch | 645 | 0.43 | Easy | 10,719 |
https://leetcode.com/problems/set-mismatch/discuss/1708997/Easy-Cyclic-Sort-Solution | class Solution:
def findErrorNums(self, nums: List[int]) -> List[int]:
i =0
res = []
while i<len(nums):
correct = nums[i]-1
if nums[i] != nums[correct]:
nums[i],nums[correct] = nums[correct],nums[i]
else:
i+=1
for i in range(len(nums)):
if i != nums[i]-1:
res.append(nums[i])
res.append(i+1)
return res | set-mismatch | Easy Cyclic Sort Solution | mdsimar | 1 | 67 | set mismatch | 645 | 0.43 | Easy | 10,720 |
https://leetcode.com/problems/set-mismatch/discuss/1307030/Python-dollarolution | class Solution:
def findErrorNums(self, nums: List[int]) -> List[int]:
d = {}
for i in range(len(nums)):
d[i+1] = 0
for i in nums:
d[i] += 1
for i in d:
if d[i] == 2:
x = i
elif d[i] == 0:
y = i
return ([x,y]) | set-mismatch | Python $olution | AakRay | 1 | 176 | set mismatch | 645 | 0.43 | Easy | 10,721 |
https://leetcode.com/problems/set-mismatch/discuss/357389/Python3-O(N)-time-and-O(1)-extra-space | class Solution:
def findErrorNums(self, nums: List[int]) -> List[int]:
for x in nums:
x = abs(x)
if nums[x-1] < 0: dup = x
nums[x-1] *= -1
missing = next(i for i, x in enumerate(nums, 1) if x > 0 and i != dup)
return [dup, missing] | set-mismatch | [Python3] O(N) time & O(1) extra space | ye15 | 1 | 136 | set mismatch | 645 | 0.43 | Easy | 10,722 |
https://leetcode.com/problems/set-mismatch/discuss/357389/Python3-O(N)-time-and-O(1)-extra-space | class Solution:
def findErrorNums(self, nums: List[int]) -> List[int]:
nums.sort()
for i in range(1, len(nums)):
if nums[i-1] == nums[i]: dup = nums[i]
miss = (lambda x: x*(x+1)//2)(len(nums)) - sum(nums) + dup
return [dup, miss] | set-mismatch | [Python3] O(N) time & O(1) extra space | ye15 | 1 | 136 | set mismatch | 645 | 0.43 | Easy | 10,723 |
https://leetcode.com/problems/set-mismatch/discuss/357389/Python3-O(N)-time-and-O(1)-extra-space | class Solution:
def findErrorNums(self, nums: List[int]) -> List[int]:
seen = set()
for x in nums:
if x in seen: dup = x
seen.add(x)
miss = (lambda x: x*(x+1)//2)(len(nums)) - sum(nums) + dup
return [dup, miss] | set-mismatch | [Python3] O(N) time & O(1) extra space | ye15 | 1 | 136 | set mismatch | 645 | 0.43 | Easy | 10,724 |
https://leetcode.com/problems/set-mismatch/discuss/357389/Python3-O(N)-time-and-O(1)-extra-space | class Solution:
def findErrorNums(self, nums: List[int]) -> List[int]:
freq = [0]*len(nums)
for x in nums: freq[x-1] += 1
ans = [0]*2
for i, x in enumerate(freq):
if x == 2: ans[0] = i+1
elif x == 0: ans[1] = i+1
return ans | set-mismatch | [Python3] O(N) time & O(1) extra space | ye15 | 1 | 136 | set mismatch | 645 | 0.43 | Easy | 10,725 |
https://leetcode.com/problems/set-mismatch/discuss/2839620/Python-or-LeetCode-or-645.-Set-Mismatch-(Easy) | class Solution:
def findErrorNums(self, nums: List[int]) -> List[int]:
set_ = set(nums)
map_ = {}
for i in range(len(nums)):
if i + 1 not in set_:
y = i + 1
if nums[i] in map_:
x = nums[i]
else:
map_[nums[i]] = 1
return [x, y] | set-mismatch | Python | LeetCode | 645. Set Mismatch (Easy) | UzbekDasturchisiman | 0 | 3 | set mismatch | 645 | 0.43 | Easy | 10,726 |
https://leetcode.com/problems/set-mismatch/discuss/2839620/Python-or-LeetCode-or-645.-Set-Mismatch-(Easy) | class Solution:
def findErrorNums(self, nums: List[int]) -> List[int]:
nums.sort()
m = True
b = True
for i in range(len(nums)):
if i + 1 != nums[i] and m == True:
y = i + 1
m = False
if i == len(nums) - 1:
pass
elif nums[i] == nums[i + 1] and b == True:
x = nums[i]
del nums[i]
nums.append(None)
b = False
else:
pass
return [x, y] | set-mismatch | Python | LeetCode | 645. Set Mismatch (Easy) | UzbekDasturchisiman | 0 | 3 | set mismatch | 645 | 0.43 | Easy | 10,727 |
https://leetcode.com/problems/set-mismatch/discuss/2839620/Python-or-LeetCode-or-645.-Set-Mismatch-(Easy) | class Solution:
def findErrorNums(self, nums: List[int]) -> List[int]:
n = len(nums)
true_sum = n*(n+1)//2
actual_sum = sum(nums)
set_sum = sum(set(nums))
return [actual_sum - set_sum, true_sum - set_sum] | set-mismatch | Python | LeetCode | 645. Set Mismatch (Easy) | UzbekDasturchisiman | 0 | 3 | set mismatch | 645 | 0.43 | Easy | 10,728 |
https://leetcode.com/problems/set-mismatch/discuss/2765451/Easy-Index-Sorting | class Solution:
def findErrorNums(self, nums: List[int]) -> List[int]:
ans = []
nums.insert(0, 0)
i = 0
while i < len(nums):
while i < len(nums) and nums[i] != i and nums[nums[i]] != nums[i]:
tmp = nums[i]
nums[i], nums[tmp] = nums[tmp], nums[i]
i += 1
i = 0
while i < len(nums):
if nums[i] != i:
ans.append(nums[i])
ans.append(i)
break
i += 1
return ans | set-mismatch | Easy Index Sorting | greybear | 0 | 2 | set mismatch | 645 | 0.43 | Easy | 10,729 |
https://leetcode.com/problems/set-mismatch/discuss/2759806/Not-worst-solution-but-i-dont-like-it-(its-too-big) | class Solution:
def findErrorNums(self, nums: List[int]) -> List[int]:
nums_dict = {i: 0 for i in range(1, len(nums)+1)}
duplicated_num = None
lost_num = None
for idx, num in enumerate(nums, start=1):
if idx != num:
nums_dict[num] += 1
else:
nums_dict[idx] += 1
for num, count in nums_dict.items():
if count == 0:
lost_num = num
elif count == 2:
duplicated_num = num
return [duplicated_num, lost_num] | set-mismatch | Not worst solution but i dont like it (its too big) | Mixalaus | 0 | 1 | set mismatch | 645 | 0.43 | Easy | 10,730 |
https://leetcode.com/problems/set-mismatch/discuss/2737318/Python-Simple-O(n)-solution-beats-94 | class Solution:
def findErrorNums(self, nums: List[int]) -> List[int]:
freqs = {}
res = [-1, -1]
for num in nums:
freqs[num] = freqs.get(num, 0) + 1
if freqs[num] == 2:
res[0] = num
for num in range(1, len(nums) + 1):
if num not in freqs:
res[1] = num
return res | set-mismatch | Python, Simple O(n) solution, beats 94% | hfryling | 0 | 5 | set mismatch | 645 | 0.43 | Easy | 10,731 |
https://leetcode.com/problems/set-mismatch/discuss/2737046/One-line-lazyperson-solution-in-Python | class Solution:
def findErrorNums(self, nums: List[int]) -> List[int]:
return Counter(nums).most_common()[0][0], len(nums) * (1 + len(nums)) // 2 - sum(set(nums)) | set-mismatch | One line lazyperson solution in Python | metaphysicalist | 0 | 8 | set mismatch | 645 | 0.43 | Easy | 10,732 |
https://leetcode.com/problems/set-mismatch/discuss/2737024/Easy-Python-solution-O(n) | class Solution:
def findErrorNums(self, nums: List[int]) -> List[int]:
from collections import Counter
cc = Counter(nums)
most = cc.most_common(1)
for i in range(1,len(nums)+1):
if(cc[i] == 0):
return [most[0][0],i] | set-mismatch | Easy Python solution O(n) | adangert | 0 | 7 | set mismatch | 645 | 0.43 | Easy | 10,733 |
https://leetcode.com/problems/set-mismatch/discuss/2736730/Simple-Python-Solution-or-Hashmap | class Solution:
def findErrorNums(self, nums: List[int]) -> List[int]:
n=len(nums)
count=Counter(nums)
ans=[0,0]
for i in range(1, n+1):
if i not in count:
ans[-1]=i
continue
if count[i]==2:
ans[0]=i
return ans | set-mismatch | Simple Python Solution | Hashmap | Siddharth_singh | 0 | 6 | set mismatch | 645 | 0.43 | Easy | 10,734 |
https://leetcode.com/problems/set-mismatch/discuss/2736400/python-dictionary-96 | class Solution:
def findErrorNums(self, nums: List[int]) -> List[int]:
"""
:type nums: List[int]
:rtype: List[int]
"""
di = {}
double = None
missing = None
for x in nums:
if x not in di:
di[x] = 1
else:
di[x] += 1
if di[x] > 1:
double = x
for x in range(1,len(nums)+1):
if di.get(x) == None:
missing = x
break
return [double,missing] | set-mismatch | python, dictionary, 96% | m-s-dwh-bi | 0 | 5 | set mismatch | 645 | 0.43 | Easy | 10,735 |
https://leetcode.com/problems/set-mismatch/discuss/2736393/Cyclic-Sort-approach-that-beats-84-solutions-in-time-complexity-and-96-in-space-complexity | class Solution:
def findErrorNums(self, nums: List[int]) -> List[int]:
N = len(nums)
i = 0
while i < N:
correct_index = nums[i] - 1
if nums[i] != nums[correct_index]:
next = nums[i]
nums[i] = nums[correct_index]
nums[correct_index] = next
else:
i += 1
for i in range(N):
if nums[i] != i + 1:
return [nums[i], i+1] | set-mismatch | Cyclic Sort approach that beats 84% solutions in time complexity and 96% in space complexity | psyduck69 | 0 | 4 | set mismatch | 645 | 0.43 | Easy | 10,736 |
https://leetcode.com/problems/set-mismatch/discuss/2736172/Python-or-Mathematical-solution-explained-or-Faster-than-98 | class Solution:
def findErrorNums(self, nums: List[int]) -> List[int]:
diff = squared_diff = 0
for i, num in enumerate(nums, 1):
diff += i - num
squared_diff += i * i - num * num
sum_ = squared_diff // diff
return [(sum_ - diff) // 2, (sum_ + diff) // 2] | set-mismatch | Python | Mathematical solution explained | Faster than 98% | ahmadheshamzaki | 0 | 10 | set mismatch | 645 | 0.43 | Easy | 10,737 |
https://leetcode.com/problems/set-mismatch/discuss/2736145/Python-One-Liner-Easy-and-Simple-Solution | class Solution:
def findErrorNums(self, n: List[int]) -> List[int]:
return [mode(n), list(set([i for i in range(1,len(n)+1) ]) - set(n))[0]] | set-mismatch | Python One Liner Easy & Simple Solution | SouravSingh49 | 0 | 12 | set mismatch | 645 | 0.43 | Easy | 10,738 |
https://leetcode.com/problems/set-mismatch/discuss/2736143/Cycle-Sort-in-Python | class Solution:
# Cycle Sort
def findErrorNums(self, nums: List[int]) -> List[int]:
i = 0
while i < len(nums):
while nums[i] != i + 1:
print(nums[i], i)
if nums[nums[i] - 1] == nums[i]: break
nums[nums[i] - 1], nums[i] = nums[i], nums[nums[i] - 1]
i += 1
for i in range(len(nums)):
if nums[i] != i + 1:
return (nums[i], i + 1) | set-mismatch | Cycle Sort in Python | shiv-codes | 0 | 6 | set mismatch | 645 | 0.43 | Easy | 10,739 |
https://leetcode.com/problems/set-mismatch/discuss/2736075/Space-Efficient-(-Memory-Usage%3A-15.4-MB-less-than-84.98-of-Python3) | class Solution:
def findErrorNums(self, nums: List[int]) -> List[int]:
n=len(nums)
x=[w for w in range(1,n+1)]
for i in range(n):
if nums[i] in x:
x.remove(nums[i])
else:
y=nums[i]
continue
return [y,x[0]] | set-mismatch | Space Efficient ( Memory Usage: 15.4 MB, less than 84.98% of Python3) | DG-Problemsolver | 0 | 2 | set mismatch | 645 | 0.43 | Easy | 10,740 |
https://leetcode.com/problems/set-mismatch/discuss/2736061/Bitmap | class Solution:
def findErrorNums(self, nums: List[int]) -> List[int]:
n = len(nums)
value = 2 ** (n) - 1
expectd_sum = (1 + n) * n / 2
current_sum = 0
for i, num in enumerate(nums):
value = value ^ (1 << (num - 1))
current_sum += num
print(f'{value:b}')
result = []
for i in range(len(nums)):
if value % 2 == 1:
result.append(i + 1)
value >>= 1
return result if expectd_sum > current_sum else result[::-1] | set-mismatch | Bitmap | aibulatov | 0 | 2 | set mismatch | 645 | 0.43 | Easy | 10,741 |
https://leetcode.com/problems/set-mismatch/discuss/2736045/Python-easy | class Solution:
def findErrorNums(self, nums: List[int]) -> List[int]:
l = len(nums)
li = [0 for i in range(l)]
for i in nums:
li[i-1] += 1
o = [li.index(2)+1,li.index(0)+1]
return o | set-mismatch | Python easy | Pradyumankannan | 0 | 7 | set mismatch | 645 | 0.43 | Easy | 10,742 |
https://leetcode.com/problems/set-mismatch/discuss/2735775/Simple-solution.-One-for-loop-seems-to-be-the-optimal-memory-solution.-Beats-95-memory. | class Solution:
def findErrorNums(self, nums: List[int]) -> List[int]:
nums = sorted(nums)
missing = 0
doubled = 0
prev = 0
for num in nums:
# print(f'{prev = }, curr = {num}')
if num != prev + 1 and num != prev:
missing = prev + 1
# print(f'{missing = }')
elif num == prev:
doubled = num
# print(f'{doubled = }')
prev = num
if missing == 0:
missing = len(nums)
return [doubled, missing] | set-mismatch | Simple solution. One for loop, seems to be the optimal memory solution. Beats 95 % memory. | HappyPotatoman | 0 | 5 | set mismatch | 645 | 0.43 | Easy | 10,743 |
https://leetcode.com/problems/set-mismatch/discuss/2735710/Python-or-Simple-set-solution | class Solution:
def findErrorNums(self, nums: List[int]) -> List[int]:
repeat = None
ran = set(range(1, len(nums) + 1))
for num in nums:
try:
ran.remove(num)
except:
repeat = num
return [repeat, ran.pop()] | set-mismatch | Python | Simple set solution | LordVader1 | 0 | 10 | set mismatch | 645 | 0.43 | Easy | 10,744 |
https://leetcode.com/problems/set-mismatch/discuss/2735669/Easy-to-Understand%3A-Python-Counter | class Solution:
def findErrorNums(self, nums: List[int]) -> List[int]:
correct = Counter(list(range(1, len(nums) + 1)))
all_count = Counter(nums) + correct
most_common = all_count.most_common()
return [most_common[0][0], most_common[-1][0]] | set-mismatch | Easy to Understand: Python Counter | rscoates | 0 | 2 | set mismatch | 645 | 0.43 | Easy | 10,745 |
https://leetcode.com/problems/set-mismatch/discuss/2735418/Python-3-Explanations-in-comment | class Solution:
def findErrorNums(self, nums: List[int]) -> List[int]:
"""
:type nums: List[int]
:rtype: List[int]
"""
n = len(nums)
# 1 + 2 + ... + n 理想 ideal
ideal = n*(n+1)//2
# 實際有重複
actual = sum(nums)
# 去掉重複
no_duplicate = sum(set(nums))
miss = ideal - no_duplicate
duplicate = actual - no_duplicate
return [duplicate, miss] | set-mismatch | [Python 3] Explanations in comment | yousenwang001 | 0 | 6 | set mismatch | 645 | 0.43 | Easy | 10,746 |
https://leetcode.com/problems/set-mismatch/discuss/2735413/i-just-love-python-3-O(n)-O(n) | class Solution:
def findErrorNums(self, nums: List[int]) -> List[int]:
counter = Counter(nums)
ret = []
ret.append(counter.most_common()[0][0])
ret.append(next(iter(set(range(1,len(nums)+1)) - counter.keys())))
return ret | set-mismatch | i just love python 3 O(n) O(n) | 1ncu804u | 0 | 4 | set mismatch | 645 | 0.43 | Easy | 10,747 |
https://leetcode.com/problems/set-mismatch/discuss/2735304/Python-(Faster-than-90)-or-HashMap | class Solution:
def findErrorNums(self, nums: List[int]) -> List[int]:
numCount = {}
res = [0, 0]
for i in range(len(nums)):
numCount[nums[i]] = numCount.get(nums[i], 0) + 1
for n in range(1, len(nums) + 1):
if numCount.get(n):
if numCount[n] == 2:
res[0] = n
else:
res[1] = n
return res | set-mismatch | Python (Faster than 90%) | HashMap | KevinJM17 | 0 | 7 | set mismatch | 645 | 0.43 | Easy | 10,748 |
https://leetcode.com/problems/set-mismatch/discuss/2735079/Python | class Solution:
def findErrorNums(self, nums: List[int]) -> List[int]:
nums = sorted(nums)
duplicate = -1
deleted = -1
for i in range(len(nums) - 1):
if nums[i] == nums[i+1]:
duplicate = nums[i]
elif nums[i+1] - nums[i] > 1:
deleted = nums[i] + 1
if deleted == -1:
if nums[0] != 1:
deleted = 1
else:
deleted = nums[-1] + 1
return [duplicate,deleted] | set-mismatch | Python | anandanshul001 | 0 | 8 | set mismatch | 645 | 0.43 | Easy | 10,749 |
https://leetcode.com/problems/set-mismatch/discuss/2735048/Simple-solution-using-9th-class-Maths-Formulae-in-Python | class Solution:
def findErrorNums(self, nums: List[int]) -> List[int]:
sizeOfNums, sumOfAllNums, sumOfUniqueNums = len(nums), sum(nums), sum(set(nums))
s = sizeOfNums*(sizeOfNums+1)//2
return [sumOfAllNums-sumOfUniqueNums, s-sumOfUniqueNums]
# --------------- Solution Explaination -----------
# It represents the sum of n natural numbers from 1 to n,
# in the given question array originally was a series of numbers from 1 to n
# so in order to find the missing number take the sum of the given array and one without the duplicate
# Ex: Given array, [1,2,2,3,5] -> Sum = 13 (Let, sumOfAllNums)
# [1,2,3,5] -> Sum = 11 (Let, sumOfUniqueNums)
# Original series: [1,2,3,4,5] -> Sum = 15 (Let, s)
# n = 5, n*(n+1)/2 = 5*(6)/2 = 30/2 = 15
# {repeated_num, missing_num} => {sumOfAllNums-sumOfUniqueNums, s-sumOfUniqueNums} = {13-11, 15-11} = {2, 4} | set-mismatch | Simple solution using 9th class Maths Formulae in Python 😎 | mohitdubey1024 | 0 | 4 | set mismatch | 645 | 0.43 | Easy | 10,750 |
https://leetcode.com/problems/set-mismatch/discuss/2734969/Java-19-featurespythonc%2B%2B-2-LINES-or-100-or-0ms-or-O(n)-or-faster-or-simple | class Solution {
public int[] findErrorNums(int[] nums) {
var st = new HashSet<Integer>();
int dup = Arrays.stream(nums).boxed().filter(i -> !st.add(i)).toList().get(0), n = nums.length, s = (n * (n + 1)) / 2, ts = Arrays.stream(nums).sum();
return new int[]{dup, s - (ts - dup)};
}
}
python :
class Solution:
def findErrorNums(self, nums: list[int]) -> list[int]:
n, a, b = len(nums), sum(nums), sum(set(nums))
s = n*(n+1)//2
return [a-b, s-b]
C++:
vector<int> findErrorNums(vector<int>& nums) {
//sum of elements on nums
int initialSum = accumulate(nums.begin(), nums.end(), 0);
//put the element of nums into set to remove the duplicate number
set<int> s;
for(auto &i: nums){
s.insert(i);
}
//sum of elements of the set
int sum = accumulate(s.begin(), s.end(), 0);
//difference of initialSum and sum will give us the repeated number
int repeatedNum = initialSum - sum;
//sum of all the natural numbers from 1 to n
int n = nums.size() + 1;
//subtracting the sum of elements in set i.e. sum from the sum of the natural numbers will give us the missing number
int missingNum = n * (n-1)/2 - sum;
return {repeatedNum, missingNum};
} | set-mismatch | ⬆️✅🔥[Java 19 features/python/c++] 2 LINES | 100% | 0ms | O(n) | faster | simple 🔥🔥🔥 | ManojKumarPatnaik | 0 | 5 | set mismatch | 645 | 0.43 | Easy | 10,751 |
https://leetcode.com/problems/set-mismatch/discuss/2734929/Python-Solution-with-Explanation | class Solution:
def findErrorNums(self, nums: List[int]) -> List[int]:
c=Counter(nums)
l=[0,0]
for i in range(1,len(nums)+1):
if c[i]==2:
l[0]=i
if c[i]==0:
l[1]=i
return l | set-mismatch | Python Solution with Explanation | mritunjayyy | 0 | 3 | set mismatch | 645 | 0.43 | Easy | 10,752 |
https://leetcode.com/problems/set-mismatch/discuss/2734451/Easy-Python-Solution-or-100-Accepted | class Solution:
def findErrorNums(self, nums: List[int]) -> List[int]:
duplicate = 0
error = 0
n = len(nums)
nums = sorted(nums)
for i in range(len(nums)):
if nums[i-1] == nums[i]:
duplicate = nums[i]
break
nums = list(set(nums))
for j in range(1, n+1):
if j not in nums:
error = j
break
return [duplicate, error] | set-mismatch | Easy Python Solution | 100% Accepted | ShivangVora1206 | 0 | 5 | set mismatch | 645 | 0.43 | Easy | 10,753 |
https://leetcode.com/problems/set-mismatch/discuss/2734433/Python-O(n)-solution-Accepted | class Solution:
def findErrorNums(self, nums: List[int]) -> List[int]:
gt = range(1, len(nums) + 1)
hashset = set(nums)
return [sum(nums) - sum(hashset), sum(gt) - sum(hashset)] | set-mismatch | Python O(n) solution [Accepted] | lllchak | 0 | 3 | set mismatch | 645 | 0.43 | Easy | 10,754 |
https://leetcode.com/problems/set-mismatch/discuss/2734233/Python-or-Using-a-Set-or-Commented | class Solution:
def findErrorNums(self, nums: List[int]) -> List[int]:
candidates = set(range(1, len(nums)+1)) # This is the 'correct' set
for nbr in nums:
if nbr in candidates: # Remove what we have already seen
candidates.remove(nbr)
else: # If it's not in the set, we've already seen it so it's a repeat
repeat = nbr
return [repeat, candidates.pop()] # Whatever is left is what was never seen``` | set-mismatch | Python | Using a Set | Commented | bmcalderon | 0 | 6 | set mismatch | 645 | 0.43 | Easy | 10,755 |
https://leetcode.com/problems/set-mismatch/discuss/2734069/Python-or-Easy-Solution-or-Maps | class Solution:
def findErrorNums(self, nums: List[int]) -> List[int]:
total = len(nums)
maps = {i:0 for i in range(1, total+1)}
for i in nums:
if i in maps:
maps[i] += 1
ans = []
sorted_map = [k for k, v in sorted(maps.items(), key=lambda a:a[1], reverse=False)]
ans = [sorted_map[-1], sorted_map[0]]
return ans | set-mismatch | Python | Easy Solution | Maps | atharva77 | 0 | 2 | set mismatch | 645 | 0.43 | Easy | 10,756 |
https://leetcode.com/problems/set-mismatch/discuss/2733934/python-simple-solution-using-math | class Solution:
def findErrorNums(self, nums: List[int]) -> List[int]:
n=len(nums)
ap=n*(n+1)/2
miss=int(ap-sum(set(nums)))
dup=int(sum(nums)+miss-ap)
return [dup,miss] | set-mismatch | python simple solution using math | Raghunath_Reddy | 0 | 5 | set mismatch | 645 | 0.43 | Easy | 10,757 |
https://leetcode.com/problems/set-mismatch/discuss/2733839/Python-or-Easy-or-95.15-or-Explanation | class Solution:
def findErrorNums(self, nums: List[int]) -> List[int]:
total, n = 0, len(nums)
s = set()
for num in nums:
if num in s:
duplicate = num
s.add(num)
total += num
total -= duplicate
missing = (n * (n + 1)) // 2 - total
return [duplicate,missing] | set-mismatch | Python | Easy | 95.15% | Explanation | Ridikulus | 0 | 4 | set mismatch | 645 | 0.43 | Easy | 10,758 |
https://leetcode.com/problems/set-mismatch/discuss/2733828/Python3!-4-Lines-solution. | class Solution:
def findErrorNums(self, nums: List[int]) -> List[int]:
diff = sum(nums) - (len(nums) * (len(nums)+1) // 2) # diff = a - b
diff2 = sum([a*a for a in nums]) - sum([i*i for i in range(1, len(nums) + 1)]) # diff2 = a^2 - b^2
add = diff2 // diff # (a - b) (a + b) = a^2 - b^2
return (diff + add) // 2, (add - diff) // 2 | set-mismatch | Python3! 4 Lines solution. | aminjun | 0 | 10 | set mismatch | 645 | 0.43 | Easy | 10,759 |
https://leetcode.com/problems/set-mismatch/discuss/2733768/Python-boolean-array-to-keep-status.-Time%3A-O(N)-Space%3A-O(N) | class Solution:
def findErrorNums(self, nums: List[int]) -> List[int]:
a = [False] * len(nums)
result = []
for n in nums:
if a[n-1]:
result.append(n)
else:
a[n-1] = True
for i, found in enumerate(a):
if not found:
result.append(i + 1)
return result | set-mismatch | Python, boolean array to keep status. Time: O(N), Space: O(N) | blue_sky5 | 0 | 4 | set mismatch | 645 | 0.43 | Easy | 10,760 |
https://leetcode.com/problems/set-mismatch/discuss/2733767/Python-3-Solution | class Solution:
def findErrorNums(self, nums: List[int]) -> List[int]:
Z = set(nums)
n = len(nums)
k = n*(n+1)//2 - sum(Z)
l = sum(nums) + k - (n*(n+1)//2)
return [l,k] | set-mismatch | Python 3 Solution | mati44 | 0 | 6 | set mismatch | 645 | 0.43 | Easy | 10,761 |
https://leetcode.com/problems/set-mismatch/discuss/2707418/Python-1-liner | class Solution:
def findErrorNums(self, nums: List[int]) -> List[int]:
return [sum(nums) - sum(set(nums)), int(len(nums)*(len(nums)+1)/2 - sum(set(nums)))] | set-mismatch | Python 1 liner | code_snow | 0 | 9 | set mismatch | 645 | 0.43 | Easy | 10,762 |
https://leetcode.com/problems/set-mismatch/discuss/2705568/Easy-Python-Solution | class Solution:
def findErrorNums(self, nums: List[int]) -> List[int]:
a = Counter(nums)
Fsm = sum(nums)
Csm = (len(nums) * (len(nums)+1))//2
tp = a.most_common(1)
return [tp[0][0], Csm - (Fsm - tp[0][0])] | set-mismatch | Easy Python Solution | arifkhan1990 | 0 | 4 | set mismatch | 645 | 0.43 | Easy | 10,763 |
https://leetcode.com/problems/maximum-length-of-pair-chain/discuss/1564508/Fast-O(NlogN)-and-simple-Python-3-solution | class Solution:
def findLongestChain(self, pairs: List[List[int]]) -> int:
pairs.sort()
rt = 1
l = pairs[0]
for r in range(1,len(pairs)):
if l[1] < pairs[r][0]:
rt += 1
l = pairs[r]
elif pairs[r][1]<l[1]:
l = pairs[r]
return rt | maximum-length-of-pair-chain | Fast O(NlogN) and simple Python 3 solution | cyrille-k | 2 | 156 | maximum length of pair chain | 646 | 0.564 | Medium | 10,764 |
https://leetcode.com/problems/maximum-length-of-pair-chain/discuss/1505898/Python-or-O(n2)-or-Simple-DP | class Solution:
def findLongestChain(self, pairs: List[List[int]]) -> int:
pairs.sort()
dp=[1 for i in range(len(pairs))]
dp[0]=1
for i in range(1,len(pairs)):
for j in range(i-1,-1,-1):
if pairs[i][0]>pairs[j][1]:
dp[i]=max(dp[i],dp[j]+1)
return dp[len(pairs)-1] | maximum-length-of-pair-chain | Python | O(n^2) | Simple DP | meghanakolluri | 2 | 133 | maximum length of pair chain | 646 | 0.564 | Medium | 10,765 |
https://leetcode.com/problems/maximum-length-of-pair-chain/discuss/1420540/WEEB-DOES-PYTHON | class Solution:
def findLongestChain(self, pairs: List[List[int]]) -> int:
pairs = sorted(pairs)
arr = [1] * len(pairs)
for i in range(1,len(pairs)):
subprob = [arr[k] for k in range(i) if pairs[k][1] < pairs[i][0]]
arr[i] = max(subprob, default=0) + 1
return max(arr) | maximum-length-of-pair-chain | WEEB DOES PYTHON | Skywalker5423 | 2 | 79 | maximum length of pair chain | 646 | 0.564 | Medium | 10,766 |
https://leetcode.com/problems/maximum-length-of-pair-chain/discuss/2840537/Python-90%2B-efficient-solution-(both-greedy-and-dynamic-programming-approaches) | class Solution:
def findLongestChain(self, pairs: List[List[int]]) -> int:
pairs.sort()
prev_index = len(pairs) - 1
result = 1
for i in range(len(pairs) - 2, -1, -1):
if pairs[i][1] < pairs[prev_index][0]:
prev_index = i
result += 1
return result
pairs.sort()
dp = [1] * len(pairs)
for i in range(len(pairs) - 1, -1, -1):
for j in range(i + 1, len(pairs)):
if pairs[i][1] < pairs[j][0]:
dp[i] = max(dp[i], 1 + dp[j])
return max(dp) | maximum-length-of-pair-chain | Python 90%+ efficient solution (both greedy and dynamic programming approaches) | Bread0307 | 0 | 1 | maximum length of pair chain | 646 | 0.564 | Medium | 10,767 |
https://leetcode.com/problems/maximum-length-of-pair-chain/discuss/2832870/DP-Kadane-algorithm-%2B-Sort-python-easy-solution | class Solution:
def findLongestChain(self, pairs: List[List[int]]) -> int:
pairs.sort()
N = len(pairs)
dp = [1] * (N + 1)
dp[0] = 0
for i in range(1, len(dp)):
for j in range(i):
if pairs[j - 1][1] < pairs[i - 1][0]:
dp[i] = max(dp[i], dp[j] + 1)
return dp[-1] | maximum-length-of-pair-chain | DP Kadane algorithm + Sort / python easy solution | Lara_Craft | 0 | 2 | maximum length of pair chain | 646 | 0.564 | Medium | 10,768 |
https://leetcode.com/problems/maximum-length-of-pair-chain/discuss/2775698/This-problem-is-the-same-as-problem-435. | class Solution:
def findLongestChain(self, pairs: List[List[int]]) -> int:
pairs.sort(key=lambda x: x[1])
ans = len(pairs)
l, r = 0, 1
while l < len(pairs):
r = l + 1
while r < len(pairs) and pairs[l][1] >= pairs[r][0]:
ans -= 1
r += 1
l = r
return ans | maximum-length-of-pair-chain | This problem is the same as problem 435. | yiming999 | 0 | 2 | maximum length of pair chain | 646 | 0.564 | Medium | 10,769 |
https://leetcode.com/problems/maximum-length-of-pair-chain/discuss/2734590/Python-or-O(n-log-n)-solution | class Solution:
def findLongestChain(self, pairs: List[List[int]]) -> int:
n = len(pairs)
pairs.sort(key=lambda x : x[0])
length = 1
prev = pairs[0]
for i in range(1, n):
p = pairs[i]
l, r = p[0], p[1]
if l > prev[1]:
length += 1
prev = p
elif r < prev[1]:
prev = p
return length | maximum-length-of-pair-chain | Python | O(n log n) solution | on_danse_encore_on_rit_encore | 0 | 2 | maximum length of pair chain | 646 | 0.564 | Medium | 10,770 |
https://leetcode.com/problems/maximum-length-of-pair-chain/discuss/2443486/Python-Solution-or-Memoization-or-Tabulation-or-100 | class Solution:
def findLongestChain(self, pairs: List[List[int]]) -> int:
pairs.sort(key=lambda x:x[0])
n=len(pairs)
# Memoization
# dp=[[-1]*(n+1) for i in range(n+1)]
# # print(pairs)
# def helper(ind, prev_ind):
# if ind==n:
# return 0
# if dp[ind][prev_ind]!=-1:
# return dp[ind][prev_ind]
# notTake=helper(ind+1, prev_ind)
# take=0
# if prev_ind==-1 or pairs[ind][0]>pairs[prev_ind][1]:
# take=1+helper(ind+1, ind)
# dp[ind][prev_ind]=max(take, notTake)
# return dp[ind][prev_ind]
# return helper(0, -1)
# Tabulation
dp=[1]*n
maxi=1
for ind in range(1, n):
for prev_ind in range(ind):
if pairs[ind][0]>pairs[prev_ind][1] and dp[ind]<dp[prev_ind]+1:
dp[ind]=dp[prev_ind]+1
maxi=max(maxi, dp[ind])
return maxi | maximum-length-of-pair-chain | Python Solution | Memoization | Tabulation | 100% | Siddharth_singh | 0 | 33 | maximum length of pair chain | 646 | 0.564 | Medium | 10,771 |
https://leetcode.com/problems/maximum-length-of-pair-chain/discuss/2411957/Python3-or-Solved-Bottom-UP-DP-%2B-Tabulation-%2B-Greedy-Sorting | class Solution:
#Time-Complexity: O(nlogn + n) -> O(nlogn)
#Space-Complexity: O(n)
def findLongestChain(self, pairs: List[List[int]]) -> int:
#the reason why you need to sort the pairs is you want to build the longest
#chain while also keeping the distance between each and every pair part in chain
#minimal as possible -> Greedy aspect of this problem also shows!
#Basically, this way you are minimizing likelihood that for any given pair
#its positional range [Li, Ri] will overlap with the Left to Right boundary
#positional range of longest pair chain you are forming so far!
pairs.sort(key = lambda x: x[0])
n = len(pairs)
#Basically, for any given pair, you have 2 options: include or not include
#in longest possible chain!
#longest chain we can form when we consider all pairs starting from index i!
#Rec. Relation = longestChain[i] = max(1 + longestChain[i+1:], longestChain[i+1:])
#Either you can include ith pair in longest chain that can be formed using
#i+1th pair onwards or not include it! -> That will provide length of longest chain
#of all pairs starting from index i and onwards!
#Bottom-Up Approach: Basically, we only need a single state paramter i, which
#is the index position we consider all pairs starting from!
#for every state paramter i val, we consider length of longest pair chain
#we can form using all pairs starting from index i!
#since recursive top-down approach does so in inc. order of state paramter val,
#we will go opposite direction and solve subproblems by decreasing index position i!
#We'll use local variables to keep track of left and right boundary pos. values
#for current longest chain!
L, R = pairs[n-1][0], pairs[n-1][1]
#dp table will store for state paramters with index ranging from 0 to n-1 ->size n
dp = [0] * n
#add dp-base for last pair -> length of longest chain is 1 just using last pair!
dp[n-1] = 1
#now, solve the subproblems!
for i in range(n-2, -1, -1):
#for each pair i, consider if it can fit in current known longest chain
#we can form using all pairs starting from index i+1th pair!
#if current ith pair left pos. value > right boundary, it can be inserted
#as the new last piece of chain!
if(pairs[i][0] > R and pairs[i][1] > R):
dp[i] = 1 + dp[i+1]
#update the right boundary of chain!
R = pairs[i][1]
continue
#if current ith pair right pos. value < Left boundary, it can be inserted
#as new first piece of current longest built-up chain!
if(pairs[i][1] < L and pairs[i][0] < L):
dp[i] = 1 + dp[i+1]
L = pairs[i][0]
continue
#otherwise, length of longest chain considering from ith pair will be
#that of already solved subproblem: length of longest chain consdering
#all pairs starting from index position i+1!
dp[i] = dp[i+1]
#return answer!
return dp[0] | maximum-length-of-pair-chain | Python3 | Solved Bottom-UP DP + Tabulation + Greedy Sorting | JOON1234 | 0 | 15 | maximum length of pair chain | 646 | 0.564 | Medium | 10,772 |
https://leetcode.com/problems/maximum-length-of-pair-chain/discuss/2317403/Python3-Solution-with-using-dp | class Solution:
def findLongestChain(self, pairs: List[List[int]]) -> int:
pairs.sort(key=lambda x: x[1])
dp = [1] * len(pairs)
for idx in range(1, len(pairs)):
if pairs[idx - 1][1] >= pairs[idx][0]:
pairs[idx] = pairs[idx - 1]
dp[idx] = dp[idx - 1]
else:
dp[idx] += dp[idx - 1]
return dp[-1] | maximum-length-of-pair-chain | [Python3] Solution with using dp | maosipov11 | 0 | 26 | maximum length of pair chain | 646 | 0.564 | Medium | 10,773 |
https://leetcode.com/problems/maximum-length-of-pair-chain/discuss/2287318/Python-Bottom-Up-DP | class Solution:
def findLongestChain(self, pairs: List[List[int]]) -> int:
pairs.sort(key = lambda x:x[0])
dp = [1 for _ in pairs]
for i in range(len(pairs)):
for j in range(0,i):
if pairs[i][0] > pairs[j][1] and dp[j]+1 > dp[i]:
dp[i] = 1+dp[j]
return max(dp) | maximum-length-of-pair-chain | Python Bottom Up DP | gurucharandandyala | 0 | 19 | maximum length of pair chain | 646 | 0.564 | Medium | 10,774 |
https://leetcode.com/problems/maximum-length-of-pair-chain/discuss/1546877/Python3-Heap-Solution | class Solution:
def findLongestChain(self, pairs: List[List[int]]) -> int:
# sort and find prev
pairs.sort()
dp = [1] * len(pairs)
heap = [] # (dp, start, end)
for i in range(len(pairs)):
# find the first max answer
tmp = []
while heap and pairs[i][0] <= heap[0][2]:
tmp.append(heapq.heappop(heap))
# if hit
if heap:
dp[i] = -heap[0][0] + 1
# push back to heap
while tmp:
heapq.heappush(heap, tmp.pop())
# push this element into heap
heapq.heappush(heap, (-dp[i], pairs[i][0], pairs[i][1]))
return dp[-1] | maximum-length-of-pair-chain | [Python3] Heap Solution | ShihChungYu | 0 | 36 | maximum length of pair chain | 646 | 0.564 | Medium | 10,775 |
https://leetcode.com/problems/maximum-length-of-pair-chain/discuss/1456247/Simple-Python-O(nlogn)-dynamic-programming-or-greedy-solutions | class Solution:
def findLongestChain(self, pairs: List[List[int]]) -> int:
pairs.sort()
dp = [1]*len(pairs)
for i in range(len(dp)):
for j in range(i):
if pairs[j][1] < pairs[i][0]:
dp[i] = max(dp[i], dp[j]+1)
return max(dp) | maximum-length-of-pair-chain | Simple Python O(nlogn) dynamic programming or greedy solutions | Charlesl0129 | 0 | 103 | maximum length of pair chain | 646 | 0.564 | Medium | 10,776 |
https://leetcode.com/problems/maximum-length-of-pair-chain/discuss/1456247/Simple-Python-O(nlogn)-dynamic-programming-or-greedy-solutions | class Solution:
def findLongestChain(self, pairs: List[List[int]]) -> int:
pairs.sort(key = lambda x: x[1])
ret = 1
prev_end = pairs[0][1]
for i in range(1, len(pairs)):
if pairs[i][0] > prev_end:
ret += 1
prev_end = pairs[i][1]
return ret | maximum-length-of-pair-chain | Simple Python O(nlogn) dynamic programming or greedy solutions | Charlesl0129 | 0 | 103 | maximum length of pair chain | 646 | 0.564 | Medium | 10,777 |
https://leetcode.com/problems/maximum-length-of-pair-chain/discuss/1391390/Python-or-Simple-solution | class Solution(object):
def findLongestChain(self, pairs):
"""
:type pairs: List[List[int]]
:rtype: int
"""
pairs.sort(key=lambda x:x[0])
pairs.sort(key=lambda x:x[1])
c=1
i=1
while i<len(pairs):
if pairs[i-1][1]<pairs[i][0]:
c+=1
i+=1
else:
pairs.pop(i)
return c | maximum-length-of-pair-chain | Python | Simple solution | nmk0462 | 0 | 63 | maximum length of pair chain | 646 | 0.564 | Medium | 10,778 |
https://leetcode.com/problems/maximum-length-of-pair-chain/discuss/1220373/Python3-Concise-Greedy | class Solution:
def findLongestChain(self, pairs: List[List[int]]) -> int:
ans, prev = 1, math.inf
for chain in sorted(pairs, key=lambda x : x[0]):
ans, prev = (ans + 1, chain[1]) if chain[0] > prev else (ans, min(prev, chain[1]))
return ans | maximum-length-of-pair-chain | Python3 - Concise Greedy | Bruception | 0 | 68 | maximum length of pair chain | 646 | 0.564 | Medium | 10,779 |
https://leetcode.com/problems/maximum-length-of-pair-chain/discuss/1208522/Simple-Dynamic-Programming-approach-in-python | class Solution:
def findLongestChain(self, pairs: List[List[int]]) -> int:
n=len(pairs)
dp=[1]*n
pairs=sorted(pairs,key=lambda k:k[0])
for i in range(1,n):
for j in range(0,i):
if pairs[i][0]>pairs[j][1] and dp[i]<dp[j]+1:
dp[i]=dp[j]+1
return max(dp) | maximum-length-of-pair-chain | Simple Dynamic Programming approach in python | samarthnehe | 0 | 66 | maximum length of pair chain | 646 | 0.564 | Medium | 10,780 |
https://leetcode.com/problems/palindromic-substrings/discuss/392119/Solution-in-Python-3-(beats-~94)-(six-lines)-(With-Detaiiled-Explanation) | class Solution:
def countSubstrings(self, s: str) -> int:
L, r = len(s), 0
for i in range(L):
for a,b in [(i,i),(i,i+1)]:
while a >= 0 and b < L and s[a] == s[b]: a -= 1; b += 1
r += (b-a)//2
return r
- Junaid Mansuri
(LeetCode ID)@hotmail.com | palindromic-substrings | Solution in Python 3 (beats ~94%) (six lines) (With Detaiiled Explanation) | junaidmansuri | 67 | 8,100 | palindromic substrings | 647 | 0.664 | Medium | 10,781 |
https://leetcode.com/problems/palindromic-substrings/discuss/2061497/Python-Easy-approach-Beats-~97 | class Solution:
def expandAndCountPallindromes(self, i, j, s):
'''Counts the number of pallindrome substrings from a given center i,j
1. when i=j, it's an odd-lengthed pallindrome string.
eg: for string "aba", i=j=1.
2. when i+1=j, it's an even-lengthed pallindrome string.
eg: for string "abba", i=1, j=2.
Parameters:
i,j - centers from which the code will expand to find number of pallindrome substrings.
s - the string in which the code needs to find the pallindrome substrings.
Returns:
cnt - The number of pallindrome substrings from the given center i,j
'''
length=len(s)
cnt=0
while 0<=i and j<length and s[i]==s[j]:
i-=1
j+=1
cnt+=1
return cnt
def countSubstrings(self, s: str) -> int:
return sum(self.expandAndCountPallindromes(i,i,s) + self.expandAndCountPallindromes(i,i+1,s) for i in range(len(s))) | palindromic-substrings | Python Easy approach Beats ~97% | constantine786 | 31 | 2,800 | palindromic substrings | 647 | 0.664 | Medium | 10,782 |
https://leetcode.com/problems/palindromic-substrings/discuss/403603/Straightforward-Python-Solution-O(1)-space-(no-tricky-arithmetic) | class Solution:
def countSubstrings(self, s: str) -> int:
def expand(left: int, right: int) -> int:
count = 0
while left >= 0 and right < len(s) and s[left] == s[right]:
# count the palindrome and expand outward
count += 1
left -= 1
right += 1
return count
palindromes = 0
for i in range(len(s)):
# the idea is to expand around the 'center' of the string, but the center could be 1 or 2 letters
# e.g., babab and cbbd, hence the (i, i) and (i, i + 1)
palindromes += expand(i, i)
palindromes += expand(i, i+ 1)
return palindromes | palindromic-substrings | Straightforward Python Solution O(1) space (no tricky arithmetic) | crippled_baby | 31 | 2,400 | palindromic substrings | 647 | 0.664 | Medium | 10,783 |
https://leetcode.com/problems/palindromic-substrings/discuss/2062005/Python-Simple-Python-Solution-Using-Two-Different-Approach | class Solution:
def countSubstrings(self, s: str) -> int:
result = 0
for i in range(len(s)):
for j in range(i,len(s)):
if s[i:j+1] == s[i:j+1][::-1]:
result = result +1
return result | palindromic-substrings | [ Python ] ✅✅ Simple Python Solution Using Two Different Approach ✌👍 | ASHOK_KUMAR_MEGHVANSHI | 7 | 464 | palindromic substrings | 647 | 0.664 | Medium | 10,784 |
https://leetcode.com/problems/palindromic-substrings/discuss/2062005/Python-Simple-Python-Solution-Using-Two-Different-Approach | class Solution:
def countSubstrings(self, s: str) -> int:
result = 0
length = len(s)
dp = [[False for _ in range(length)] for _ in range(length)]
for i in range(length-1,-1,-1):
dp[i][i] = True
result = result + 1
for j in range(i+1,length):
if j - i == 1 :
if s[i] == s[j]:
dp[i][j] = True
else:
dp[i][j] = False
else:
if s[i] == s[j] and dp[i+1][j-1] == True:
dp[i][j] = True
else:
dp[i][j] = False
if dp[i][j] == True:
result = result + 1
return result | palindromic-substrings | [ Python ] ✅✅ Simple Python Solution Using Two Different Approach ✌👍 | ASHOK_KUMAR_MEGHVANSHI | 7 | 464 | palindromic substrings | 647 | 0.664 | Medium | 10,785 |
https://leetcode.com/problems/palindromic-substrings/discuss/1034932/Python-or-Expand-from-Center-or-Easy! | class Solution:
def countSubstrings(self, s: str) -> int:
global result
result = 0
def expandFromCenter(i, j):
global result
while 0 <= i < len(s) and 0 <= j < len(s) and s[i] == s[j]:
result += 1
i -= 1
j += 1
for idx in range(len(s)):
expandFromCenter(idx, idx) # odd expansion
expandFromCenter(idx, idx+1) # even expansion
return result | palindromic-substrings | Python | Expand from Center | Easy! | dev-josh | 6 | 665 | palindromic substrings | 647 | 0.664 | Medium | 10,786 |
https://leetcode.com/problems/palindromic-substrings/discuss/1748039/Python3-DFS-solution-Follows-a-template | class Solution:
def countSubstrings(self, s: str) -> int:
@lru_cache(maxsize=None)
def dfs(start, end):
if s[start:end+1] == s[start:end+1][::-1]:
result.add((start, end))
# loop with one less character
if start < end:
dfs(start + 1, end)
dfs(start, end-1)
result = set()
dfs(0, len(s) - 1)
return len(result) | palindromic-substrings | Python3 DFS solution - Follows a template | GeneBelcher | 5 | 309 | palindromic substrings | 647 | 0.664 | Medium | 10,787 |
https://leetcode.com/problems/palindromic-substrings/discuss/1748039/Python3-DFS-solution-Follows-a-template | class Solution:
def mainFunction(self, s: str) -> int:
@lru_cache(maxsize=None)
def dfs(params):
# 1. End state to recursion; usually append to result or increment counter
# 2. Call back to the helper dfs function
# setup result variable
# call to dfs()
# return result | palindromic-substrings | Python3 DFS solution - Follows a template | GeneBelcher | 5 | 309 | palindromic substrings | 647 | 0.664 | Medium | 10,788 |
https://leetcode.com/problems/palindromic-substrings/discuss/2061746/python-easy-solution | class Solution:
def countSubstrings(self, s: str) -> int:
count = 0
def pal(s,l,r):
count = 0
while l>=0 and r<len(s) and s[l] == s[r]:
count +=1
l -=1
r +=1
return count
for i in range(len(s)):
count += pal(s,i,i) # for odd palindroms
count += pal(s,i,i+1) #for even palindroms
return count | palindromic-substrings | python easy solution | testbugsk | 4 | 555 | palindromic substrings | 647 | 0.664 | Medium | 10,789 |
https://leetcode.com/problems/palindromic-substrings/discuss/753494/Python3-Solution-with-a-Detailed-Explanation-Palindromic-Substrings | class Solution:
def countSubstrings(self, s: str) -> int:
count = 0
n = len(s)
if n == 0:
return 0
for i in range(n): #1
count += 1 #2
right = i + 1 #3
left = i - 1 #4
while right < n and s[right] == s[i]: #5
right+=1
count+=1
while right < n and left >= 0 and s[left] == s[right]: #6
count += 1
left -= 1
right += 1
return count | palindromic-substrings | Python3 Solution with a Detailed Explanation - Palindromic Substrings | peyman_np | 3 | 650 | palindromic substrings | 647 | 0.664 | Medium | 10,790 |
https://leetcode.com/problems/palindromic-substrings/discuss/1685870/Python-Short-and-Simple-Code-or-Time-and-Memory-Beats-100-or-Expansion-around-centre-approach | class Solution:
def countSubstrings(self, s: str) -> int:
n, ans = len(s), 0
def longest_palindrome_around_center(start, end):
num = 0 # Iteration counter
# Indices must be in range and palindrome property must satisfy
while start >= 0 and end < n and s[start] == s[end]:
start -= 1
end += 1
num += 1
# Number of times the iteration was run is the total number of palindromes that exists with the given center
return num
for i in range(n):
ans += longest_palindrome_around_center(i, i)+longest_palindrome_around_center(i, i+1)
# Two seperate calls made, one for even sized and one for odd sized palindromes with the given center
return ans | palindromic-substrings | Python Short and Simple Code | Time and Memory Beats 100% | Expansion around centre approach | anCoderr | 2 | 153 | palindromic substrings | 647 | 0.664 | Medium | 10,791 |
https://leetcode.com/problems/palindromic-substrings/discuss/1273173/Faster-than-97.08-of-python-online-solution-or-palindromic-substring | class Solution:
def countSubstrings(self, s: str) -> int:
if len(s)==0:
return 0
n=len(s)
res=0
c=list(s)
def ispalindrome(s,e,c):
count=0
while(s>=0 and e<n and c[s]==c[e]):
s-=1
e+=1
count+=1
return count
for i in range(n):
res+=ispalindrome(i,i,c)
res+=ispalindrome(i,i+1,c)
return res | palindromic-substrings | Faster than 97.08% of python online solution | palindromic substring | lalith_kumaran | 2 | 352 | palindromic substrings | 647 | 0.664 | Medium | 10,792 |
https://leetcode.com/problems/palindromic-substrings/discuss/2629025/Python-Brute-Force-%2B-hashmap-solution. | class Solution:
def countSubstrings(self, s: str) -> int:
n = len(s)
count = len(s)
hm = {}
for i in range(n-1):
for j in range(i+1, n):
ns = s[i:j+1]
if ns in hm:
count+=1
else:
if ns==ns[::-1]:
hm[ns]=1
count+=1
else:
pass
return count | palindromic-substrings | Python Brute Force + hashmap solution. | prajwalahluwalia | 1 | 27 | palindromic substrings | 647 | 0.664 | Medium | 10,793 |
https://leetcode.com/problems/palindromic-substrings/discuss/2602024/94-faster-and-98-space-optimized-oror-Python | class Solution:
def countSubstrings(self, s: str) -> int:
result = 0
def isPalindrome(left, right):
counter = 0
while left >= 0 and right < len(s):
if s[left] != s[right]:
return counter
counter += 1
left -= 1
right += 1
return counter
for index in range(len(s)):
result += isPalindrome(index, index) + isPalindrome(index, index + 1)
return result | palindromic-substrings | 94 % faster and 98 % space optimized || Python | Sefinehtesfa34 | 1 | 123 | palindromic substrings | 647 | 0.664 | Medium | 10,794 |
https://leetcode.com/problems/palindromic-substrings/discuss/2339070/Python-Bottom-up-or-DP | class Solution:
def countSubstrings(self, s: str) -> int:
count = 0
dp = [[-1]*len(s) for _ in range(len(s))]
for g in range(len(s)):
for i,j in zip(range(0,len(dp)),range(g,len(dp))):
if g==0:
dp[i][j] = True
elif g==1:
if s[i] == s[j]:
dp[i][j] = True
else:
dp[i][j] = False
else:
if s[i] == s[j] and dp[i+1][j-1]==True:
dp[i][j] = True
else:
dp[i][j] = False
if dp[i][j]:
count+=1
return count | palindromic-substrings | Python Bottom up | DP | bliqlegend | 1 | 112 | palindromic substrings | 647 | 0.664 | Medium | 10,795 |
https://leetcode.com/problems/palindromic-substrings/discuss/2063895/Easy-and-Understandable-Approach-using-combinationsoror-Python | class Solution:
def countSubstrings(self, s: str) -> int:
count = 0
# Making all possible substring
res = [s[x:y] for x,y in combinations(range(len(s)+1),r = 2)]
# Checking if the reverse of the substring is same or not
for st in res:
if st==st[::-1]:
count+=1
return count | palindromic-substrings | Easy and Understandable Approach using combinations|| Python | M3Sachin | 1 | 69 | palindromic substrings | 647 | 0.664 | Medium | 10,796 |
https://leetcode.com/problems/palindromic-substrings/discuss/2009559/Python-DP-Solution-or-O(n2)-or-Expanding-around-center | class Solution:
def countSubstrings(self, s: str) -> int:
count = 0
for i in range(len(s)):
# odd len
l, r = i, i
while l >= 0 and r < len(s) and s[l] == s[r]:
count += 1
l -= 1
r += 1
# even len
l,r = i, i+1
while l >= 0 and r < len(s) and s[l] == s[r]:
count += 1
l -= 1
r += 1
return count | palindromic-substrings | Python DP Solution | O(n^2) | Expanding around center | dos_77 | 1 | 86 | palindromic substrings | 647 | 0.664 | Medium | 10,797 |
https://leetcode.com/problems/palindromic-substrings/discuss/1508517/Python3-Easy-to-understand-solution-using-expand-from-center | class Solution:
def countSubstrings(self, s: str) -> int:
def getPalindroms(word,left,right):
if left > right or word == "":
return 0
counter = 0
while left >= 0 and right < len(word) and word[left] == word[right]:
left -= 1
right += 1
counter += 1
return counter #Shows how many palindroms we have starting from left
result = 0
for i in range(len(s)):
result += getPalindroms(s,i,i)
result += getPalindroms(s,i,i+1)
return result | palindromic-substrings | [Python3] Easy to understand solution using expand from center | GiorgosMarga | 1 | 157 | palindromic substrings | 647 | 0.664 | Medium | 10,798 |
https://leetcode.com/problems/palindromic-substrings/discuss/1343078/Python3-solution-using-dynamic-programming | class Solution:
def countSubstrings(self, s: str) -> int:
m = len(s)
dp = []
for i in range(m):
x = []
for j in range(m):
if i == j:
x.append(1)
else:
x.append(0)
dp.append(x)
for i in range(m):
for j in range(i,m):
if j - i == 1:
if s[i] == s[j]:
dp[i][j] = 1
for i in range(m-1,-1,-1):
for j in range(m-1,-1,-1):
if j - i > 1:
if s[i] == s[j] and dp[i+1][j-1] == 1:
dp[i][j] = 1
res = 0
for i in dp:
res += sum(i)
return res | palindromic-substrings | Python3 solution using dynamic programming | EklavyaJoshi | 1 | 193 | palindromic substrings | 647 | 0.664 | Medium | 10,799 |
Subsets and Splits
Top 2 Solutions by Upvotes
Identifies the top 2 highest upvoted Python solutions for each problem, providing insight into popular approaches.