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/combination-sum-iii/discuss/1429952/Python-backtracking-solution-for-Combination-Sum-I-II-and-III | class Solution:
def combinationSum3(self, k: int, n: int) -> List[List[int]]:
nums = list(range(1, 10))
res = []
path = []
index = 0
total = 0
self.backtrack(k, n, nums, res, path, index, total)
return res
def backtrack(self, k, n, nums, res, path, index, total):
if len(path) == k and total == n:
res.append(path[:])
return
if total > n:
return
for i in range(index, len(nums)):
path.append(nums[i])
self.backtrack(k, n, nums, res, path, i+1, total + nums[i])
path.pop() | combination-sum-iii | Python backtracking solution for Combination Sum I, II and III | treksis | 0 | 80 | combination sum iii | 216 | 0.672 | Medium | 3,800 |
https://leetcode.com/problems/combination-sum-iii/discuss/1376521/combination-sum-III-or-Python3-or-Backtracking | class Solution:
def combinationSum3(self, k: int, n: int) -> List[List[int]]:
dg=[1,2,3,4,5,6,7,8,9]
ds=[]
self.ans=[]
self.solve(0,k,n,ds,dg)
return self.ans
def solve(self,strt,k,n,ds,dg):
if len(ds)==k and sum(ds)==n:
self.ans.append(ds[:])
return
for i in range(strt,len(dg)):
ds.append(dg[i])
self.solve(i+1,k,n,ds,dg)
ds.pop()
return | combination-sum-iii | combination sum III | Python3 | Backtracking | swapnilsingh421 | 0 | 56 | combination sum iii | 216 | 0.672 | Medium | 3,801 |
https://leetcode.com/problems/combination-sum-iii/discuss/1372731/Python3-solution | class Solution:
def combinationSum3(self, k: int, n: int) -> List[List[int]]:
l = list(range(1,10))
ans = []
for i in range(1,2**9+1):
x = bin(i)[2:].zfill(9)
if x.count('1') == k:
s = 0
for j in range(9):
if x[j] == '1':
s += (j+1)
if s == n:
z = []
for j in range(9):
if x[j] == '1':
z += [(j+1)]
ans += [z]
return ans | combination-sum-iii | Python3 solution | EklavyaJoshi | 0 | 28 | combination sum iii | 216 | 0.672 | Medium | 3,802 |
https://leetcode.com/problems/combination-sum-iii/discuss/1353807/Python3-Backtracking-Simple-beat-70 | class Solution:
def combinationSum3(self, k: int, n: int) -> List[List[int]]:
res = []
def backtrack(remain,start,comb):
if len(comb) == k:
if remain == 0:
res.append(list(comb))
return
for i in range(start,min(9,remain)):
comb.append(i+1)
backtrack(remain-i-1,i+1,comb)
comb.pop()
backtrack(n,0,[])
return res | combination-sum-iii | Python3 Backtracking Simple beat 70% | caw062 | 0 | 60 | combination sum iii | 216 | 0.672 | Medium | 3,803 |
https://leetcode.com/problems/combination-sum-iii/discuss/1336746/Python3-faster-than-91.27-backtracking | class Solution:
def combinationSum3(self, k: int, n: int) -> List[List[int]]:
result = []
def traverse(cur: List[int], curSet: set, memo: List[set], s: int, index: int):
if s == n:
if curSet not in memo and len(cur) == k:
result.append(cur)
memo.append(curSet)
else:
return
if s > n:
return
for i in range(index, 10):
copy = cur.copy()
copySet = curSet.copy()
copy.append(i)
copySet.add(i)
# no need to compute anymore
if len(copy) > k:
continue
traverse(
copy,
copySet,
memo,
s + i,
i + 1
)
traverse([], set(), [], 0, 1)
return result | combination-sum-iii | Python3 - faster than 91.27%, backtracking | CC_CheeseCake | 0 | 15 | combination sum iii | 216 | 0.672 | Medium | 3,804 |
https://leetcode.com/problems/combination-sum-iii/discuss/842992/simple-python-recursive-solution-or-faster-than-89-submisssions | class Solution:
def Util(self, k, n, i, sm, curstr):
if sm == n and len(curstr) == k:
return [list(map(int, curstr))]
if sm > n or len(curstr) > k:
return [[]]
if i >= 10:
return [[]]
ret1 = self.Util(k, n, i + 1, sm + i, curstr + str(i))
ret2 = self.Util(k, n, i + 1, sm, curstr)
if ret1 != [[]] and ret2 != [[]]:
return ret1 + ret2
if ret1 != [[]]:
return ret1
if ret2 != [[]]:
return ret2
else:
return [[]]
def combinationSum3(self, k: int, n: int) -> List[List[int]]:
ans = self.Util(k, n, 1, 0, '')
if ans == [[]]:
return []
return ans | combination-sum-iii | simple python recursive solution | faster than 89 % submisssions | _YASH_ | 0 | 26 | combination sum iii | 216 | 0.672 | Medium | 3,805 |
https://leetcode.com/problems/combination-sum-iii/discuss/753226/Python3-easy-understanding | class Solution:
def combinationSum3(self, k: int, n: int) -> List[List[int]]:
def helper(arr, idx, k, n):
if n < 0:
return
if k == 0 and n == 0:
res.append(deepcopy(arr))
return
for i in range(idx, min(n + 1, 10)):
arr.append(i)
helper(arr, i + 1, k - 1, n - i)
arr.pop()
res = []
helper([], 1, k, n)
return res | combination-sum-iii | Python3 easy understanding | tianboh | 0 | 38 | combination sum iii | 216 | 0.672 | Medium | 3,806 |
https://leetcode.com/problems/combination-sum-iii/discuss/738244/Python3-combination-sum-I-II-III | class Solution:
def combinationSum3(self, k: int, n: int) -> List[List[int]]:
def fn(n, i=1):
"""Populate ans with a stack."""
if n < 0 or len(stack) > k: return
if n == 0 and len(stack) == k: return ans.append(stack.copy())
for ii in range(i, 10):
stack.append(ii)
fn(n-ii, ii+1)
stack.pop()
ans, stack = [], []
fn(n)
return ans | combination-sum-iii | [Python3] combination sum I, II, III | ye15 | 0 | 78 | combination sum iii | 216 | 0.672 | Medium | 3,807 |
https://leetcode.com/problems/combination-sum-iii/discuss/738244/Python3-combination-sum-I-II-III | class Solution:
def combinationSum3(self, k: int, n: int) -> List[List[int]]:
dp = [[] for _ in range(n+1)]
dp[0].append([])
for x in range(1, 10):
for i in reversed(range(n)):
if i+x <= n:
for seq in dp[i]:
dp[i+x].append(seq + [x])
return [seq for seq in dp[-1] if len(seq) == k] | combination-sum-iii | [Python3] combination sum I, II, III | ye15 | 0 | 78 | combination sum iii | 216 | 0.672 | Medium | 3,808 |
https://leetcode.com/problems/combination-sum-iii/discuss/738244/Python3-combination-sum-I-II-III | class Solution:
def combinationSum3(self, k: int, n: int) -> List[List[int]]:
ans, stack = [], []
x = 1
while True:
if len(stack) == k and sum(stack) == n: ans.append(stack.copy())
if len(stack) == k or k - len(stack) > 10 - x:
if not stack: break
x = stack.pop() + 1
else:
stack.append(x)
x += 1
return ans | combination-sum-iii | [Python3] combination sum I, II, III | ye15 | 0 | 78 | combination sum iii | 216 | 0.672 | Medium | 3,809 |
https://leetcode.com/problems/combination-sum-iii/discuss/536806/Python-(DFS%2BBacktracking) | class Solution:
def combinationSum3(self, k: int, n: int) -> List[List[int]]:
res = []
self.backtrack(k, n, [],0,1, res)
return res
def backtrack(self, k, n, cur, comb, ind, res):
if comb > n:
return
elif comb == n and len(cur) == k:
res.append([]+cur)
else:
for i in range(ind,10):
cur.append(i)
self.backtrack(k, n, cur, comb+i, i+1, res)
cur.pop() | combination-sum-iii | Python (DFS+Backtracking) | tohbaino | 0 | 119 | combination sum iii | 216 | 0.672 | Medium | 3,810 |
https://leetcode.com/problems/contains-duplicate/discuss/1496268/Python-98-speed-faster | class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
return len(set(nums)) != len(nums) | contains-duplicate | Python // 98% speed faster | fabioo29 | 11 | 1,900 | contains duplicate | 217 | 0.613 | Easy | 3,811 |
https://leetcode.com/problems/contains-duplicate/discuss/2546139/3-different-Python-solutions | class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
return len(set(nums)) != len(nums) | contains-duplicate | 📌 3 different Python solutions | croatoan | 10 | 807 | contains duplicate | 217 | 0.613 | Easy | 3,812 |
https://leetcode.com/problems/contains-duplicate/discuss/2546139/3-different-Python-solutions | class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
res = {}
for i in nums:
if i not in res:
res[i] = 1
else:
return True
return False | contains-duplicate | 📌 3 different Python solutions | croatoan | 10 | 807 | contains duplicate | 217 | 0.613 | Easy | 3,813 |
https://leetcode.com/problems/contains-duplicate/discuss/2546139/3-different-Python-solutions | class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
return set(collections.Counter(nums).values()) != set([1]) | contains-duplicate | 📌 3 different Python solutions | croatoan | 10 | 807 | contains duplicate | 217 | 0.613 | Easy | 3,814 |
https://leetcode.com/problems/contains-duplicate/discuss/2196197/Python-One-liner | class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
seen = {}
for i in range(len(nums)):
seen[nums[i]] = seen.get(nums[i], 0) + 1
for k, v in seen.items():
if v > 1:
return True
return False | contains-duplicate | ✅Python - One liner | thesauravs | 10 | 655 | contains duplicate | 217 | 0.613 | Easy | 3,815 |
https://leetcode.com/problems/contains-duplicate/discuss/2196197/Python-One-liner | class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
return not len(nums) == len(set(nums)) | contains-duplicate | ✅Python - One liner | thesauravs | 10 | 655 | contains duplicate | 217 | 0.613 | Easy | 3,816 |
https://leetcode.com/problems/contains-duplicate/discuss/2196197/Python-One-liner | class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
temp = set()
count = 0
for num in nums:
temp.add(num)
count += 1
if len(temp) != count:
return True
return False | contains-duplicate | ✅Python - One liner | thesauravs | 10 | 655 | contains duplicate | 217 | 0.613 | Easy | 3,817 |
https://leetcode.com/problems/contains-duplicate/discuss/2593840/SIMPLE-PYTHON3-SOLUTION-ONE-LINER-easiest-using-set | class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
return False if len(nums)==len(list(set(nums))) else True | contains-duplicate | ✅✔ SIMPLE PYTHON3 SOLUTION ✅✔ ONE LINER easiest using set | rajukommula | 9 | 1,100 | contains duplicate | 217 | 0.613 | Easy | 3,818 |
https://leetcode.com/problems/contains-duplicate/discuss/343102/Solution-in-Python-3-(beats-~100) | class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
return len(set(nums)) != len(nums)
- Python 3
- Junaid Mansuri | contains-duplicate | Solution in Python 3 (beats ~100%) | junaidmansuri | 9 | 3,100 | contains duplicate | 217 | 0.613 | Easy | 3,819 |
https://leetcode.com/problems/contains-duplicate/discuss/1128103/Simple-Python-Solution-Faster-than-95 | class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
return len(set(nums))!=len(nums) | contains-duplicate | Simple Python Solution; Faster than 95% | Annushams | 8 | 1,400 | contains duplicate | 217 | 0.613 | Easy | 3,820 |
https://leetcode.com/problems/contains-duplicate/discuss/2340241/fast-short-and-simple-python-code | class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
ls=len(set(nums))
l=len(nums)
return l>ls | contains-duplicate | fast, short & simple python code | ayushigupta2409 | 6 | 532 | contains duplicate | 217 | 0.613 | Easy | 3,821 |
https://leetcode.com/problems/contains-duplicate/discuss/2803000/87.55-TC-with-simple-python-solution-for-Contains-Duplicate-problem | class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
dict_nums = {}
for i in nums:
if i in dict_nums:
return True
else:
dict_nums[i] = 1
return False | contains-duplicate | 😎 87.55% TC with simple python solution for Contains Duplicate problem | Pragadeeshwaran_Pasupathi | 4 | 773 | contains duplicate | 217 | 0.613 | Easy | 3,822 |
https://leetcode.com/problems/contains-duplicate/discuss/2657081/Python-or-1-liner-set-solution | class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
return len(nums) > len(set(nums)) | contains-duplicate | Python | 1-liner set solution | LordVader1 | 4 | 349 | contains duplicate | 217 | 0.613 | Easy | 3,823 |
https://leetcode.com/problems/contains-duplicate/discuss/2642318/Python-oror-Easily-Understood-oror-Faster-than-96-oror-ONELINE-SOLUTION | class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
return False if len(nums)==len(list(set(nums))) else True | contains-duplicate | 🔥 Python || Easily Understood ✅ || Faster than 96% || ONELINE SOLUTION | rajukommula | 3 | 233 | contains duplicate | 217 | 0.613 | Easy | 3,824 |
https://leetcode.com/problems/contains-duplicate/discuss/2364314/Solution-that-beats-95.35-in-Runtime-97.45-in-Memory-Usage. | class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
love = set()
while nums:
temp = nums.pop()
if temp in love: return True
else: love.add(temp) | contains-duplicate | Solution that beats 95.35% in Runtime, 97.45% in Memory Usage. | HappyLunchJazz | 3 | 562 | contains duplicate | 217 | 0.613 | Easy | 3,825 |
https://leetcode.com/problems/contains-duplicate/discuss/1947745/Python3-Using-Python-Sets-(faster-than-91) | class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
# In this solution, we use a python set to remove any duplicates, then convert the set back into a list.
# Python Sets are a unique data structure that only contains unique items and are unordered and unchangable.
# Learn more about sets: https://www.w3schools.com/python/python_sets.asp
# With this, if there are any duplicates we will know because the new list will have less items than the original
if(len(nums) > len(list(set(nums)))):
return True
else:
return False | contains-duplicate | [Python3] Using Python Sets (faster than 91%) | Rustizx | 3 | 176 | contains duplicate | 217 | 0.613 | Easy | 3,826 |
https://leetcode.com/problems/contains-duplicate/discuss/1886465/Python-One-liner-or-Time-Complexity-%3A-O(n) | class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
return len(nums) != len(set(nums)) | contains-duplicate | Python One liner | Time Complexity : O(n) | parthpatel9414 | 3 | 265 | contains duplicate | 217 | 0.613 | Easy | 3,827 |
https://leetcode.com/problems/contains-duplicate/discuss/1779672/Python-Simple-Python-Solution-With-Two-Approach | class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
t=list(dict.fromkeys(nums))
if len(t)!=len(nums):
return True
else:
return False | contains-duplicate | [ Python ] ✔✅ Simple Python Solution With Two Approach 🔥✌ | ASHOK_KUMAR_MEGHVANSHI | 3 | 451 | contains duplicate | 217 | 0.613 | Easy | 3,828 |
https://leetcode.com/problems/contains-duplicate/discuss/1779672/Python-Simple-Python-Solution-With-Two-Approach | class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
dictionary = {}
for num in nums:
if num not in dictionary:
dictionary[num] = 1
else:
return True
return False | contains-duplicate | [ Python ] ✔✅ Simple Python Solution With Two Approach 🔥✌ | ASHOK_KUMAR_MEGHVANSHI | 3 | 451 | contains duplicate | 217 | 0.613 | Easy | 3,829 |
https://leetcode.com/problems/contains-duplicate/discuss/1568960/Python-Very-Easy-Solution-or-Using-HashSet | class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
# Time and Space: O(n)
# 1st Approach:
hashSet = set()
for i in range(len(nums)):
if nums[i] in hashSet:
return True
hashSet.add(nums[i])
# 2nd Approach:
hashMap = dict()
for i in range(len(nums)):
if nums[i] in hashMap:
return True
else:
hashMap[i] = 1 | contains-duplicate | Python Very Easy Solution | Using HashSet | leet_satyam | 3 | 457 | contains duplicate | 217 | 0.613 | Easy | 3,830 |
https://leetcode.com/problems/contains-duplicate/discuss/1250561/Python3-dollarolution-(one-lineSimple-code) | class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
return (len(nums) != len(set(nums))) | contains-duplicate | Python3 $olution (one line/Simple code) | AakRay | 3 | 447 | contains duplicate | 217 | 0.613 | Easy | 3,831 |
https://leetcode.com/problems/contains-duplicate/discuss/381953/Python-solutions | class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
return len(set(nums)) < len(nums) | contains-duplicate | Python solutions | amchoukir | 3 | 932 | contains duplicate | 217 | 0.613 | Easy | 3,832 |
https://leetcode.com/problems/contains-duplicate/discuss/2263172/One-line-solution-217.-Contains-Duplicate | class Solution(object):
def containsDuplicate(self, nums):
return len(nums)!= len(set(nums)) | contains-duplicate | One line solution 217. Contains Duplicate | m_e_shivam | 2 | 304 | contains duplicate | 217 | 0.613 | Easy | 3,833 |
https://leetcode.com/problems/contains-duplicate/discuss/2089924/Python3-4-solutions-from-O(n2)-to-O(n)-in-runtime-O(n)-to-O(1)-in-memory | class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
return self.containDuplicateWithSet(nums)
# O(n^2) || O(1)
def containDuplicateBruteForce(self, array):
if not array: return False
for i in range(len(array)):
for j in range(i + 1, len(array)):
if array[i] == array[j]:
return True
return False
# where n is the number of elements in the array
# O(n) || O(n)
def containDuplicateWithSet(self, array):
if not array: return False
hashSet = set()
for i in array:
if i in hashSet:
return True
hashSet.add(i)
return False
# OR
return len(set(array)) == len(array)
# O(nlogn) || O(1)
def containDuplicateWithSorting(self, array):
if not array: return False
array.sort()
for i in range(1, len(array)):
if array[i-1] == array[i]:
return True
return False | contains-duplicate | Python3 4 solutions from O(n^2) to O(n) in runtime; O(n) to O(1) in memory | arshergon | 2 | 423 | contains duplicate | 217 | 0.613 | Easy | 3,834 |
https://leetcode.com/problems/contains-duplicate/discuss/1909604/3-Different-Approaches-w-Explaination-O(n2)-O(nlogn)-O(n) | class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
# BruteForce
# Time: O(n^2) Space: O(1)
# Here, we'll simply compare each and every pair of element in the list
# and if there's a pair which has the same value
# then we'll return True
for i in range(len(nums)):
for j in range(len(nums)):
if i == j:
continue
elif nums[i] == nums[j]:
return True
return False
# The above solution wll give TLE because of the constraints
# So, let's get to a more optimal solution
# Sorting method
# Time: O(nlogn) Space: O(1)
# Here, we'll sort the list and check if the current and next element are equal
# if yes, the return True
nums.sort()
for i in range(1,len(nums)):
if nums[i] == nums[i-1]:
return True
return False
# The above solution works but we can get more optimal solution
# so, let's find out the solution
# Dictionary method
#Time: O(n) Space: O(n)
# Here, we'll traverse through the list and in each iteration
# we'll keep the count of the element in the dictionary
# if for some element the count == 2 we'll return True
res = {}
for el in nums:
if el in res:
return True
else:
res[el] = 1
return False | contains-duplicate | 3 Different Approaches w/ Explaination O(n^2) O(nlogn) O(n) | introvertednerd | 2 | 239 | contains duplicate | 217 | 0.613 | Easy | 3,835 |
https://leetcode.com/problems/contains-duplicate/discuss/1734583/Python-one-line-solution | class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
return not(len(set(nums)) == len(nums)) | contains-duplicate | Python one line solution | rushikeshjaisur11 | 2 | 566 | contains duplicate | 217 | 0.613 | Easy | 3,836 |
https://leetcode.com/problems/contains-duplicate/discuss/1246656/WEEB-DOES-PYTHON(3-METHODS) | class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
nums = sorted(nums)
for i in range(len(nums)-1):
if nums[i] == nums[i+1]:
return True
return False
# METHOD 2: using the Counter function from collections
# return True if Counter(nums).most_common(1)[0][1] > 1 else False
# METHOD 3: using sets
# return len(nums) != len(set(nums)) | contains-duplicate | WEEB DOES PYTHON(3 METHODS) | Skywalker5423 | 2 | 353 | contains duplicate | 217 | 0.613 | Easy | 3,837 |
https://leetcode.com/problems/contains-duplicate/discuss/819888/Python-One-Line-Easy | class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
return True if len(set(nums)) < len(nums) else False
# TC: O(n)
# SC: O(n) | contains-duplicate | Python One Line, Easy | airksh | 2 | 150 | contains duplicate | 217 | 0.613 | Easy | 3,838 |
https://leetcode.com/problems/contains-duplicate/discuss/2747229/Contains-Duplicate-or-Python-1-liner | class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
if len(set(nums)) != len(nums): return True | contains-duplicate | Contains Duplicate | Python 1 liner | ygygupta0 | 1 | 46 | contains duplicate | 217 | 0.613 | Easy | 3,839 |
https://leetcode.com/problems/contains-duplicate/discuss/2730690/1-Liner-Python3 | class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
return (len(nums) != len(set(nums))) | contains-duplicate | 1 Liner, Python3 | zoominL1 | 1 | 10 | contains duplicate | 217 | 0.613 | Easy | 3,840 |
https://leetcode.com/problems/contains-duplicate/discuss/2426099/Python3-2-Approaches-with-Big-O-breakdown-results-(99.8-runtime)-and-explanation | class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
# I want to try this two ways to compare complexity and runtime
if len(nums) == 0: return False
# 1. Sort the array, then loop through to search for neighbours
# Complexity = Sorting + Looping through comparing
# = O(nlogn) + O(n)
# = O(nlogn)
# Results: 697ms (47.8%), 26.2MB (5.20%)
#nums.sort()
#for i in range(1, len(nums)):
# if nums[i] == nums[i-1]: return True
#return False
# 2. Loop through the array updating a dict (hashmap) and return if the entry already exists
# Complexity = Looping * dictionary lookup
# = O(n) * O(1) on average
# Results: 435ms (99.8%), 26MB (72.7%)
seen = {}
for i in nums:
if seen.get(i): return True
seen[i] = 1
return False | contains-duplicate | [Python3] 2 Approaches with Big O breakdown, results (99.8% runtime), and explanation | connorthecrowe | 1 | 142 | contains duplicate | 217 | 0.613 | Easy | 3,841 |
https://leetcode.com/problems/contains-duplicate/discuss/2361442/python3-or-Hashmap | class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
numsDict = {}
for i in range(len(nums)):
if nums[i] not in numsDict:
numsDict[nums[i]] = 1
else:
numsDict[nums[i]] += 1
for k, v in numsDict.items():
if v > 1:
return True
return False | contains-duplicate | python3 | Hashmap | arvindchoudhary33 | 1 | 60 | contains duplicate | 217 | 0.613 | Easy | 3,842 |
https://leetcode.com/problems/contains-duplicate/discuss/2317509/Solution-(Faster-than-90-) | class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
num = set(nums)
if len(num) < len(nums):
return True
return False | contains-duplicate | Solution (Faster than 90 %) | fiqbal997 | 1 | 210 | contains duplicate | 217 | 0.613 | Easy | 3,843 |
https://leetcode.com/problems/contains-duplicate/discuss/2287903/Easy-python3-using-set(updated) | class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
hashset = set()
for num in nums:
if num in hashset:
return True
hashset.add(num)
return False | contains-duplicate | Easy python3 using set(updated) | __Simamina__ | 1 | 120 | contains duplicate | 217 | 0.613 | Easy | 3,844 |
https://leetcode.com/problems/contains-duplicate/discuss/2246533/Python3-solution-using-set | class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
if len(nums)==0:
return False
d = set()
for i in nums:
if i in d:
return True
else:
d.add(i)
return False | contains-duplicate | 📌 Python3 solution using set | Dark_wolf_jss | 1 | 56 | contains duplicate | 217 | 0.613 | Easy | 3,845 |
https://leetcode.com/problems/contains-duplicate/discuss/2188042/Python-Hash-Set-oror-Two-Pointer-oror-Brute-Force-easy-solutions | class Solution: # Most efficient in TIME among the solutions
def containsDuplicate(self, nums: List[int]) -> bool: # Time: O(1) and Space: O(n)
hashset=set()
for n in nums:
if n in hashset:return True
hashset.add(n)
return False | contains-duplicate | Python [ Hash Set || Two Pointer || Brute Force ] easy solutions | DanishKhanbx | 1 | 263 | contains duplicate | 217 | 0.613 | Easy | 3,846 |
https://leetcode.com/problems/contains-duplicate/discuss/2188042/Python-Hash-Set-oror-Two-Pointer-oror-Brute-Force-easy-solutions | class Solution: # Most efficient in SPACE among the solutions
def containsDuplicate(self, nums: List[int]) -> bool: # Time: O(nlogn) and Space: O(1)
nums.sort()
l = 0
r = l + 1
while r < len(nums):
if nums[l] == nums[r]:
return True
l = l + 1
r = l + 1
return False | contains-duplicate | Python [ Hash Set || Two Pointer || Brute Force ] easy solutions | DanishKhanbx | 1 | 263 | contains duplicate | 217 | 0.613 | Easy | 3,847 |
https://leetcode.com/problems/contains-duplicate/discuss/2188042/Python-Hash-Set-oror-Two-Pointer-oror-Brute-Force-easy-solutions | class Solution: # Time limit exceeds
def containsDuplicate(self, nums: List[int]) -> bool:
for i in range(len(nums)):
for j in range(i+1,len(nums)):
if nums[i]==nums[j]:
return True
return False | contains-duplicate | Python [ Hash Set || Two Pointer || Brute Force ] easy solutions | DanishKhanbx | 1 | 263 | contains duplicate | 217 | 0.613 | Easy | 3,848 |
https://leetcode.com/problems/contains-duplicate/discuss/2175684/Python-One-Liner-Solution-454-ms-faster-than-97.56 | class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
return True if(len(nums)>len(set(nums))) else False | contains-duplicate | Python One Liner Solution 454 ms, faster than 97.56% | thetimeloops | 1 | 262 | contains duplicate | 217 | 0.613 | Easy | 3,849 |
https://leetcode.com/problems/contains-duplicate/discuss/2002489/Python-easy-to-read-and-understand-or-set | class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
d = set()
for num in nums:
if num in d:
return True
d.add(num)
return False | contains-duplicate | Python easy to read and understand | set | sanial2001 | 1 | 291 | contains duplicate | 217 | 0.613 | Easy | 3,850 |
https://leetcode.com/problems/contains-duplicate/discuss/1917418/Python-3-Simple-one-line-solution-oror-88-faster | class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
return len(nums) != len(list(set(nums))) | contains-duplicate | Python 3 Simple one line solution || 88% faster | VINOD27 | 1 | 187 | contains duplicate | 217 | 0.613 | Easy | 3,851 |
https://leetcode.com/problems/contains-duplicate/discuss/1903448/Python-1-liner-explained | class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
return len(nums) != len(set(nums)) | contains-duplicate | Python 1 liner explained | fox-of-snow | 1 | 119 | contains duplicate | 217 | 0.613 | Easy | 3,852 |
https://leetcode.com/problems/contains-duplicate/discuss/1893043/Python3-1-line-99.5-faster | class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
return len(set(nums)) != len(nums) | contains-duplicate | Python3, 1 line 99.5% faster | AK_gautam | 1 | 192 | contains duplicate | 217 | 0.613 | Easy | 3,853 |
https://leetcode.com/problems/contains-duplicate/discuss/1772859/Contains-Duplicate-Python-O(n) | class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
hashset = set() #declaring hashset
for n in nums: #n is iterator
if n in hashset: #if n exists in hashset return true
return True
hashset.add(n) #else add it to hashset
return False #duplicate not exist return false | contains-duplicate | Contains Duplicate Python O(n) | prasadshembekar | 1 | 348 | contains duplicate | 217 | 0.613 | Easy | 3,854 |
https://leetcode.com/problems/contains-duplicate/discuss/1606977/3-ways%3Asort%2Bset-hashtable-counter-package | class Solution(object):
def containsDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
#1
# a = list(set(nums))
# nums.sort()
# a.sort()
# return False if a==nums else True
#2
hash_table = {}
for num in nums:
hash_table[num] = hash_table.get(num, 0)+1
return False if max(hash_table.values()) == 1 else True
# #3
# from collections import Counter
# return False if set(Counter(nums).values()) == {1} else True | contains-duplicate | 3 ways:sort+set, hashtable, counter package | Allisonzhang4 | 1 | 136 | contains duplicate | 217 | 0.613 | Easy | 3,855 |
https://leetcode.com/problems/the-skyline-problem/discuss/2640697/Python-oror-Easily-Understood-oror-Faster-oror-with-maximum-heap-explained | class Solution:
def getSkyline(self, buildings: List[List[int]]) -> List[List[int]]:
# for the same x, (x, -H) should be in front of (x, 0)
# For Example 2, we should process (2, -3) then (2, 0), as there's no height change
x_height_right_tuples = sorted([(L, -H, R) for L, R, H in buildings] + [(R, 0, "doesn't matter") for _, R, _ in buildings])
# (0, float('inf')) is always in max_heap, so max_heap[0] is always valid
result, max_heap = [[0, 0]], [(0, float('inf'))]
for x, negative_height, R in x_height_right_tuples:
while x >= max_heap[0][1]:
# reduce max height up to date, i.e. only consider max height in the right side of line x
heapq.heappop(max_heap)
if negative_height:
# Consider each height, as it may be the potential max height
heapq.heappush(max_heap, (negative_height, R))
curr_max_height = -max_heap[0][0]
if result[-1][1] != curr_max_height:
result.append([x, curr_max_height])
return result[1:] | the-skyline-problem | 🔥 Python || Easily Understood ✅ || Faster || with maximum heap explained | rajukommula | 12 | 1,100 | the skyline problem | 218 | 0.416 | Hard | 3,856 |
https://leetcode.com/problems/the-skyline-problem/discuss/2640781/My-Python-Solution-with-Comments | class Solution:
def getSkyline(self, buildings: List[List[int]]) -> List[List[int]]:
events = []
for L, R, H in buildings:
# append start point of building
events.append((L, -H, R))
# append end point of building
events.append((R, 0, 0))
# sort the event
events.sort()
# init for result and heap
res = [[0, 0]]
hp = [(0, float("inf"))]
for pos, negH, R in events:
# pop out building which is end
while hp[0][1] <= pos:
heapq.heappop(hp)
# if it is a start of building, push it into heap as current building
if negH != 0:
heapq.heappush(hp, (negH, R))
# if change in height with previous key point, append to result
if res[-1][1] != -hp[0][0]:
res.append([pos, -hp[0][0]])
return res[1:] | the-skyline-problem | My Python Solution with Comments ✅ | Khacker | 3 | 408 | the skyline problem | 218 | 0.416 | Hard | 3,857 |
https://leetcode.com/problems/the-skyline-problem/discuss/2642224/Python-two-heaps-to-maintain-the-max-height | class Solution:
def getSkyline(self, buildings: List[List[int]]) -> List[List[int]]:
change_point = []
for start, end, height in buildings:
# 1 means the start of the building
# -1 means the end of the building
change_point.append([start, 1, height])
change_point.append([end, -1, height])
change_point.sort(key = lambda x:[x[0], -x[1], -x[2]])
res = []
heap = [] # height
remove_heap = []
for i, (position, flag, height) in enumerate(change_point):
# add a building
if flag == 1:
heapq.heappush(heap, -height)
# remove a building
else:
heapq.heappush(remove_heap, -height)
# remove all the removed height, to avoid taking the removed height as the highest
while len(remove_heap) > 0 and heap[0] == remove_heap[0]:
heapq.heappop(heap)
heapq.heappop(remove_heap)
# no building at the current position
if len(heap) == 0:
res.append([position, 0])
else:
# take consideration of the first and the last one
# if the current max height equals the last height(two adjacent buildings), continue
# if the current position has multiple operations(only take the highest one), continue
if i == 0 or i == len(change_point)-1 or (-heap[0] != res[-1][1] and position != change_point[i+1][0]):
res.append([position, -heap[0]]) # current max height
return res | the-skyline-problem | [Python] two heaps to maintain the max height | henryluo108 | 2 | 42 | the skyline problem | 218 | 0.416 | Hard | 3,858 |
https://leetcode.com/problems/the-skyline-problem/discuss/2641854/Faster-than-93.17-or-Single-priority-Queue-or-Easy-to-understand-or-Python3-or-Max-heap | class Solution(object):
def getSkyline(self, buildings):
"""
:type buildings: List[List[int]]
:rtype: List[List[int]]
"""
buildings.sort(key=lambda x:[x[0],-x[2]]) #Sort elements according to x-axis (ascending) and height(descending)
new_b=[]
max_r=-float('inf')
min_l=float('inf')
for i in buildings:
new_b.append([-i[2],i[0],i[1]]) #Create new array for priority queue with [-1*height, left,right], as we are creating max heap
max_r=max(max_r,i[1])
min_l=min(min_l,i[0])
ans=[[0,0,max_r+1]] #for default when the buildings at a specific point is over
f_ans=[]
heapq.heapify(ans)
while min_l<=max_r:
while new_b and min_l>=new_b[0][1]:
temp=new_b.pop(0)
heapq.heappush(ans,temp)
while ans and ans[0][2]<=min_l:
heapq.heappop(ans)
if not f_ans or f_ans[-1][1]!=(-ans[0][0]):
f_ans.append([min_l,-ans[0][0]])
if new_b:
min_l=min(ans[0][2],new_b[0][1]) #To update the min_l according to the next element and the element itself
else:
min_l=ans[0][2]
return f_ans | the-skyline-problem | Faster than 93.17% | Single priority Queue | Easy to understand | Python3 | Max heap | ankush_A2U8C | 2 | 122 | the skyline problem | 218 | 0.416 | Hard | 3,859 |
https://leetcode.com/problems/the-skyline-problem/discuss/741467/Python3-priority-queue | class Solution:
def getSkyline(self, buildings: List[List[int]]) -> List[List[int]]:
buildings.append([inf, inf, 0]) # sentinel
ans, pq = [], [] # max-heap
for li, ri, hi in buildings:
while pq and -pq[0][1] < li:
_, rj = heappop(pq)
while pq and -pq[0][1] <= -rj: heappop(pq)
hj = pq[0][0] if pq else 0
ans.append((-rj, -hj))
if 0 < hi and (not pq or -pq[0][0] < hi):
if ans and ans[-1][0] == li: ans.pop()
ans.append((li, hi))
heappush(pq, (-hi, -ri))
return ans | the-skyline-problem | [Python3] priority queue | ye15 | 2 | 423 | the skyline problem | 218 | 0.416 | Hard | 3,860 |
https://leetcode.com/problems/the-skyline-problem/discuss/2642707/Clean-Python3-or-Heap-or-O(n-log(n)) | class Solution:
def getSkyline(self, buildings: List[List[int]]) -> List[List[int]]:
buildings.sort(key = lambda k: (k[0], -k[2])) # by left (asc), then by height (desc)
buildings.append([float('inf'), float('inf'), 0]) # to help with end condition
height_mxheap = [] # [(height, right), ...]
skyline = [] # [(left, height), ...]
for left, right, height in buildings:
# while max height building has been passed
while height_mxheap and height_mxheap[0][1] <= left:
_, last_right = heapq.heappop(height_mxheap)
if last_right == left: # has alredy been accounted for
continue
# pop all shorter heights with a right that passed before last_right
while height_mxheap and height_mxheap[0][1] <= last_right:
heapq.heappop(height_mxheap)
if height_mxheap: # if there is something left, end the previous section and add this
if skyline[-1][1] != -height_mxheap[0][0]:
skyline.append([last_right, -height_mxheap[0][0]])
else: # if there is nothing, add a 0 section
skyline.append([last_right, 0])
heapq.heappush(height_mxheap, (-height, right))
max_height = -height_mxheap[0][0]
# start next section with current max height building
if not skyline or skyline[-1][1] != max_height:
skyline.append([left, max_height])
return skyline | the-skyline-problem | Clean Python3 | Heap | O(n log(n)) | ryangrayson | 1 | 102 | the skyline problem | 218 | 0.416 | Hard | 3,861 |
https://leetcode.com/problems/the-skyline-problem/discuss/2641280/Python3-Extremely-bad-and-convoluted-solution-but-surprisingly-fast | class Solution:
def getSkyline(self, buildings: List[List[int]]) -> List[List[int]]:
"""LeetCode 218
My God. I did it by myself. Could've passed on the first try, but got
a little confused about the first if condition. It was fixed very
quickly.
This solution is pure analysis. We sort the buildings in descent for
heights, and if heights are the same, sort left ascend.
Then we build the range for each contour. We use the left bound as key,
and the value is [right bound, left height, right height]
For each new building, we sort the keys, so that we can use binary
search to see where the new building shall be placed. Since the height
of the new building is not heigher than all the existing contours,
any time the new building has left or right side stuck out, we record
the results. Also, if the new building touches or merges with some of
the existing contour, we update the contour or delete it.
It's convoluted, but it can be done if one is patient enough.
106 ms, faster than 99.75%
"""
buildings.sort(key=lambda lst: (lst[2], -lst[0]), reverse=True)
# the values are [right bound, left height, right height]
left_bounds = {buildings[0][0]: [buildings[0][1], buildings[0][2], buildings[0][2]]}
res = [[buildings[0][0], buildings[0][2]]]
for l, r, h in buildings[1:]:
sorted_left = sorted(left_bounds)
idx = bisect_right(sorted_left, l)
if idx == len(sorted_left) and l > left_bounds[sorted_left[idx - 1]][0]:
pl = sorted_left[idx - 1]
pr, plh, prh = left_bounds[pl]
if pr < l:
res.append([l, h])
left_bounds[l] = [r, h, h]
else:
left_bounds[pl][0] = r
if prh > h:
res.append([pr, h])
left_bounds[pl][0] = r
left_bounds[pl][2] = h
elif idx == 0:
res.append([l, h])
if r < sorted_left[0]:
left_bounds[l] = [r, h, h]
else:
some_r_bigger = False
for sl in sorted_left:
if left_bounds[sl][0] < r:
if left_bounds[sl][2] > h:
res.append([left_bounds[sl][0], h])
del left_bounds[sl]
else:
some_r_bigger = True
break
if not some_r_bigger or r < sl:
left_bounds[l] = [r, h, h]
else:
left_bounds[l] = [left_bounds[sl][0], h, left_bounds[sl][2]]
del left_bounds[sl]
else:
pl = sorted_left[idx - 1]
if r <= left_bounds[pl][0]:
continue
if l > left_bounds[pl][0]:
res.append([l, h])
elif left_bounds[pl][2] > h:
res.append([left_bounds[pl][0], h])
i = idx
some_r_bigger = False
while i < len(sorted_left):
sl = sorted_left[i]
if left_bounds[sl][0] < r:
if left_bounds[sl][2] > h:
res.append([left_bounds[sl][0], h])
del left_bounds[sl]
else:
some_r_bigger = True
break
i += 1
if not some_r_bigger or r < sorted_left[i]:
if l > left_bounds[pl][0]:
left_bounds[l] = [r, h, h]
else:
left_bounds[pl][0] = r
left_bounds[pl][2] = h
else:
sl = sorted_left[i]
if l > left_bounds[pl][0]:
left_bounds[l] = [left_bounds[sl][0], h, left_bounds[sl][2]]
else:
left_bounds[pl][0] = left_bounds[sl][0]
left_bounds[pl][2] = left_bounds[sl][2]
del left_bounds[sl]
# print(l, r, h)
# print(left_bounds)
for r, _, _ in left_bounds.values():
res.append([r, 0])
return sorted(res) | the-skyline-problem | [Python3] Extremely bad and convoluted solution, but surprisingly fast | FanchenBao | 1 | 150 | the skyline problem | 218 | 0.416 | Hard | 3,862 |
https://leetcode.com/problems/the-skyline-problem/discuss/1248136/python3-o(n-logn)-divide-and-conquer-method-with-detailed-comments | class Solution:
def getSkyline(self, buildings: List[List[int]]) -> List[List[int]]:
# base case:
if len(buildings) == 1:
return [[buildings[0][0], buildings[0][2]], [buildings[0][1], 0]]
# prepare to divide the buildings into two parts
left, right = 0, len(buildings) - 1
mid = left + (right - left) // 2
# recuesive case:
left_skyline = self.getSkyline(buildings[0:mid + 1])
right_skyline = self.getSkyline(buildings[mid + 1:])
# merge the left and the right skyline
return self.merge_skyline(left_skyline, right_skyline)
def merge_skyline(self, left: List[List[int]], right: List[List[int]]) -> List[List[int]]:
# index of the left and right buildings
i, j = 0, 0
# height of the left and right buildings
left_y, right_y = 0, 0
skyline = []
# while traverse both the left and right building
while i < len(left) and j < len(right):
# choose the building with the smaller x coodinate to be the added to the skyline
skyline_x = min(left[i][0], right[j][0])
# if the position in the left building's x coordinate is smaller than the right one
if left[i][0] < right[j][0]:
# the height of the left building
left_y = left[i][1]
# if not the first right building. (to avoid right[-1][1] out of index)
if j > 0:
right_y = right[j - 1][1]
skyline_y = max(left_y, right_y)
i += 1
# similar to the smaller case:
elif left[i][0] > right[j][0]:
right_y = right[j][1]
if i > 0:
left_y = left[i - 1][1]
skyline_y = max(left_y, right_y)
j += 1
# if the x coodinates are the same, just get the higher y coordinate and both move to the next point
else:
left_y = left[i][1]
right_y = right[j][1]
skyline_y = max(left_y, right_y)
i += 1
j += 1
# if skyline empty
if not skyline:
last_max = 0
else:
last_max = skyline[-1][1]
# if the current height is not equal to the last height, add it to the skyline
if skyline_y != last_max:
skyline.append([skyline_x, skyline_y])
# append what's left in the list left or right which is already the skyline
skyline.extend(left[i:] or right[j:])
return skyline | the-skyline-problem | python3 o(n logn) divide and conquer method with detailed comments | holmesmoon | 1 | 278 | the skyline problem | 218 | 0.416 | Hard | 3,863 |
https://leetcode.com/problems/the-skyline-problem/discuss/2644004/Python3-Wow-That-Was-Fun | class Solution:
def getSkyline(self, buildings: List[List[int]]) -> List[List[int]]:
bc = 0
b = []
m = 0
for [li, ri, hi] in buildings:
b.append((li, hi, bc))
b.append((ri, 0, bc))
m = max(ri, m)
bc += 1
b.sort()
b.append((m+10**6, 0, -1))
deleted = set()
cb = [(0, -2)]
j = 0
le = 0
outp = []
i = 0
while i < m + 1:
new_deletion = False
while b[j][0] <= i:
p, e, build = b[j]
j += 1
if e == 0:
deleted.add(build)
new_deletion = True
else:
heappush(cb, (-e, build))
if new_deletion:
while cb[0][1] in deleted:
heappop(cb)
cu = -cb[0][0]
if cu!=le:
le=cu
outp.append([i, le])
i = b[j][0]
return outp | the-skyline-problem | Python3 Wow That Was Fun | godshiva | 0 | 12 | the skyline problem | 218 | 0.416 | Hard | 3,864 |
https://leetcode.com/problems/the-skyline-problem/discuss/2643773/Python-Sorting-Heap-Two-Pointers | class Solution:
def getSkyline(self, buildings: List[List[int]]) -> List[List[int]]:
result = []
cur = defaultdict(int)
heights = []
heapq.heapify(heights)
buildings.sort(key=lambda x: (x[0], -x[2]))
ends = sorted(buildings, key=lambda x: (x[1], x[2]))
# two pointers
p_beg, p_end = 0, 0
while p_end < len(buildings):
# check for the last
if p_beg < len(buildings):
beg = buildings[p_beg]
else:
beg = [float('inf')]
end = ends[p_end]
if beg[0] <= end[1]:
p_beg += 1
height = beg[2]
cur[height] += 1
if cur[height] > 1:
continue
if not heights or -heights[0] < height:
result.append([beg[0], height])
heapq.heappush(heights, -height)
else:
p_end += 1
height = end[2]
cur[height] -= 1
if cur[height] > 0:
continue
if -heights[0] == height:
heapq.heappop(heights)
while heights and cur[-heights[0]] == 0:
heapq.heappop(heights)
result.append([end[1], 0 if not heights else -heights[0]])
return result | the-skyline-problem | Python, Sorting, Heap, Two Pointers | sadomtsevvs | 0 | 12 | the skyline problem | 218 | 0.416 | Hard | 3,865 |
https://leetcode.com/problems/the-skyline-problem/discuss/2643176/Python-3-simple-direct-approach-with-no-heap-or-other-imported-functions | class Solution:
def getSkyline(self, buildings: List[List[int]]) -> List[List[int]]:
points = []
for i in buildings:
points.append([i[0], i[2], 1])
points.append([i[1], i[2], 0])
points.sort(key = lambda x : [x[0], -x[1], -x[2]] )
#print(points)
ans = []
mx = [0]
for i in points:
if(i[-1] == 1):
if(i[1] > max(mx)):
ans.append([i[0],i[1]])
mx.append(i[1])
elif(i[-1] == 0):
if(i[1] == max(mx) and mx.count(i[1]) == 1 ):
mx.remove(i[1])
ans.append([i[0],max(mx)])
else:
mx.remove(i[1])
n = len(ans)
i = 1
while(i < n):
if(ans[i][0] == ans[i-1][0]):
del ans[i-1]
i -=1
n -=1
i +=1
return(ans) | the-skyline-problem | Python 3 simple direct approach with no heap or other imported functions | user2800NJ | 0 | 14 | the skyline problem | 218 | 0.416 | Hard | 3,866 |
https://leetcode.com/problems/the-skyline-problem/discuss/2641072/PYTHON-SOLUTION-oror-EASY-TO-UNDERSTAND-oror-SIMPLE-SOLUTION | class Solution:
def getSkyline(self, buildings: List[List[int]]) -> List[List[int]]:
height = []
for i,j,k in buildings:
height.append([i,-k])
height.append([j,k])
height_sorted = sorted(height)
current_height = 0
ans = []
stack = [0]
for i,j in height_sorted:
current_height = max(stack)
#STARTING RECTANGLE
if j<0 and abs(j)>current_height:
stack.append(-j)
ans.append([i,max(stack)])
# print(-j)
elif j<0:
stack.append(-j)
elif j>0:
stack.remove(j)
if current_height!=max(stack):
ans.append([i,max(stack)])
return ans | the-skyline-problem | PYTHON SOLUTION || EASY TO UNDERSTAND || SIMPLE SOLUTION | Airodragon | 0 | 49 | the skyline problem | 218 | 0.416 | Hard | 3,867 |
https://leetcode.com/problems/the-skyline-problem/discuss/2395544/python-max-heap | class Solution:
def getSkyline(self, buildings: List[List[int]]) -> List[List[int]]:
stack = []
ans = []
while buildings or stack:
if not stack or(buildings and stack[0][2]>=buildings[0][0]):
nb = buildings.pop(0)#Add new building
heapq.heappush(stack, (-nb[2], nb[0],nb[1]))
while buildings and buildings[0][0]==nb[0]: #Add all buildings starging with the same x coordinate
nb = buildings.pop(0)
heapq.heappush(stack, (-nb[2], nb[0],nb[1]))
if not ans or -stack[0][0]!= ans[-1][1]:
ans.append([stack[0][1], -stack[0][0]])#Add a point to the answers when the newly add building expands the skyline
else:#stack is empty or the next building is not overlapping, updating the right part
pb = heapq.heappop(stack) #previous highest
while stack:
if stack[0][2]<=pb[2]:
heapq.heappop(stack)#delete buildings that are covered
else:
if -stack[0][0]!= ans[-1][1]:
ans.append([pb[2], -stack[0][0]])
break
if not stack:#add the bottom point
ans.append([pb[2], 0])
return ans | the-skyline-problem | python max heap | li87o | 0 | 96 | the skyline problem | 218 | 0.416 | Hard | 3,868 |
https://leetcode.com/problems/the-skyline-problem/discuss/955076/The-Skyline-Problem-or-python3-Divide-and-Conquer | class Solution:
def getSkyline(self, buildings: List[List[int]]) -> List[List[int]]:
if not buildings:
return []
if len(buildings) == 1:
return [[buildings[0][0], buildings[0][2]],[buildings[0][1], 0]]
mid = (len(buildings)-1) // 2
left = self.getSkyline(buildings[0:mid+1])
right = self.getSkyline(buildings[mid+1:])
return self.merge(left, right)
def merge(self, left, right):
i = j = h1 = h2 = 0
ret = []
while i < len(left) and j < len(right):
if left[i][0] < right[j][0]:
h1 = left[i][1]
new = [left[i][0], max(h1, h2)]
if not ret or ret[-1][1] != new[1]:
ret.append(new)
i += 1
elif left[i][0] > right[j][0]:
h2 = right[j][1]
new = [right[j][0], max(h1, h2)]
if not ret or ret[-1][1]!=new[1]:
ret.append(new)
j+=1
else:
h1 = left[i][1]
h2 = right[j][1]
new = [right[j][0], max(h1, h2)]
if not ret or ret[-1][1] != new[1]:
ret.append([right[j][0],max(h1, h2)])
i += 1
j += 1
while i < len(left):
if not ret or ret[-1][1] != left[i][1]:
ret.append(left[i][:])
i+=1
while j < len(right):
if not ret or ret[-1][1] != right[j][1]:
ret.append(right[j][:])
j+=1
return ret | the-skyline-problem | The Skyline Problem | python3 Divide and Conquer | hangyu1130 | -1 | 152 | the skyline problem | 218 | 0.416 | Hard | 3,869 |
https://leetcode.com/problems/contains-duplicate-ii/discuss/2463150/Very-Easy-oror-100-oror-Fully-Explained-oror-Java-C%2B%2B-Python-Javascript-Python3-(Using-HashSet) | class Solution:
def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
# Create hset for storing previous of k elements...
hset = {}
# Traverse for all elements of the given array in a for loop...
for idx in range(len(nums)):
# If duplicate element is present at distance less than equal to k, return true...
if nums[idx] in hset and abs(idx - hset[nums[idx]]) <= k:
return True
hset[nums[idx]] = idx
# If no duplicate element is found then return false...
return False | contains-duplicate-ii | Very Easy || 100% || Fully Explained || Java, C++, Python, Javascript, Python3 (Using HashSet) | PratikSen07 | 45 | 3,400 | contains duplicate ii | 219 | 0.423 | Easy | 3,870 |
https://leetcode.com/problems/contains-duplicate-ii/discuss/2727788/Python's-Simple-and-Easy-to-Understand-Solutionor-O(n)-Solution-or-99-Faster | class Solution:
def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
# Create dictionary for Lookup
lookup = {}
for i in range(len(nums)):
# If num is present in lookup and satisfy the condition return True
if nums[i] in lookup and abs(lookup[nums[i]]-i) <= k:
return True
# If num is not present in lookup then add it to lookup
lookup[nums[i]] = i
return False | contains-duplicate-ii | ✔️ Python's Simple and Easy to Understand Solution| O(n) Solution | 99% Faster 🔥 | pniraj657 | 11 | 1,100 | contains duplicate ii | 219 | 0.423 | Easy | 3,871 |
https://leetcode.com/problems/contains-duplicate-ii/discuss/381965/Python-solutions | class Solution:
def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
positions = {}
for idx, num in enumerate(nums):
if num in positions and (idx - positions[num] <= k):
return True
positions[num] = idx
return False | contains-duplicate-ii | Python solutions | amchoukir | 7 | 1,500 | contains duplicate ii | 219 | 0.423 | Easy | 3,872 |
https://leetcode.com/problems/contains-duplicate-ii/discuss/381965/Python-solutions | class Solution:
def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
rolling_window = set()
for idx, num in enumerate(nums):
if idx > k:
rolling_window.remove(nums[idx-k-1])
if num in rolling_window:
return True
rolling_window.add(num)
return False | contains-duplicate-ii | Python solutions | amchoukir | 7 | 1,500 | contains duplicate ii | 219 | 0.423 | Easy | 3,873 |
https://leetcode.com/problems/contains-duplicate-ii/discuss/1631026/easy-solution-python | class Solution:
def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
if len(set(nums)) == len(nums):
return False
for i in range(len(nums)):
if len(nums[i:i+k+1])!=len(set(nums[i:i+k+1])):
return True
return False | contains-duplicate-ii | easy solution python | diksha_choudhary | 6 | 758 | contains duplicate ii | 219 | 0.423 | Easy | 3,874 |
https://leetcode.com/problems/contains-duplicate-ii/discuss/1364843/Easy-to-understand | class Solution:
def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
if len(set(nums)) == len(nums):
return False
for i in range(len(nums)):
if len(set(nums[i : i+k+1])) < len(nums[i : i+k+1]):
return True
return False | contains-duplicate-ii | Easy to understand | samirpaul1 | 6 | 513 | contains duplicate ii | 219 | 0.423 | Easy | 3,875 |
https://leetcode.com/problems/contains-duplicate-ii/discuss/2189626/Python3-Sliding-Window | class Solution:
def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
l = set()
for i in range(len(nums)):
if len(l) >= k+1:
l.remove(nums[i-k-1]) # remove left-most elem
if nums[i] in l:
return True
l.add(nums[i])
return False | contains-duplicate-ii | Python3 Sliding Window | alapha23 | 5 | 324 | contains duplicate ii | 219 | 0.423 | Easy | 3,876 |
https://leetcode.com/problems/contains-duplicate-ii/discuss/1015739/Easy-and-Clear-Solution-Python-3 | class Solution:
def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
if len(nums)<2 :
return False
if k>=len(nums):
return len(set(nums))<len(nums)
aux=set(nums[0:k+1])
if len(aux)!=k+1:
return True
for i in range(1,len(nums)-k):
aux.remove(nums[i-1])
aux.add(nums[i+k])
if len(aux)!=k+1:
return True
return False | contains-duplicate-ii | Easy & Clear Solution Python 3 | moazmar | 5 | 1,100 | contains duplicate ii | 219 | 0.423 | Easy | 3,877 |
https://leetcode.com/problems/contains-duplicate-ii/discuss/2200965/Python3-Easy-to-Understand-or-Dictionary | class Solution:
def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
seen = {}
for i in range(len(nums)):
if nums[i] in seen and abs(i - seen[nums[i]]) <= k:
return True
seen[nums[i]] = i
return False | contains-duplicate-ii | ✅Python3 Easy to Understand | Dictionary | thesauravs | 4 | 137 | contains duplicate ii | 219 | 0.423 | Easy | 3,878 |
https://leetcode.com/problems/contains-duplicate-ii/discuss/549053/Python-simple-solution-72-ms-faster-than-90.80 | class Solution(object):
def containsNearbyDuplicate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: bool
"""
if len(nums) == len(set(nums)):
return False
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
if nums[i] == nums[j]:
if j - i <= k:
return True
return False | contains-duplicate-ii | Python simple solution 72 ms, faster than 90.80% | hemina | 4 | 798 | contains duplicate ii | 219 | 0.423 | Easy | 3,879 |
https://leetcode.com/problems/contains-duplicate-ii/discuss/343138/Solution-in-Python-3-(beats-~95)-(very-short) | class Solution:
def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
N = {}
for i,n in enumerate(nums):
if n in N and i - N[n] <= k: return True
N[n] = i
return False
- Python 3
- Junaid Mansuri | contains-duplicate-ii | Solution in Python 3 (beats ~95%) (very short) | junaidmansuri | 3 | 601 | contains duplicate ii | 219 | 0.423 | Easy | 3,880 |
https://leetcode.com/problems/contains-duplicate-ii/discuss/2729337/Python-most-easy | class Solution:
def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
x = {}
for i in range(len(nums)):
if nums[i] in x:
if i - x[nums[i]] <= k:
return True
else:
x[nums[i]] = i
else:
x[nums[i]] = i
return False | contains-duplicate-ii | Python most easy | codewithsonukumar | 2 | 186 | contains duplicate ii | 219 | 0.423 | Easy | 3,881 |
https://leetcode.com/problems/contains-duplicate-ii/discuss/1981958/PYTHON-3-EASY-SOLUTION | class Solution:
def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
if(len(set(nums))==len(nums)): #checking if duplicates exist.
return(False)
i=0
while(i<len(nums)-1):
if(len(set(nums[i:i+k+1]))!=len(nums[i:i+k+1])):
return(True)
i+=1
return(False) | contains-duplicate-ii | PYTHON 3 EASY SOLUTION | saibackinaction1 | 2 | 465 | contains duplicate ii | 219 | 0.423 | Easy | 3,882 |
https://leetcode.com/problems/contains-duplicate-ii/discuss/1848798/python-easy-noob-solution-97 | class Solution:
def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
hash = {}
for index,num in enumerate(nums):
if num in hash and index-hash[num]<=k:
return True
hash[num] = index
return False | contains-duplicate-ii | python easy noob solution 97% | Brillianttyagi | 2 | 254 | contains duplicate ii | 219 | 0.423 | Easy | 3,883 |
https://leetcode.com/problems/contains-duplicate-ii/discuss/1824677/Python-Easiest-Solution-90.12-Faster-Beg-to-Adv-Hashmap | class Solution:
def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
if len(nums) == len(set(nums)):
return False
for i in range(len(nums)):
for j in range(i+1, len(nums)):
if i != j and nums[i] == nums[j] and abs(i - j) <= k:
return True
return False | contains-duplicate-ii | Python Easiest Solution, 90.12 % Faster, Beg to Adv, Hashmap | rlakshay14 | 2 | 210 | contains duplicate ii | 219 | 0.423 | Easy | 3,884 |
https://leetcode.com/problems/contains-duplicate-ii/discuss/1824677/Python-Easiest-Solution-90.12-Faster-Beg-to-Adv-Hashmap | class Solution:
def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
hashmap = {}
for i,v in enumerate(nums):
if v in hashmap and i - hashmap[v] <= k:
return True
hashmap[v] = i
return False | contains-duplicate-ii | Python Easiest Solution, 90.12 % Faster, Beg to Adv, Hashmap | rlakshay14 | 2 | 210 | contains duplicate ii | 219 | 0.423 | Easy | 3,885 |
https://leetcode.com/problems/contains-duplicate-ii/discuss/1684158/Python-andand-Kotlin-solutions-%2B-explanation-(self-made-BST) | class Solution:
# O(n) Space & O(n) Time
def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
"""
1. why do we need hashtable? => i & j can be any indicies, not simply adjacent ones
2. why do we put `curr_num` in ht after? => we need to find if two DIFFERENT
idxs have the same value
"""
ht = {}
for i in range(len(nums)):
curr_num = nums[i]
if curr_num in ht: # means values are similar
idx = ht[curr_num] # get that another index
if abs(i - idx) <= k:
return True
ht[curr_num] = i
return False
# tree
def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
"""
Use BST + use Height Balanced feature
"""
tree = BST(nums[0])
for i in range(1, len(nums)):
num = nums[i]
if tree.search(num) and k != 0:
# second check is for the following:
# [1,2,1]
# 0
return True
tree.insert(num)
tree.length += 1
if tree.length > k:
# we need to move this window and remove in FIFO style
tree.remove(nums[i - k])
tree.length -= 1
return False
class BST:
def __init__(self, root, left=None, right=None):
self.root = root
self.left = left
self.right = right
self.length = 1
def search(self, value):
curr = self
while curr:
if curr.root > value:
curr = curr.left
elif curr.root < value:
curr = curr.right
else:
return True
return False
def insert(self, value):
if value < self.root:
if self.left is None:
self.left = BST(value)
return
else:
self.left.insert(value)
else:
if self.right is None:
self.right = BST(value)
return
else:
self.right.insert(value)
def remove(self, value, parent=None):
# cases to deal with
# 1. if both childs are in place
# 2. if no parent (find at first try) + only one child (when both above is dealth with)
# 3. if parent exists, but only 1 child
curr = self
while curr:
if curr.root > value:
parent = curr
curr = curr.left
elif curr.root < value:
parent = curr
curr = curr.right
else:
if curr.left is not None and curr.right is not None:
curr.root = curr.right.minFind() # change itself happens here
curr.right.remove(curr.root, curr) # remove smallest from the right tree as we put it in the root
elif parent is None: # means we found the value instantly without if/elif + only one child
if curr.left is not None:
curr.root = curr.left.root
curr.right = curr.left.right
curr.left = curr.left.left # assign last as you'll need it
elif curr.right is not None:
curr.root = curr.right.root
curr.left = curr.right.left
curr.right = curr.right.right # assign last as you'll need it
else:
pass # no children
elif parent.left == curr:
# 5
# /
#4 this to be removed
# \
# 3
parent.left = curr.left if curr.left is not None else curr.right
elif parent.right == curr:
parent.right = curr.left if curr.left is not None else curr.right
break
return self
def minFind(self):
curr = self
while curr.left:
curr = curr.left
return curr.root | contains-duplicate-ii | 二つのPython && 二つのKotlin solutions + explanation (self-made BST) | SleeplessChallenger | 2 | 127 | contains duplicate ii | 219 | 0.423 | Easy | 3,886 |
https://leetcode.com/problems/contains-duplicate-ii/discuss/1447805/Python3-Faster-Than-98.66-Easy-Solution-With-Explanation | class Solution:
def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
d = {}
for i in range(len(nums)):
if nums[i] not in d:
d[nums[i]] = i
else:
if i - d[nums[i]] <= k:
return True
else:
d[nums[i]] = i
return False | contains-duplicate-ii | Python3 Faster Than 98.66%, Easy Solution With Explanation | Hejita | 2 | 338 | contains duplicate ii | 219 | 0.423 | Easy | 3,887 |
https://leetcode.com/problems/contains-duplicate-ii/discuss/1218124/Python3Easy-understanding-solution-use-dict | class Solution:
def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
dic = {}
for idx, num in enumerate(nums):
if num in dic and idx - dic[num] <= k:
return True
dic[num] = idx
return False | contains-duplicate-ii | 【Python3】Easy understanding solution use dict | qiaochow | 2 | 97 | contains duplicate ii | 219 | 0.423 | Easy | 3,888 |
https://leetcode.com/problems/contains-duplicate-ii/discuss/613239/Python-Solution-98ms-Easy-to-Understand-Explained | class Solution:
def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
d = dict()
for i in range(0,len(nums)):
if nums[i] in d:
if abs(d[nums[i]]-i) <= k:
return True
else:
d[nums[i]] = i
else:
d[nums[i]]=i
return False | contains-duplicate-ii | Python Solution 98ms [Easy to Understand] Explained | code_zero | 2 | 202 | contains duplicate ii | 219 | 0.423 | Easy | 3,889 |
https://leetcode.com/problems/contains-duplicate-ii/discuss/2728597/Python-(using-dictionary) | class Solution:
def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
dict = {}
for i in range(len(nums)):
if nums[i] in dict:
if i - dict[nums[i]] <= k: return True
else: dict[nums[i]] = i
else: dict[nums[i]] = i
return False | contains-duplicate-ii | Python (using dictionary) | anandanshul001 | 1 | 72 | contains duplicate ii | 219 | 0.423 | Easy | 3,890 |
https://leetcode.com/problems/contains-duplicate-ii/discuss/2728505/Very-simple-solution-in-CPP-and-Python | class Solution:
def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
E = dict()
for i in range(len(nums)):
n = nums[i]
if n in E:
if abs(E[n] - i) <= k:
return True
E[n] = i
return False | contains-duplicate-ii | Very simple solution in CPP & Python | nuoxoxo | 1 | 64 | contains duplicate ii | 219 | 0.423 | Easy | 3,891 |
https://leetcode.com/problems/contains-duplicate-ii/discuss/2728305/Sweet-solution.-Beats-91 | class Solution:
def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
hashMap = {}
for i, n in enumerate(nums):
if n in hashMap:
diff = i - hashMap[n]
if diff <= k:
return True
hashMap[n] = i
return False | contains-duplicate-ii | Sweet solution. Beats 91% | sukumar-satapathy | 1 | 101 | contains duplicate ii | 219 | 0.423 | Easy | 3,892 |
https://leetcode.com/problems/contains-duplicate-ii/discuss/2728134/Python-or-Dict-and-deque-solution-or-O(n) | class Solution:
def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
stat, q = defaultdict(int), deque([])
for num in nums:
stat[num] += 1
q.append(num)
if stat[num] > 1:
return True
if len(q) == k + 1:
stat[q.popleft()] -= 1
return False | contains-duplicate-ii | Python | Dict and deque solution | O(n) | LordVader1 | 1 | 30 | contains duplicate ii | 219 | 0.423 | Easy | 3,893 |
https://leetcode.com/problems/contains-duplicate-ii/discuss/2234782/Python-HashMap-Beats-75 | class Solution:
def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
d = {}
prev = 0
for i in range(len(nums)):
if nums[i] not in d:
d[nums[i]] = i
else:
prev = d[nums[i]] # Keep track of the previous index
d[nums[i]] = i
if abs(i - prev) <=k:
return True
return False | contains-duplicate-ii | Python HashMap Beats 75% | theReal007 | 1 | 91 | contains duplicate ii | 219 | 0.423 | Easy | 3,894 |
https://leetcode.com/problems/contains-duplicate-ii/discuss/2210474/Easy-Python-Solution-oror-O(n) | class Solution:
def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
obj = {}
for i, j in enumerate(nums):
if j in obj and i - obj[j] <= k:
return True
else:
obj[j] = i
return False | contains-duplicate-ii | Easy Python Solution || O(n) | MorgDzh | 1 | 87 | contains duplicate ii | 219 | 0.423 | Easy | 3,895 |
https://leetcode.com/problems/contains-duplicate-ii/discuss/2192641/Python-solution | class Solution:
def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
ones = []
if len(set(nums)) == len(nums):
return False
for i in range(0,len(nums)):
if nums[i] in ones:
continue
if nums.count(nums[i]) == 1:
ones.append(nums[i])
continue
for j in range(i+1,len(nums)):
if nums[i] == nums[j] and abs(i-j) <= k:
return True
else:
return False | contains-duplicate-ii | Python solution | StikS32 | 1 | 165 | contains duplicate ii | 219 | 0.423 | Easy | 3,896 |
https://leetcode.com/problems/contains-duplicate-ii/discuss/1605516/Python-Hashmap-Easy-Small-Solution | class Solution:
def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
hashmap={}
i=0
while(i<len(nums)):
current=nums[i]
if(current in hashmap and i-hashmap[current]<=k):
return True
else:
hashmap[current]=i
i+=1
return False
``` | contains-duplicate-ii | Python Hashmap Easy Small Solution | akshattrivedi9 | 1 | 185 | contains duplicate ii | 219 | 0.423 | Easy | 3,897 |
https://leetcode.com/problems/contains-duplicate-ii/discuss/1488297/python3-O(n)-Solution | class Solution:
def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
dct = dict()
for indx,val in enumerate(nums):
if val in dct:
if indx-dct[val]<=k:
return True
dct[val]=indx
else:
dct[val]=indx
return False | contains-duplicate-ii | [python3] O(n) Solution | _jorjis | 1 | 203 | contains duplicate ii | 219 | 0.423 | Easy | 3,898 |
https://leetcode.com/problems/contains-duplicate-ii/discuss/1243656/Python-Three-approaches | class Solution:
def containsNearbyDuplicate(self, nums: List[int], target: int) -> bool:
#Method 3: add index to dict and then use the two-sum logic(lookback and check if condition is satisfied)
d = {}
for k,v in enumerate(nums):
if v in d and k - d[v] <= target:
return True
d[v] = k
return False
#Method 2: Dict plus combinations - Mem Limit Exceeded
# d = defaultdict(list)
# for i in range(len(nums)):
# d[nums[i]] += [i]
# print(d)
# for k in d.keys():
# l = len(d[k])
# if l >= 2:
# from itertools import combinations
# for combo in list(combinations(d[k],2)):
# if abs(combo[0] - combo[1]) <= target:
# return True
# return False
#Method 1: Brute Force - TLE
# for i in range(len(nums)):
# for j in range(i, len(nums)):
# if nums[i] != nums[j]:
# continue
# else:
# if j != i and abs(i - j) <= k:
# # print(i,j)
# return True
# return False | contains-duplicate-ii | Python - Three approaches | mehrotrasan16 | 1 | 327 | contains duplicate ii | 219 | 0.423 | Easy | 3,899 |
Subsets and Splits