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/shortest-palindrome/discuss/739903/Python3-2-line-brute-force-and-9-line-KMP | class Solution:
def shortestPalindrome(self, s: str) -> str:
ss = s + "#" + s[::-1]
lps = [0]*len(ss) #longest prefix suffix array
k = 0
for i in range(1, len(ss)):
while k and ss[k] != ss[i]:
k = lps[k-1]
if ss[k] == ss[i]: k += 1
lps[i] = k
return s[k:][::-1] + s | shortest-palindrome | [Python3] 2-line brute force & 9-line KMP | ye15 | 1 | 92 | shortest palindrome | 214 | 0.322 | Hard | 3,700 |
https://leetcode.com/problems/shortest-palindrome/discuss/2847682/python | class Solution:
def shortestPalindrome(self, s: str) -> str:
if len(s) in [0,1]:
return s
n = len(s)//2
if len(s)%2==0:
n-=1
for i in range(n,0,-1):
if 2*(i+1)<= len(s) and s[:i+1][::-1] == s[i+1:2*(i+1)]:
return s[2*(i+1) :][::-1] + s
elif s[:i+1][::-1] == s[i:(2 *i)+1]:
return s[(2 *i)+1 :][::-1] + s
for i in range(1,len(s)):
if s[i] != s[0] :
return s[i:][::-1] + s | shortest-palindrome | python | ABDRAHIMHA2001 | 0 | 1 | shortest palindrome | 214 | 0.322 | Hard | 3,701 |
https://leetcode.com/problems/shortest-palindrome/discuss/2704009/sasta-python-code-oror | class Solution:
def shortestPalindrome(self, s: str) -> str:
def palin(st,j):
i=0
while i<j:
if st[i]!=st[j]:
return False
i+=1
j-=1
return True
if len(s)==0:
return ""
if s.count(s[0])==40000:
pass
#return last testcase ans it will rrun upto last test case
for i in range(len(s)-1,-1,-1):
if palin(s,i):
return s[i+1:][::-1]+s | shortest-palindrome | sasta python code || | narendra_036 | 0 | 9 | shortest palindrome | 214 | 0.322 | Hard | 3,702 |
https://leetcode.com/problems/shortest-palindrome/discuss/2677831/Brute-force-in-Python-but-faster-than-half | class Solution:
def shortestPalindrome(self, s: str) -> str:
n = len(s)
if n == 1:
return s
for pivot in range((n + 1) // 2, -1, -1):
pre = s[:pivot]
suf1 = s[pivot:pivot+pivot][::-1]
suf2 = s[pivot-1:pivot+pivot-1][::-1]
if pre == suf1:
return s[pivot:][::-1] + s[pivot:]
elif pre == suf2:
return s[pivot-1:][::-1] + s[pivot:]
return s[::-1] + s[1:] | shortest-palindrome | Brute force in Python, but faster than half | metaphysicalist | 0 | 28 | shortest palindrome | 214 | 0.322 | Hard | 3,703 |
https://leetcode.com/problems/shortest-palindrome/discuss/2564711/Simple-python-solution-and-easy-to-understand-explaination | class Solution:
def shortestPalindrome(self, s: str) -> str:
end = len(s)-1
while(end>0):
if s[0] == s[end]:
#Check if s[0:end+1] is palindrome
if end % 2 == 0: # s[0:end+1] has odd digits
if s[0:end//2] == s[end:end//2:-1]:
return s[:end:-1]+s
elif end % 2 == 1: # s[0:end+1] has even digits
if s[0:end//2+1] == s[end:end//2:-1]:
return s[:end:-1]+s
end -= 1
return s[:end:-1]+s | shortest-palindrome | Simple python solution and easy-to-understand explaination | guojunfeng1998 | 0 | 77 | shortest palindrome | 214 | 0.322 | Hard | 3,704 |
https://leetcode.com/problems/shortest-palindrome/discuss/2177355/Simple-Iterative-Solution-O(n)-Python3 | class Solution:
def shortestPalindrome(self, s: str) -> str:
# filter out edge cases for strings we need to check
if len(s) <= 1:
return s
elif len(s) == 2:
if s[0] == s[1]:
return s
else:
return str(s[1]) + s
# will be populated in reverse order
# (add to the left of s to make a palindrome)
additions = ""
# here, we are optimizing the number of steps searched
# by checking for the longest palindromes first
# (a valid palindrome has to be a substring starting at s[0])
# so we go from right to left
# if the string we are looking at has odd length, then we take the left and right and skip the middle, and check for palindrome
# if the string we are looking at has even length, then we simply split the string in half
for i in range(len(s)-1, 0, -1):
if i == 1:
if s[i] == s[0]:
# first two letters is palindrome
break
else:
additions += str(s[i])
# break (basically)
elif i % 2 == 0: # i is on even index
# this means that s[:i] actually has a odd length
left = s[0:i//2]
right = s[ i : i // 2 : -1]
if left == right:
break
# found a palindrome, ends loop short
else:
additions += str(s[i])
else: # is odd position
# s[:i] has even length
left = s[0:((i+1)//2)]
right = s[ i : (i-1)//2 : -1]
if left == right:
break
else:
additions += str(s[i])
# at every step we add a letter to the letters to add if we fail to find a palindrome
return additions + s | shortest-palindrome | Simple Iterative Solution O(n) - Python3 | ginomcfino | 0 | 73 | shortest palindrome | 214 | 0.322 | Hard | 3,705 |
https://leetcode.com/problems/shortest-palindrome/discuss/1727335/python3-easy-solution-but-should-I-use-more-complicated-method-like-KMP | class Solution:
def shortestPalindrome(self, s: str) -> str:
if s=="":
return ""
reverse_s = ''.join(list(reversed(s)))
for i in range(len(s)):
if reverse_s[i:] == s[0:len(s)-i]:
return reverse_s[0:i]+s | shortest-palindrome | python3 easy solution but, should I use more complicated method like KMP? | njuasxzg | 0 | 122 | shortest palindrome | 214 | 0.322 | Hard | 3,706 |
https://leetcode.com/problems/shortest-palindrome/discuss/1683203/Python-3-Rabin-Karp-%2B-custom-hash-function-constant-space-and-average-liniar-time | class Solution:
def shortestPalindrome(self, s: str) -> str:
n = len(s)
# The idea is to find the longest prefix in string S that is a palindrome. To solve this, apply Rabin-Karp
# algorithm with a custom rolling hash function. Once the longest palindrome prefix has been found, just add the
# reversed suffix at the beginning of string S to get the output string.
#
# The Rabin-Karp algorithm is applied as follows:
# 1. Compute the hash of the original and the reversed string S and assign these values to variables left_hash
# and right_hash respectively.
# 2. Create a loop that will iterate until both left and right hashes are equal and the strings corresponding to
# these hashes are equal (meaning a palindrome prefix has been found).
# 3. On each iteration:
# a. From left_hash remove one character at a time from the end of the string S and compute the new hash.
# b. From right_hash remove one character at a time from the beginning of the string S and compute the new
# hash.
# 4. Build and return the output string.
#
# Custom hash function formula (simple, but good enough for the purpose of this problem):
# H = c_1 * 1 + c_2 * 2 + c_3 * 3 + ... + c_k * k
#
# Examples:
# H("abcd") = 97 * 1 + 98 * 2 + 99 * 3 + 100 * 4 = 990
# H("dcba") = 97 * 4 + 98 * 3 + 99 * 2 + 100 * 1 = 980
#
# Entire algorithm time complexity: O(n) on average (spurious hits)
# Space complexity: O(1)
# Leetcode best runtime is 59 ms with 14.3 MB memory usage
# Factorial prime number for modulo:
# 1. https://en.wikipedia.org/wiki/Factorial_prime
# 2. https://math.stackexchange.com/questions/1310813/why-modulo-prime-prefered-over-modulo-composite
modulo = 479001599
# Helper function to check if the prefix of string S with a given length is a palindrome
def is_prefix_palindrome(length: int) -> bool:
return reduce(lambda acc, i: acc & (s[i] == s[length - i - 1]), range(length // 2), True)
# Compute initial hashes. These values might overflow 32-bit integer values, hence modulo is applied
left_hash = reduce(lambda acc, val: (acc + val[0] * ord(val[1])) % modulo, enumerate(s, start=1), 0)
right_hash = reduce(lambda acc, val: (acc + val[0] * ord(val[1])) % modulo, enumerate(reversed(s), start=1), 0)
prefix_len = n
# Subtrahend will be required for updating the rolling hash for right_hash
subtrahend = sum(ord(c) for c in s)
# Find the longest palindrome prefix
while left_hash != right_hash or not is_prefix_palindrome(prefix_len):
# Character to be removed from both strings
char = s[prefix_len - 1]
# Remove the character from both left_hash and right_hash and compute the new hashes (take into account the
# modulo)
left_hash = (left_hash - ord(char) * prefix_len + modulo) % modulo
right_hash = (right_hash - subtrahend + modulo) % modulo
# Decrement prefix length and update the subtrahend
prefix_len = prefix_len - 1
subtrahend = subtrahend - ord(char)
return s[:prefix_len - n - 1:-1] + s | shortest-palindrome | [Python 3] Rabin-Karp + custom hash function, constant space and average liniar time | corcoja | 0 | 135 | shortest palindrome | 214 | 0.322 | Hard | 3,707 |
https://leetcode.com/problems/shortest-palindrome/discuss/1590060/Python-one-liner | class Solution:
def shortestPalindrome(self, s: str) -> str:
return s[[i for i in range(len(s) - 1, -1, -1) if s[:i] == s[:i][::-1]][0]:][::-1] + s if s != s[::-1] else s | shortest-palindrome | Python one liner | shiv-sj | 0 | 173 | shortest palindrome | 214 | 0.322 | Hard | 3,708 |
https://leetcode.com/problems/shortest-palindrome/discuss/1255373/Python3-solution-using-KMP-algorithm | class Solution:
def shortestPalindrome(self, s: str) -> str:
"""
catacb
catacb#bcatac
0000100012345
basically if we observe catacb, if we just add 1 b in the beginning, it becomes a palindrome.
Easiest way to find that being, what is the prefix, which is also suffix.
If we see catacb#bcatac.
If we remove the common prefix/suffix, if the remainder we append at the beginning of string.
b
it will become bcatacb. Which is a palindrome.
"""
def init_arr(w):
"""
j is the one traversing.
i is the one keeping track of the prefix.
"""
n, i, j = len(w), 0, 1
arr = [0]*n
while j<n:
if w[i]==w[j]:
# if prefix is same as the suffix/
i+=1
arr[j]=i
j+=1
elif i==0:
# if prefix is not same and we reached end of string.
arr[j]=0
j+=1
else:
# we fall back to init_arr, prev index.
i = arr[i-1]
return arr
pal = s+"#"+s[::-1]
table = init_arr(pal)
return s[table[-1]:][::-1]+s | shortest-palindrome | Python3 solution using KMP algorithm | amol1729 | 0 | 108 | shortest palindrome | 214 | 0.322 | Hard | 3,709 |
https://leetcode.com/problems/shortest-palindrome/discuss/483134/Python3-short-simple-recursive-solution-faster-than-92.15 | class Solution:
def shortestPalindrome(self, s: str) -> str:
i,l = 0,len(s)
for j in range(l-1,-1,-1):
if s[i]==s[j]: i+=1
if i==l: return s
return s[i:][::-1] + self.shortestPalindrome(s[:i]) + s[i:] | shortest-palindrome | Python3 short simple recursive solution, faster than 92.15% | jb07 | 0 | 183 | shortest palindrome | 214 | 0.322 | Hard | 3,710 |
https://leetcode.com/problems/kth-largest-element-in-an-array/discuss/2180509/Python-Easy-O(logn)-Space-approach-or-One-liner | class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
n = len(nums)
def partition(l, r, pivot):
pivot_elem=nums[pivot]
nums[r],nums[pivot]=nums[pivot],nums[r]
index=l
for i in range(l, r):
if nums[i]<pivot_elem:
nums[i],nums[index]=nums[index],nums[i]
index+=1
nums[index],nums[r]=nums[r],nums[index]
return index
def quick_select(l,r,kth_index):
if l==r:
return nums[l]
pivot_index=partition(l,r,l)
if pivot_index==kth_index:
return nums[pivot_index]
if kth_index>pivot_index:
return quick_select(pivot_index+1, r, kth_index)
else:
return quick_select(l,pivot_index-1, kth_index)
return quick_select(0, n - 1, n - k) | kth-largest-element-in-an-array | Python Easy O(logn) Space approach | One liner | constantine786 | 24 | 3,300 | kth largest element in an array | 215 | 0.658 | Medium | 3,711 |
https://leetcode.com/problems/kth-largest-element-in-an-array/discuss/2180509/Python-Easy-O(logn)-Space-approach-or-One-liner | class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
return sorted(nums)[-k] | kth-largest-element-in-an-array | Python Easy O(logn) Space approach | One liner | constantine786 | 24 | 3,300 | kth largest element in an array | 215 | 0.658 | Medium | 3,712 |
https://leetcode.com/problems/kth-largest-element-in-an-array/discuss/2182564/Two-Approaches-or-Sorting-or-Min-Heap | class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
nums.sort(reverse=True)
return nums[k-1] | kth-largest-element-in-an-array | Two Approaches | Sorting | Min-Heap | zeus-salazar | 13 | 587 | kth largest element in an array | 215 | 0.658 | Medium | 3,713 |
https://leetcode.com/problems/kth-largest-element-in-an-array/discuss/2182564/Two-Approaches-or-Sorting-or-Min-Heap | class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
minheap=[]
count=0
for num in nums:
heappush(minheap,num)
count+=1
if count>k:
heappop(minheap)
count-=1
return minheap[0] | kth-largest-element-in-an-array | Two Approaches | Sorting | Min-Heap | zeus-salazar | 13 | 587 | kth largest element in an array | 215 | 0.658 | Medium | 3,714 |
https://leetcode.com/problems/kth-largest-element-in-an-array/discuss/2134244/Python-2-best-Solutions-using-Heap-and-Quick-Select | class Solution:
def findKthLargest(self, nums, k):
pivot = nums[0]
left = [num for num in nums if num < pivot]
equal = [num for num in nums if num == pivot]
right = [num for num in nums if num > pivot]
if k <= len(right): return self.findKthLargest(right, k)
elif len(right) < k <= len(right) + len(equal): return equal[0]
else: return self.findKthLargest(left, k - len(right) - len(equal))
# Average Time Complexity: O(N)
# Worst Case Time Complexity: O(N^2)
# Space Complexity: O(N) | kth-largest-element-in-an-array | Python 2 best Solutions using Heap and Quick-Select | samirpaul1 | 7 | 491 | kth largest element in an array | 215 | 0.658 | Medium | 3,715 |
https://leetcode.com/problems/kth-largest-element-in-an-array/discuss/553723/Several-Python-solution-sharing.-w-Study-resource | class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
nums.sort( reverse = True )
return nums[k-1] | kth-largest-element-in-an-array | Several Python solution sharing. [w/ Study resource] | brianchiang_tw | 7 | 1,400 | kth largest element in an array | 215 | 0.658 | Medium | 3,716 |
https://leetcode.com/problems/kth-largest-element-in-an-array/discuss/553723/Several-Python-solution-sharing.-w-Study-resource | class Solution:
def partition(self, nums, left, right):
pivot = nums[left]
l, r = left+1, right
while l <= r:
if nums[l] < pivot and nums[r] > pivot:
nums[l], nums[r] = nums[r], nums[l]
l, r = l+1, r-1
if nums[l] >= pivot:
l += 1
if nums[r] <= pivot:
r -= 1
nums[left], nums[r] = nums[r], nums[left]
return r
def findKthLargest(self, nums: List[int], k: int) -> int:
size = len(nums)
left, right = 0, size-1
while True:
cur_index = self.partition( nums, left, right)
if cur_index > k-1:
right = cur_index -1
elif cur_index < k - 1:
left = cur_index + 1
else:
return nums[ cur_index ] | kth-largest-element-in-an-array | Several Python solution sharing. [w/ Study resource] | brianchiang_tw | 7 | 1,400 | kth largest element in an array | 215 | 0.658 | Medium | 3,717 |
https://leetcode.com/problems/kth-largest-element-in-an-array/discuss/2759090/Python-using-heap | class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
nums=list(map(lambda x:-x,nums))
heapq.heapify(nums)
for i in range(k-1):
heapq.heappop(nums) #Pop minimum from the list
return -heapq.heappop(nums) | kth-largest-element-in-an-array | Python using heap | Jebdeju | 4 | 517 | kth largest element in an array | 215 | 0.658 | Medium | 3,718 |
https://leetcode.com/problems/kth-largest-element-in-an-array/discuss/1371234/Python-Quickselect-template | class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
def partition(left, right, pivot_index):
pivot = nums[pivot_index]
nums[pivot_index], nums[right] = nums[right], nums[pivot_index]
index = left
for i in range(left, right):
if nums[i] < pivot:
nums[index], nums[i] = nums[i], nums[index]
index += 1
nums[right], nums[index] = nums[index], nums[right]
return index
def quick_select(left = 0, right = len(nums)-1):
if left > right: return
pivot_index = random.randint(left, right)
index = partition(left, right, pivot_index)
if index == n_smaller: return
elif index > n_smaller: quick_select(left, index-1)
else: quick_select(index+1, right)
n_smaller = len(nums)-k
quick_select()
return nums[n_smaller] | kth-largest-element-in-an-array | [Python] Quickselect template | soma28 | 4 | 372 | kth largest element in an array | 215 | 0.658 | Medium | 3,719 |
https://leetcode.com/problems/kth-largest-element-in-an-array/discuss/2183958/Python-one-liner-solution-oror-Easy-To-Understand | class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
return sorted(nums,reverse=True)[k-1] | kth-largest-element-in-an-array | ✅Python one-liner solution || Easy-To-Understand | Shivam_Raj_Sharma | 3 | 164 | kth largest element in an array | 215 | 0.658 | Medium | 3,720 |
https://leetcode.com/problems/kth-largest-element-in-an-array/discuss/2180503/Python-Two-Line-Solution | class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
nums.sort()
return nums[-k] | kth-largest-element-in-an-array | Python Two Line Solution | Ritaj_Zamel | 3 | 368 | kth largest element in an array | 215 | 0.658 | Medium | 3,721 |
https://leetcode.com/problems/kth-largest-element-in-an-array/discuss/1633253/Simple-and-straightforward-Python3-implementation-using-heap-with-explanation | class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
# 1. Initialize minheap/priority queue to empty list. (in Python3 all heaps are minheaps by default)
pq = []
# 2. loop through every number in nums
for n in nums:
# 3. push each number n onto our heap pq
heapq.heappush(pq, n)
# 4. if the heap size is greater than k pop the top of the heap which is the min value
if len(pq) > k:
heapq.heappop(pq)
# 5. return the element on the top of our minheap pq[0] which is the k-th largest number
# since our pq will contain the k largest numbers from nums
return pq[0] | kth-largest-element-in-an-array | Simple and straightforward Python3 implementation using heap with explanation | drdill | 3 | 251 | kth largest element in an array | 215 | 0.658 | Medium | 3,722 |
https://leetcode.com/problems/kth-largest-element-in-an-array/discuss/491649/Python-One-Liner-Heap | class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
return min(heapq.nlargest(k, nums)) | kth-largest-element-in-an-array | Python - One Liner - Heap | mmbhatk | 3 | 945 | kth largest element in an array | 215 | 0.658 | Medium | 3,723 |
https://leetcode.com/problems/kth-largest-element-in-an-array/discuss/2403885/Quick-Select-algorithm-easy-to-understand | class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
pivot = random.choice(nums)
bigger = [x for x in nums if x > pivot]
eq = [x for x in nums if x == pivot]
less = [x for x in nums if x < pivot]
if len(bigger) >= k: # all k elements are in the bigger partition
return self.findKthLargest(bigger,k)
elif len(bigger) + len(eq) < k:
return self.findKthLargest(less,k - len(bigger) - len(eq)) # some of the largest elements were in bigger and eq
else:
return eq[0] # all elements in eq are the answer so just take the first one | kth-largest-element-in-an-array | Quick Select algorithm easy to understand | imanhn | 2 | 166 | kth largest element in an array | 215 | 0.658 | Medium | 3,724 |
https://leetcode.com/problems/kth-largest-element-in-an-array/discuss/2484681/Python-(Simple-Approach-and-Beginner-Friendly) | class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
nums = sorted(nums)
return nums[len(nums)-k] | kth-largest-element-in-an-array | Python (Simple Approach and Beginner-Friendly) | vishvavariya | 1 | 191 | kth largest element in an array | 215 | 0.658 | Medium | 3,725 |
https://leetcode.com/problems/kth-largest-element-in-an-array/discuss/2465988/Python-1-line-solution-O(N-log-N) | class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
return sorted(nums)[-k] | kth-largest-element-in-an-array | Python 1 line solution O(N log N) | sezanhaque | 1 | 101 | kth largest element in an array | 215 | 0.658 | Medium | 3,726 |
https://leetcode.com/problems/kth-largest-element-in-an-array/discuss/2181271/Python-59-ms-run-time-or-99.17-faster-one-liner-97-memory-efficient | class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
return sorted(nums,reverse=True)[k-1] | kth-largest-element-in-an-array | Python 59 ms run time | 99.17% faster one liner 97% memory efficient | anuvabtest | 1 | 134 | kth largest element in an array | 215 | 0.658 | Medium | 3,727 |
https://leetcode.com/problems/kth-largest-element-in-an-array/discuss/2180861/Python3-or-very-easy-or-heap-oreasy-to-understand | class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
heap = []
for e in nums:
heappush(heap, -e)
ans= -1
while k:
k-=1
ans = -heappop(heap)
return ans | kth-largest-element-in-an-array | Python3 | very easy | heap |easy to understand | H-R-S | 1 | 53 | kth largest element in an array | 215 | 0.658 | Medium | 3,728 |
https://leetcode.com/problems/kth-largest-element-in-an-array/discuss/2180564/Quickselect-solution-in-Python-and-C%2B%2B | class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
def swap(i, j):
nums[i], nums[j] = nums[j], nums[i]
def find_pivot_idx(l, r):
pivot_idx = (l + r) // 2
swap(pivot_idx, r)
pivot_val = nums[r]
end_of_larger_idx = l - 1
for i in range(l, r):
if nums[i] >= pivot_val:
swap(i, end_of_larger_idx + 1)
end_of_larger_idx += 1
swap(r, end_of_larger_idx + 1)
return end_of_larger_idx + 1
def kth_largest(l, r, k):
pivot_idx = find_pivot_idx(l, r)
if pivot_idx - l + 1 == k:
return nums[pivot_idx]
elif pivot_idx - l + 1 > k:
return kth_largest(l, pivot_idx - 1, k)
else:
return kth_largest(pivot_idx + 1, r, k - (pivot_idx - l + 1))
N = len(nums)
return kth_largest(0, N - 1, k) | kth-largest-element-in-an-array | Quickselect solution in Python and C++ | kryuki | 1 | 48 | kth largest element in an array | 215 | 0.658 | Medium | 3,729 |
https://leetcode.com/problems/kth-largest-element-in-an-array/discuss/2133311/minHeap-solution | class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
if not nums:
return 0
heap = []
for i in nums:
heapq.heappush(heap, i)
if len(heap) > k:
heapq.heappop(heap)
return heapq.heappop(heap) | kth-largest-element-in-an-array | minHeap solution | writemeom | 1 | 88 | kth largest element in an array | 215 | 0.658 | Medium | 3,730 |
https://leetcode.com/problems/kth-largest-element-in-an-array/discuss/1927426/2-lines-of-code-and-97.16-less-memory-usage | class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
nums.sort(reverse=True)
return nums[k - 1] | kth-largest-element-in-an-array | 2 lines of code and 97.16 less memory usage | ankurbhambri | 1 | 64 | kth largest element in an array | 215 | 0.658 | Medium | 3,731 |
https://leetcode.com/problems/kth-largest-element-in-an-array/discuss/1869155/Python-one-line-solution | class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
return sorted(nums, reverse=True)[k-1] | kth-largest-element-in-an-array | Python one line solution | alishak1999 | 1 | 164 | kth largest element in an array | 215 | 0.658 | Medium | 3,732 |
https://leetcode.com/problems/kth-largest-element-in-an-array/discuss/1827506/99.83-Faster-or-Simple-1-line-python-solution | class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
return sorted(nums)[-k] | kth-largest-element-in-an-array | ✔99.83 Faster | Simple 1 line python solution | Coding_Tan3 | 1 | 113 | kth largest element in an array | 215 | 0.658 | Medium | 3,733 |
https://leetcode.com/problems/kth-largest-element-in-an-array/discuss/1822851/best-solution-ever-python-O(Nlogk)-time-O(k)-space-complexity | class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
import heapq
heap = []
for num in nums:
if len(heap)<k:
heapq.heappush(heap,num)
elif num>heap[0]:
heapq.heappushpop(heap,num)
return heapq.heappop(heap) | kth-largest-element-in-an-array | best solution ever , python, O(Nlogk) time, O(k) space complexity | aaronat | 1 | 78 | kth largest element in an array | 215 | 0.658 | Medium | 3,734 |
https://leetcode.com/problems/kth-largest-element-in-an-array/discuss/1645758/One-liner-Python3-solution-Easy-faster-than-96.61-and-memory-usage-less-than-93.31 | class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
return sorted(nums)[len(nums) - k] | kth-largest-element-in-an-array | One-liner Python3 solution - Easy, faster than 96.61% and memory usage less than 93.31% | y-arjun-y | 1 | 175 | kth largest element in an array | 215 | 0.658 | Medium | 3,735 |
https://leetcode.com/problems/kth-largest-element-in-an-array/discuss/1339497/Python-Max-Heap-Solution-Without-Using-a-Library-Function-(93-less-memory) | class Solution:
def __init__(self):
self.heap=[]
self.capacity=0
self.length=0
def findKthLargest(self, nums: List[int], k: int) -> int:
self.capacity=len(nums)
self.heap=[0]*self.capacity
for i in nums:
self.heap[self.length] = i
self.length += 1
self.fixUp(self.length - 1)
for i in range(k):
item=self.remove_heap()
return item
def remove_heap(self):
self.heap[0],self.heap[self.length-1]=self.heap[self.length-1],self.heap[0]
item = self.heap.pop()
self.length-=1
self.fixDown(0)
return item
def fixDown(self, index):
leftIdx = (2*index) + 1
rightIdx=(2*index) +2
largerIdx=index
if leftIdx< self.length and self.heap[largerIdx]<self.heap[leftIdx]:
largerIdx=leftIdx
if rightIdx < self.length and self.heap[largerIdx]<self.heap[rightIdx]:
largerIdx=rightIdx
if index!=largerIdx:
self.heap[index], self.heap[largerIdx]=self.heap[largerIdx], self.heap[index]
self.fixDown(largerIdx)
def fixUp(self,index):
parentIdx=(index-1)//2
if parentIdx>=0 and self.heap[parentIdx]<self.heap[index]:
self.heap[parentIdx], self.heap[index] = self.heap[index], self.heap[parentIdx]
self.fixUp(parentIdx) | kth-largest-element-in-an-array | Python Max Heap Solution Without Using a Library Function (93% less memory) | prajwal_vs | 1 | 177 | kth largest element in an array | 215 | 0.658 | Medium | 3,736 |
https://leetcode.com/problems/kth-largest-element-in-an-array/discuss/1147682/Python3-Solution-(99.8) | class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
h = [] # use min heap with size k
for n in nums[:k]:
heappush(h, n)
for n in nums[k:]:
if n > h[0]:
heapreplace(h, n)
return heappop(h)
``` | kth-largest-element-in-an-array | Python3 Solution (99.8%) | dalechoi | 1 | 432 | kth largest element in an array | 215 | 0.658 | Medium | 3,737 |
https://leetcode.com/problems/kth-largest-element-in-an-array/discuss/736733/Python3-3-solutions-from-O(NlogN)-to-O(NlogK)-to-O(N) | class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
return sorted(nums)[-k] | kth-largest-element-in-an-array | [Python3] 3 solutions from O(NlogN) to O(NlogK) to O(N) | ye15 | 1 | 126 | kth largest element in an array | 215 | 0.658 | Medium | 3,738 |
https://leetcode.com/problems/kth-largest-element-in-an-array/discuss/736733/Python3-3-solutions-from-O(NlogN)-to-O(NlogK)-to-O(N) | class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
pq = [] #min heap of size k
for x in nums:
heappush(pq, x)
if len(pq) > k: heappop(pq)
return pq[0] | kth-largest-element-in-an-array | [Python3] 3 solutions from O(NlogN) to O(NlogK) to O(N) | ye15 | 1 | 126 | kth largest element in an array | 215 | 0.658 | Medium | 3,739 |
https://leetcode.com/problems/kth-largest-element-in-an-array/discuss/736733/Python3-3-solutions-from-O(NlogN)-to-O(NlogK)-to-O(N) | class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
return nlargest(k, nums)[-1] | kth-largest-element-in-an-array | [Python3] 3 solutions from O(NlogN) to O(NlogK) to O(N) | ye15 | 1 | 126 | kth largest element in an array | 215 | 0.658 | Medium | 3,740 |
https://leetcode.com/problems/kth-largest-element-in-an-array/discuss/736733/Python3-3-solutions-from-O(NlogN)-to-O(NlogK)-to-O(N) | class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
"""Hoare's selection algo"""
def partition(lo, hi):
"""Return partition of nums[lo:hi]."""
i, j = lo+1, hi-1
while i <= j:
if nums[i] < nums[lo]: i += 1
elif nums[j] > nums[lo]: j -= 1
else:
nums[i], nums[j] = nums[j], nums[i]
i += 1
j -= 1
nums[lo], nums[j] = nums[j], nums[lo]
return j
shuffle(nums)
lo, hi = 0, len(nums)
while True:
mid = partition(lo, hi)
if mid+k < len(nums): lo = mid + 1
elif mid+k == len(nums): return nums[mid]
else: hi = mid | kth-largest-element-in-an-array | [Python3] 3 solutions from O(NlogN) to O(NlogK) to O(N) | ye15 | 1 | 126 | kth largest element in an array | 215 | 0.658 | Medium | 3,741 |
https://leetcode.com/problems/kth-largest-element-in-an-array/discuss/736733/Python3-3-solutions-from-O(NlogN)-to-O(NlogK)-to-O(N) | class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
def fn(lo, hi):
"""Partition nums[lo:hi+1] into two parts"""
p = randint(lo, hi) #random pivot
nums[hi], nums[p] = nums[p], nums[hi] #relocate to rear
i = lo
while i < hi:
if nums[i] < nums[hi]:
nums[lo], nums[i] = nums[i], nums[lo]
lo += 1
i += 1
nums[lo], nums[hi] = nums[hi], nums[lo]
return lo
lo, hi = 0, len(nums)
while lo < hi:
p = fn(lo, hi-1)
if p + k == len(nums): return nums[p]
elif p + k > len(nums): hi = p
else: lo = p + 1 | kth-largest-element-in-an-array | [Python3] 3 solutions from O(NlogN) to O(NlogK) to O(N) | ye15 | 1 | 126 | kth largest element in an array | 215 | 0.658 | Medium | 3,742 |
https://leetcode.com/problems/kth-largest-element-in-an-array/discuss/701254/Python-3Kth-Largest-Element-in-an-Array.-Beats-95. | class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
heapq.heapify(nums)
return nlargest(len(nums), nums)[k-1] | kth-largest-element-in-an-array | [Python 3]Kth Largest Element in an Array. Beats 95%. | tilak_ | 1 | 378 | kth largest element in an array | 215 | 0.658 | Medium | 3,743 |
https://leetcode.com/problems/kth-largest-element-in-an-array/discuss/2847975/One-line-Python-Solution | class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
nums.sort()
return nums[-k] | kth-largest-element-in-an-array | One line Python Solution | abdulrahmanphy64 | 0 | 2 | kth largest element in an array | 215 | 0.658 | Medium | 3,744 |
https://leetcode.com/problems/kth-largest-element-in-an-array/discuss/2840650/Python-Easy-Solution | class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
s = sorted(nums)
for i in range(k-1):
s.pop(len(s)-1)
return s[-1] | kth-largest-element-in-an-array | Python Easy Solution | Jashan6 | 0 | 3 | kth largest element in an array | 215 | 0.658 | Medium | 3,745 |
https://leetcode.com/problems/kth-largest-element-in-an-array/discuss/2840216/Find-K-largest-values-python-O(N*log(N)) | class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
kheap = []
for num in nums:
if len(kheap) < k:
heapq.heappush(kheap, num)
elif kheap[0]<num:
heapq.heappop(kheap)
heapq.heappush(kheap, num)
return kheap[0] | kth-largest-element-in-an-array | Find K largest values - python - O(N*log(N)) | DavidCastillo | 0 | 1 | kth largest element in an array | 215 | 0.658 | Medium | 3,746 |
https://leetcode.com/problems/kth-largest-element-in-an-array/discuss/2840215/Find-K-largest-values-python-O(N*log(k)) | class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
kheap = []
for num in nums:
if len(kheap) < k:
heapq.heappush(kheap, num)
elif kheap[0]<num:
heapq.heappop(kheap)
heapq.heappush(kheap, num)
return kheap[0] | kth-largest-element-in-an-array | Find K largest values - python - O(N*log(k)) | DavidCastillo | 0 | 2 | kth largest element in an array | 215 | 0.658 | Medium | 3,747 |
https://leetcode.com/problems/kth-largest-element-in-an-array/discuss/2834044/Simplest-Python-Solution | class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
nums.sort()
nums=nums[::-1]
return nums[(k-1)] | kth-largest-element-in-an-array | Simplest Python Solution | Ashil_3108 | 0 | 5 | kth largest element in an array | 215 | 0.658 | Medium | 3,748 |
https://leetcode.com/problems/kth-largest-element-in-an-array/discuss/2824521/Easiest-Solution | class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
nums.sort()
return nums[-k] | kth-largest-element-in-an-array | Easiest Solution | khanismail_1 | 0 | 4 | kth largest element in an array | 215 | 0.658 | Medium | 3,749 |
https://leetcode.com/problems/kth-largest-element-in-an-array/discuss/2822275/Python-solution-or-heap | class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
heap = []
n = len(nums)
for i in range(n):
heapq.heappush(heap,nums[i])
for i in range(n - k):
heapq.heappop(heap)
return heapq.heappop(heap) | kth-largest-element-in-an-array | Python solution | heap | maomao1010 | 0 | 4 | kth largest element in an array | 215 | 0.658 | Medium | 3,750 |
https://leetcode.com/problems/kth-largest-element-in-an-array/discuss/2814381/Python-easy-code-solution. | class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
nums.sort()
n = nums[::-1]
s = n[k-1:k]
ans = 0
for i in s:
ans += i
return int(ans) | kth-largest-element-in-an-array | Python easy code solution. | anshu71 | 0 | 5 | kth largest element in an array | 215 | 0.658 | Medium | 3,751 |
https://leetcode.com/problems/kth-largest-element-in-an-array/discuss/2808326/Python-quick-select | class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
k = len(nums) - k
def quickSelect(l, r):
pivot, p = nums[r], l
for i in range(l, r):
if nums[i] <= pivot:
nums[p], nums[i] = nums[i], nums[p]
p += 1
nums[p], nums[r] = nums[r], nums[p]
if p > k: return quickSelect(l, p-1)
elif p < k: return quickSelect(p+1, r)
else: return nums[p]
return quickSelect(0, len(nums)-1) | kth-largest-element-in-an-array | Python quick select | zananpech9 | 0 | 5 | kth largest element in an array | 215 | 0.658 | Medium | 3,752 |
https://leetcode.com/problems/kth-largest-element-in-an-array/discuss/2806451/one-line-python-solution | class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
nums.sort()
return (nums[-k])
# result = []
# for i in range(k):
# result.append(max(nums))
# nums.remove(max(nums))
# return result[-1] | kth-largest-element-in-an-array | one line python solution | rahul_1234598 | 0 | 5 | kth largest element in an array | 215 | 0.658 | Medium | 3,753 |
https://leetcode.com/problems/kth-largest-element-in-an-array/discuss/2803919/Daily-LeetCode-Practice-Day-22 | class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
if not nums:
return
pivot = random.choice(nums)
left = [x for x in nums if x > pivot]
mid = [x for x in nums if x == pivot]
right = [x for x in nums if x < pivot]
L = len(left)
M = len(mid)
if k <= L:
return self.findKthLargest(left, k)
elif k > L + M:
return self.findKthLargest(right, k - L - M)
else:
return mid[0] | kth-largest-element-in-an-array | Daily LeetCode Practice, Day 22 | yluo3421 | 0 | 3 | kth largest element in an array | 215 | 0.658 | Medium | 3,754 |
https://leetcode.com/problems/kth-largest-element-in-an-array/discuss/2785616/ONE-LINE-SOLUTION-PYTHON-O(n) | class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
return sorted(nums)[::-1][k-1] | kth-largest-element-in-an-array | ONE LINE SOLUTION PYTHON O(n) | m_ujeeb | 0 | 1 | kth largest element in an array | 215 | 0.658 | Medium | 3,755 |
https://leetcode.com/problems/kth-largest-element-in-an-array/discuss/2780439/Two-line-solution-using-python! | class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
nums.sort(reverse=True)
return nums[k-1] | kth-largest-element-in-an-array | Two line solution using python! | secret_hell | 0 | 3 | kth largest element in an array | 215 | 0.658 | Medium | 3,756 |
https://leetcode.com/problems/kth-largest-element-in-an-array/discuss/2780426/Bucket-sort.-Easy-O(n) | class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
arr = [0 for i in range(2*10001)]
for i in nums:
arr[i+10000] += 1
for j in range(len(arr)-1,-1,-1):
if(arr[j]>=k):
return j-10000
else:
k -= arr[j] | kth-largest-element-in-an-array | Bucket sort. Easy O(n) | rkgupta1298 | 0 | 5 | kth largest element in an array | 215 | 0.658 | Medium | 3,757 |
https://leetcode.com/problems/kth-largest-element-in-an-array/discuss/2779121/heap-approach-python | class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
# O(n*log(k)), O(k)
heapq.heapify(nums)
while len(nums) > k:
heapq.heappop(nums)
return nums[0]
# or
# return heapq.nlargest(k, nums)[-1] | kth-largest-element-in-an-array | heap approach python | sahilkumar158 | 0 | 7 | kth largest element in an array | 215 | 0.658 | Medium | 3,758 |
https://leetcode.com/problems/kth-largest-element-in-an-array/discuss/2757951/Python3-Priority-Queue | class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
h = []
for num in nums:
if len(h) < k:
heapq.heappush(h, num)
else:
if num > h[0]:
heapq.heappushpop(h, num)
return h[0] | kth-largest-element-in-an-array | Python3 Priority Queue | jonathanbrophy47 | 0 | 4 | kth largest element in an array | 215 | 0.658 | Medium | 3,759 |
https://leetcode.com/problems/kth-largest-element-in-an-array/discuss/2727344/Quick-Select-Algorithm | class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
n = len(nums)
k = n - k
def quickSort(l=0, r=n-1):
p, pivot = l, nums[r]
for i in range(l, r):
if nums[i] <= pivot:
nums[i], nums[p] = nums[p], nums[i]
p += 1
nums[p], nums[r] = pivot, nums[p]
if k > p:
return quickSort(p + 1, r)
elif k < p:
return quickSort(l, p - 1)
return nums[k]
return quickSort() | kth-largest-element-in-an-array | Quick Select Algorithm | andrewnerdimo | 0 | 9 | kth largest element in an array | 215 | 0.658 | Medium | 3,760 |
https://leetcode.com/problems/combination-sum-iii/discuss/1312030/Elegant-Python-Iterative-or-Recursive | class Solution:
def combinationSum3(self, k: int, n: int) -> List[List[int]]:
current_combination, combinations = [], []
integer, combination_sum = 1, 0
queue = [(integer, current_combination, combination_sum)]
while queue:
integer, current_combination, combination_sum = queue.pop()
if combination_sum == n and len(current_combination) == k: combinations.append(current_combination)
else:
for i in range(integer, 10):
if combination_sum + i > n: break
queue.append((i+1, current_combination + [i], combination_sum + i))
return combinations | combination-sum-iii | Elegant Python Iterative | Recursive | soma28 | 5 | 175 | combination sum iii | 216 | 0.672 | Medium | 3,761 |
https://leetcode.com/problems/combination-sum-iii/discuss/1312030/Elegant-Python-Iterative-or-Recursive | class Solution:
def combinationSum3(self, k: int, n: int) -> List[List[int]]:
combinations = []
counter = [(integer, 1) for integer in range(1, 10)]
def recursion(integer = 0, current_combination = [], combination_sum = 0):
if combination_sum > n or len(current_combination) > k or integer not in range(9): return
elif combination_sum == n and len(current_combination) == k: combinations.append(current_combination.copy())
else:
candidate, frequency = counter[integer]
if frequency == 1:
counter[integer] = (candidate, 0)
recursion(integer, current_combination + [candidate], combination_sum + candidate)
counter[integer] = (candidate, frequency)
recursion(integer+1, current_combination, combination_sum)
recursion()
return combinations | combination-sum-iii | Elegant Python Iterative | Recursive | soma28 | 5 | 175 | combination sum iii | 216 | 0.672 | Medium | 3,762 |
https://leetcode.com/problems/combination-sum-iii/discuss/2677557/Python-oror-Backtracking-(with-comments) | class Solution:
def combinationSum3(self, k: int, n: int) -> List[List[int]]:
if k > n: # if number of elements greater than sum no point in checking
return []
if n > 45: # we can have max sum 45 for [1,2....,9]
return []
lst = range(1,10)
ans=[]
def solve(ind, ds, target):
if target == 0 and len(ds) == k:
ans.append(ds[:]) # have to append a copy to our final answer (i.e. we cannot do ans.append(ds))
return
for i in range(ind,len(lst)):
if target < lst[i]:
break
ds.append(lst[i]) # add the element to our data structure
solve(i+1, ds, target-lst[i]) # remove that element from target
ds.pop() # now during backtracking we have to remove that element from our data structure
solve(0,[],n)
return ans | combination-sum-iii | Python || Backtracking (with comments) | Graviel77 | 2 | 124 | combination sum iii | 216 | 0.672 | Medium | 3,763 |
https://leetcode.com/problems/combination-sum-iii/discuss/842624/Python-3-or-Backtracking-DFS-or-Explanations | class Solution:
def combinationSum3(self, k: int, n: int) -> List[List[int]]:
def dfs(digit, start_num, cur, cur_sum):
if cur_sum == n and digit == k: ans.append(cur[:])
elif digit >= k or cur_sum > n: return
else:
for i in range(start_num+1, 10):
cur.append(i)
dfs(digit+1, i, cur, cur_sum+i)
cur.pop()
ans = list()
dfs(0, 0, [], 0)
return ans | combination-sum-iii | Python 3 | Backtracking, DFS | Explanations | idontknoooo | 2 | 351 | combination sum iii | 216 | 0.672 | Medium | 3,764 |
https://leetcode.com/problems/combination-sum-iii/discuss/2382303/Python-or-Easy-solution | class Solution:
def combinationSum3(self, k: int, n: int) -> List[List[int]]:
answer = []
path = []
def dp(idx, total):
if len(path) > k:
return
if total > n:
return
if total == n and len(path) == k:
answer.append(path.copy())
return
for i in range(idx, 10):
path.append(i)
dp(i+1, total + i)
path.pop()
dp(1, 0)
return answer | combination-sum-iii | Python | Easy solution | pivovar3al | 1 | 26 | combination sum iii | 216 | 0.672 | Medium | 3,765 |
https://leetcode.com/problems/combination-sum-iii/discuss/2025095/Python-Simple-and-Easy-Solution-using-Recursion-and-Backtracking | class Solution:
def combinationSum3(self, k: int, n: int) -> List[List[int]]:
options = [1,2,3,4,5,6,7,8,9]
ans = []
comb = []
score = 0
self.GenerateValid(options, 0, k, n, score, comb, ans)
return ans
def GenerateValid(self, options, currentIndex, k, n, score, comb, ans):
if(score == n and k == 0):
ans.append(comb[:])
return
if(currentIndex >= len(options) or (score != n and k <= 0)):
return
if(score + options[currentIndex] <= n and k > 0):
comb.append(options[currentIndex])
self.GenerateValid(options, currentIndex + 1, k - 1, n, score + options[currentIndex], comb, ans)
comb.pop()
self.GenerateValid(options, currentIndex + 1, k, n, score, comb, ans)
return | combination-sum-iii | Python Simple and Easy Solution using Recursion and Backtracking | shubhamgoel90 | 1 | 52 | combination sum iii | 216 | 0.672 | Medium | 3,766 |
https://leetcode.com/problems/combination-sum-iii/discuss/2023986/Python-or-Standard-Backtrack-or-Easy-to-Understand | class Solution:
def combinationSum3(self, k: int, n: int) -> List[List[int]]:
result = []
candidate = []
def backtrack(startIndex, curSum):
if curSum == n and len(candidate) == k:
result.append(candidate[:])
return
for i in range(startIndex, 10):
candidate.append(i)
curSum += i
backtrack(i+1, curSum)
candidate.pop()
curSum -= i
backtrack(1, 0)
return result | combination-sum-iii | Python | Standard Backtrack | Easy to Understand | Mikey98 | 1 | 36 | combination sum iii | 216 | 0.672 | Medium | 3,767 |
https://leetcode.com/problems/combination-sum-iii/discuss/1197561/Python-simple-DFS-faster-than-85%2B | class Solution:
def combinationSum3(self, k, n):
nums = list(range(1, 10))
ans = []
def dfs(cur, pos, target, d):
if d == k:
if target == 0:
ans.append(cur.copy())
return
for i in range(pos, 9):
if nums[i] > target: break
cur.append(nums[i])
dfs(cur, i+1, target-nums[i], d+1)
cur.pop()
dfs([], 0, n, 0)
return ans | combination-sum-iii | Python simple DFS, faster than 85+% | dustlihy | 1 | 102 | combination sum iii | 216 | 0.672 | Medium | 3,768 |
https://leetcode.com/problems/combination-sum-iii/discuss/2789873/Intuitive-solution | class Solution:
def combinationSum3(self, k: int, target: int) -> List[List[int]]:
ans = []
def help(i,n,s,tot):
if len(s)==k and tot==target:
ans.append(s.copy())
return
if i>n:
return
if len(s)>k:
return
if tot>target:
return
help(i+1,n,s+[i],tot+i)
help(i+1,n,s,tot)
help(1,9,[],0)
return ans | combination-sum-iii | Intuitive solution | Rtriders | 0 | 1 | combination sum iii | 216 | 0.672 | Medium | 3,769 |
https://leetcode.com/problems/combination-sum-iii/discuss/2772111/Python-solution-or-backtrack | class Solution:
def combinationSum3(self, k: int, n: int) -> List[List[int]]:
def backtrack(nums, index, target, path, res):
if len(path) == k and target == 0:
res.append(path)
return
if target < nums[index]:
return
for i in range(index + 1, len(nums)):
backtrack(nums, i, target - nums[i], path + [nums[i]], res)
nums = [i for i in range(1,10)]
res = []
for i in range(len(nums)):
backtrack(nums, i, n - nums[i], [nums[i]], res)
return res | combination-sum-iii | Python solution | backtrack | maomao1010 | 0 | 3 | combination sum iii | 216 | 0.672 | Medium | 3,770 |
https://leetcode.com/problems/combination-sum-iii/discuss/2751342/PYTHON-Solution-using-Combination-Sum-II | class Solution:
def combinationSum3(self, k: int, n: int) -> List[List[int]]:
candidates = [num for num in range(1,10)] # build candidates
result = []
# combination sum II
def backtrack(idx,curr,target):
if target == 0 and len(curr) == k:
result.append(curr[::])
return
if target < 0:
return
for j in range(idx,len(candidates)):
curr.append(candidates[j])
backtrack(j+1,curr,target-candidates[j])
curr.pop()
backtrack(0,[],n)
return result | combination-sum-iii | PYTHON Solution using Combination Sum II | iamrahultanwar | 0 | 2 | combination sum iii | 216 | 0.672 | Medium | 3,771 |
https://leetcode.com/problems/combination-sum-iii/discuss/2748503/Python | class Solution:
def combinationSum3(self, k: int, n: int) -> List[List[int]]:
if k > n:
return []
if n > 45:
return []
lst = range(1,10)
ans=[]
def solve(ind, ds, target):
if target == 0 and len(ds) == k:
ans.append(ds[:])
return
for i in range(ind,len(lst)):
if target < lst[i]:
break
ds.append(lst[i])
solve(i+1, ds, target-lst[i])
ds.pop()
solve(0,[],n)
return ans | combination-sum-iii | Python | lucy_sea | 0 | 3 | combination sum iii | 216 | 0.672 | Medium | 3,772 |
https://leetcode.com/problems/combination-sum-iii/discuss/2744142/Simple-Python-Backtrack-Solution | class Solution:
def combinationSum3(self, k: int, n: int) -> List[List[int]]:
visited = [False for _ in range(n)]
result = []
def backtrack(index, path):
if sum(path) == n and len(path)==k:
result.append(list(path))
return
if len(path) > k:
return
for num in range(index, 10):
if num not in path:
path.append(num)
backtrack(num+1, path)
path.pop()
backtrack(1, [])
return result | combination-sum-iii | Simple Python Backtrack Solution | Rui_Liu_Rachel | 0 | 5 | combination sum iii | 216 | 0.672 | Medium | 3,773 |
https://leetcode.com/problems/combination-sum-iii/discuss/2720185/Python-itertools-SolutionEasy-To-Understand | class Solution:
def combinationSum3(self, k: int, n: int) -> List[List[int]]:
result = []
for comb in itertools.combinations(range(1, 10), k):
if sum(comb) == n:
result.append(list(comb))
return result | combination-sum-iii | Python itertools Solution[Easy To Understand] | namashin | 0 | 4 | combination sum iii | 216 | 0.672 | Medium | 3,774 |
https://leetcode.com/problems/combination-sum-iii/discuss/2693654/Simple-backtracking | class Solution:
def combinationSum3(self, k: int, n: int) -> List[List[int]]:
arr = [1,2,3,4,5,6,7,8,9]
res = []
ans = []
def backtrack(i, k, curSum):
if k == 0 and curSum == n:
res.append(ans.copy())
return
if k < 0 or i >= len(arr):
return
ans.append(arr[i])
backtrack(i+1, k-1, curSum+arr[i])
ans.pop()
backtrack(i+1, k, curSum)
backtrack(0, k, 0)
return res | combination-sum-iii | Simple backtracking | mukundjha | 0 | 2 | combination sum iii | 216 | 0.672 | Medium | 3,775 |
https://leetcode.com/problems/combination-sum-iii/discuss/2498746/Easy-Python-Solution-or-Recursion | class Solution:
def combinationSum3(self, k: int, n: int) -> List[List[int]]:
arr=[1,2,3,4,5,6,7,8,9]
ans=[]
def helper(ind, count, curr):
if ind==len(arr):
if count==k and sum(curr)==n:
return ans.append(curr[:])
return
helper(ind+1, count, curr)
curr.append(arr[ind])
count+=1
helper(ind+1, count, curr)
curr.pop()
count-=1
return
helper(0, 0, [])
return ans | combination-sum-iii | Easy Python Solution | Recursion | Siddharth_singh | 0 | 24 | combination sum iii | 216 | 0.672 | Medium | 3,776 |
https://leetcode.com/problems/combination-sum-iii/discuss/2456201/Python3-or-Simple-Backtracking-%2B-Recursion-Solution | class Solution:
#Time-Complexity : O(9^k), since branching factor of rec. tree is at worst 9 and the height of tree
#is at most k!
#Space-Complexity:O(9 + k) -> O(k), due to max call stack depth of recursion!
def combinationSum3(self, k: int, n: int) -> List[List[int]]:
#arr will have numbers from 1 through 10 in ascending order!
arr = [i for i in range(1, 10)]
ans = []
def helper(i, cur, a):
nonlocal k, n, ans, arr
#base case
if(len(a) == k):
if(cur == n):
ans.append(a[::])
return
else:
return
#another base case: check if index i is out of bounds and no more elements to consider!
if(i == len(arr)):
return
#recurse iteratively from index i to index len(arr) - 1!
for j in range(i, len(arr)):
#update the current array by including arr[j]!
a.append(arr[j])
#make rec. call!
helper(j+1, cur + arr[j] , a)
#once we return from recursive call and backtrack, restore a!
a.pop()
helper(0, 0, [])
return ans | combination-sum-iii | Python3 | Simple Backtracking + Recursion Solution | JOON1234 | 0 | 11 | combination sum iii | 216 | 0.672 | Medium | 3,777 |
https://leetcode.com/problems/combination-sum-iii/discuss/2357095/python3-solution-backtrack | class Solution:
def combinationSum3(self, k: int, n: int) -> List[List[int]]:
if n >= 10:
candidates = [i for i in range(1, 10)]
else:
candidates = [i for i in range(1, n+1)]
res, track = [], []
def backtrack(first, track):
if sum(track) == n and len(track) == k:
res.append(list(track))
return
elif sum(track) > n or len(track) > k:
return
for i in range(first, len(candidates)):
track.append(candidates[i])
backtrack(i+1, track)
track.pop()
backtrack(0, track)
return res | combination-sum-iii | python3 solution backtrack | codeSheep_01 | 0 | 16 | combination sum iii | 216 | 0.672 | Medium | 3,778 |
https://leetcode.com/problems/combination-sum-iii/discuss/2104023/Python3-DFS%3A-Easy-to-understand | class Solution:
def combinationSum3(self, k: int, n: int) -> List[List[int]]:
candidates = list(range(1,10,1)) #List from 1-9
return self.helper(candidates, n, [], [], k-1)
def helper(self, candidates: List[int], target: int, path: List[int], output: List[List[int]], noOfItems:int) -> List[List[int]]:
if target<=0:
if target==0: output.append(path)
return output
for i in range(len(candidates)):
if candidates[i]==target and noOfItems==len(path):
output.append(path + [candidates[i]])
elif candidates[i]<target:
self.helper(candidates[i+1:], target-candidates[i], path+[candidates[i]], output, noOfItems)
return output | combination-sum-iii | Python3 DFS: Easy to understand | abrarjahin | 0 | 23 | combination sum iii | 216 | 0.672 | Medium | 3,779 |
https://leetcode.com/problems/combination-sum-iii/discuss/2028530/Python-Solution-or-One-Liner-or-Over-99-Faster-or-Itertools | class Solution:
def __init__(self):
self.l = [1,2,3,4,5,6,7,8,9]
def combinationSum3(self, k: int, n: int) -> List[List[int]]:
return [item for item in itertools.combinations(self.l,r=k) if sum(item) == n] | combination-sum-iii | Python Solution | One Liner | Over 99% Faster | Itertools | Gautam_ProMax | 0 | 21 | combination sum iii | 216 | 0.672 | Medium | 3,780 |
https://leetcode.com/problems/combination-sum-iii/discuss/2027134/Python-One-Line! | class Solution:
def combinationSum3(self, k, n):
return [x for x in combinations(range(1,10), k) if sum(x) == n] | combination-sum-iii | Python - One-Line! | domthedeveloper | 0 | 14 | combination sum iii | 216 | 0.672 | Medium | 3,781 |
https://leetcode.com/problems/combination-sum-iii/discuss/2025973/Python3-simple-backtracking-oror-dfs | class Solution:
def combinationSum3(self, k: int, n: int) -> List[List[int]]:
self.ans = set()
def dfs(total=0, arr=[]):
if total==n and len(arr) == k:
self.ans.add(tuple(arr))
return
if len(arr) > k:
return
for i in range(arr[-1]+1 if arr else 1, 10):
# If arr[-1] == 1, then we start from 2 so that the elements are in ascending order
# and this will prevent the array with the same elements but different order to be put into the answer
dfs(total+i, arr+[i])
dfs()
return self.ans | combination-sum-iii | Python3 simple backtracking || dfs | rjnkokre | 0 | 11 | combination sum iii | 216 | 0.672 | Medium | 3,782 |
https://leetcode.com/problems/combination-sum-iii/discuss/2025477/Python-solution-using-Backtracking-99-faster | class Solution:
def combinationSum3(self, k: int, n: int) -> List[List[int]]:
res = []
def backtrack(val, stack, target):
if len(stack) == k:
if target == 0:
res.append(stack)
else:
return
for x in range(val + 1, 10):
if x <= target:
backtrack(x, stack + [x], target - x)
else:
return
backtrack(0, [], n)
return res | combination-sum-iii | Python solution using Backtracking 99% faster | pradeep288 | 0 | 10 | combination sum iii | 216 | 0.672 | Medium | 3,783 |
https://leetcode.com/problems/combination-sum-iii/discuss/2025295/Python-or-Backtracking-%2B-recursion-or-Easy-to-understand | class Solution:
def combinationSum3(self, k: int, n: int) -> List[List[int]]:
res = []
def backtrack (num, stack, target):
if len(stack) == k:
if target == 0:
res.append(stack)
return
for currNum in range(num+1, 10):
if currNum <= target:
backtrack(currNum, stack+[currNum], target-currNum)
else:
return
backtrack(0,[],n)
return res | combination-sum-iii | Python | Backtracking + recursion | Easy to understand | Patil_Pratik | 0 | 27 | combination sum iii | 216 | 0.672 | Medium | 3,784 |
https://leetcode.com/problems/combination-sum-iii/discuss/2024948/python-java-DFS-(recursia) | class Solution:
def __init__(self):
self.answer = []
def combinationSum3(self, k: int, n: int) -> List[List[int]]:
def DFS(table, sum, start, digits, total):
if digits == 0 :
if total == sum :
self.answer.append([])
for n in table : self.answer[-1].append(n)
else :
for i in range (start, 10) :
if sum + i <= total :
table.append(i)
DFS(table, sum + i, i + 1, digits - 1, total)
table.pop()
else : break
DFS([], 0, 1, k, n)
return self.answer | combination-sum-iii | python, java - DFS (recursia) | ZX007java | 0 | 12 | combination sum iii | 216 | 0.672 | Medium | 3,785 |
https://leetcode.com/problems/combination-sum-iii/discuss/2024897/Python3-or-recursion-or-simple-solution | class Solution:
def combinationSum3(self, k: int, n: int) -> List[List[int]]:
res=[]
def sum3(st,N,rem,ans):
if(N==0):
if(rem==0):
res.append(ans)
return
for i in range(st,10):
sum3(i+1,N-1,rem-i,ans+[i])
sum3(1,k,n,[])
return res | combination-sum-iii | Python3 | recursion | simple solution | kalyan63 | 0 | 25 | combination sum iii | 216 | 0.672 | Medium | 3,786 |
https://leetcode.com/problems/combination-sum-iii/discuss/2024868/python-3-oror-backtracking | class Solution:
def combinationSum3(self, k: int, n: int) -> List[List[int]]:
def helper(k, n, low):
if k == 1:
return [[n]] if low <= n <= 9 else []
res = []
for num in range(low, 10):
for combo in helper(k - 1, n - num, num + 1):
combo.append(num)
res.append(combo)
return res
return helper(k, n, 1) | combination-sum-iii | python 3 || backtracking | dereky4 | 0 | 22 | combination sum iii | 216 | 0.672 | Medium | 3,787 |
https://leetcode.com/problems/combination-sum-iii/discuss/2024573/Python3-Backtracking-or-Run-time-Beats-93.11 | class Solution:
def combinationSum3(self, k: int, n: int) -> List[List[int]]:
result, curr = [], []
def backtrack(curr, index):
if len(curr) == k and sum(curr) == n:
result.append(curr[:])
return
elif len(curr) >= k or index > 9:
return
while index < 10: ## instead of using for loop which will cause duplicates, while loop can keep track of current index
curr.append(index)
backtrack(curr, index + 1)
curr.pop()
index += 1
backtrack(curr, 1)
return result | combination-sum-iii | Python3 Backtracking | Run time Beats 93.11% | elainexma4 | 0 | 6 | combination sum iii | 216 | 0.672 | Medium | 3,788 |
https://leetcode.com/problems/combination-sum-iii/discuss/2024485/Python3-87.92-or-DFS-Solution-O(C(9-k))-or-Easy-Implementation | class Solution:
def combinationSum3(self, k: int, n: int) -> List[List[int]]:
results = []
def dfs(remain, comb, next_start):
if remain == 0 and len(comb) == k:
# make a copy of current combination
# Otherwise the combination would be reverted in other branch of backtracking.
results.append(comb[:])
return
elif remain < 0 or len(comb) == k:
# exceed the scope, no need to explore further.
return
# Iterate through the reduced list of candidates.
for i in range(next_start, 10):
dfs(remain-i, comb+[i], i+1)
dfs(n, [], 1)
return results | combination-sum-iii | Python3 87.92% | DFS Solution O(C(9, k)) | Easy Implementation | doneowth | 0 | 11 | combination sum iii | 216 | 0.672 | Medium | 3,789 |
https://leetcode.com/problems/combination-sum-iii/discuss/2024382/python3-simple-backtracking-explained | class Solution:
def combinationSum3(self, k: int, n: int) -> List[List[int]]:
# k = length limit, n = target
def dfs(num, total): # return None
# num = current checking, total = sum of tmp list
nonlocal k, n
if len(tmp) == k:
if total == n:
ans.append(tmp.copy())
return
for i in range(num + 1, 10):
tmp.append(i)
dfs(i, total + i)
tmp.pop()
tmp = list()
ans = list()
dfs(0, 0)
return ans | combination-sum-iii | [python3] simple backtracking, explained | sshinyy | 0 | 10 | combination sum iii | 216 | 0.672 | Medium | 3,790 |
https://leetcode.com/problems/combination-sum-iii/discuss/2024249/Explained-Backtracking-(Python) | class Solution:
def combinationSum3(self, k: int, n: int) -> List[List[int]]:
res = []
def get_path(min_num, path, sm):
"""
min_num : minimum number from which we check further numbers. It is higher
than the last number inserted into the path
path : Record of digits already inserted
sm : Sum of digits already inserted
"""
nums = len(path)
# end condition
# if number of digits taken == k, then check if sum == n
if nums == k:
if sm == n:
# path.copy() is appended as path keeps getting changed
res.append(path.copy())
return
# as the order is ascending, we take the for loop from the next highest number
# after the last number in path. The loop stops while leaving enough digits for
# the rest of the numbers
# e.g if k = 3, and nums = 0 i.e. no numbers inserted yet, the loop runs from
# 0 to 7, hence leaving 2 numbers (8 and 9) for further recursions
for i in range(min_num, 10 - (k - nums - 1)):
# if sum exceeds n, no need for further checks
if sm + i <= n:
path.append(i)
get_path(i + 1, path, sm + i)
path.pop()
else:
break
return
get_path(1, [], 0)
return res | combination-sum-iii | Explained Backtracking (Python) | kaustav43 | 0 | 10 | combination sum iii | 216 | 0.672 | Medium | 3,791 |
https://leetcode.com/problems/combination-sum-iii/discuss/2024021/Python-Recursion-with-Time-Complexity | class Solution:
def combinationSum3(self, k: int, n: int) -> List[List[int]]:
res = []
def combinationSum3Inner(i, target, l):
if target == 0 and len(l) == k:
res.append(l)
return
if target < 0 or len(l)==k:
return
for j in range(i, 9):
combinationSum3Inner(j+1, target-j-1, l + [j+1])
combinationSum3Inner(0, n, [])
return res | combination-sum-iii | ✅ Python Recursion with Time Complexity | constantine786 | 0 | 145 | combination sum iii | 216 | 0.672 | Medium | 3,792 |
https://leetcode.com/problems/combination-sum-iii/discuss/1714052/Python3-oror-Backtracking-solution-for-beginners-oror-Recursion | class Solution:
def combinationSum3(self, k: int, n: int) -> List[List[int]]:
res = []
def backtrack(curr,i,k):
# base match: a match
if k==0 and sum(curr)==n:
res.append(curr.copy())
return
if sum(curr)>n or k<0:
return
# check each combination
for j in range(i,10):
curr.append(j)
backtrack(curr,j+1,k-1)
curr.pop()
# start from each integer
for i in range(1,10):
backtrack([],i,k)
# remove the duplicates
ans = []
for i in res:
if i not in ans:
ans.append(i)
return ans | combination-sum-iii | Python3 || Backtracking solution for beginners || Recursion | tahsin_alamin | 0 | 35 | combination sum iii | 216 | 0.672 | Medium | 3,793 |
https://leetcode.com/problems/combination-sum-iii/discuss/1625694/Python-Backtracking-Solution-oror-greater-97-Time | class Solution:
def backtracker(self, lst, target, partial, targetSubsetL, ans):
if len(partial) > targetSubsetL:
return
elif len(partial) == targetSubsetL and sum(partial) == target:
ans.append(partial)
else:
for i in range(len(lst)):
num = lst[i]
self.backtracker(lst[i+1:], target, partial+[num], targetSubsetL, ans)
return
def combinationSum3(self, k: int, n: int) -> List[List[int]]:
if n < 0 or n > ((k*(k+1))//2 + (9-k)*k):
return []
lst = [1,2,3,4,5,6,7,8,9]
ans = []
self.backtracker(lst, n, [], k, ans)
return ans | combination-sum-iii | Python Backtracking Solution || > 97% Time | henriducard | 0 | 53 | combination sum iii | 216 | 0.672 | Medium | 3,794 |
https://leetcode.com/problems/combination-sum-iii/discuss/1528944/WEEB-DOES-PYTHON-(3-METHODS) | class Solution:
def combinationSum3(self, k: int, n: int) -> List[List[int]]:
result = []
nums = [i for i in range(1, 10)]
def dfs(path = [], idx = 0):
if sum(path) == n and len(path) == k:
result.append(path)
return
if sum(path) > n or len(path) > k or idx == len(nums): return
dfs(path + [nums[idx]], idx+1)
dfs(path, idx+1)
dfs()
return result | combination-sum-iii | WEEB DOES PYTHON (3 METHODS) | Skywalker5423 | 0 | 63 | combination sum iii | 216 | 0.672 | Medium | 3,795 |
https://leetcode.com/problems/combination-sum-iii/discuss/1528944/WEEB-DOES-PYTHON-(3-METHODS) | class Solution:
def combinationSum3(self, k: int, n: int) -> List[List[int]]:
nums = [i for i in range(1, 10)]
queue = deque([])
for i in range(len(nums)):
queue.append(([nums[i]], i, nums[i]))
return self.bfs(queue, nums, k, n)
def bfs(self, queue, nums, k, n):
result = []
while queue:
curPath, idx , curSum = queue.popleft()
if len(curPath) > k or curSum > n:
continue
if len(curPath) == k and curSum == n:
result.append(curPath)
continue
for i in range(idx+1, len(nums)):
queue.append((curPath + [nums[i]], i, curSum + nums[i]))
return result | combination-sum-iii | WEEB DOES PYTHON (3 METHODS) | Skywalker5423 | 0 | 63 | combination sum iii | 216 | 0.672 | Medium | 3,796 |
https://leetcode.com/problems/combination-sum-iii/discuss/1528944/WEEB-DOES-PYTHON-(3-METHODS) | class Solution:
def combinationSum3(self, k: int, n: int) -> List[List[int]]:
return [val for val in itertools.combinations([i for i in range(1,10)], k) if sum(val) == n] | combination-sum-iii | WEEB DOES PYTHON (3 METHODS) | Skywalker5423 | 0 | 63 | combination sum iii | 216 | 0.672 | Medium | 3,797 |
https://leetcode.com/problems/combination-sum-iii/discuss/1429952/Python-backtracking-solution-for-Combination-Sum-I-II-and-III | class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
res = []
path = []
index = 0
total = 0
candidates.sort()
self.backtrack(candidates, target, res, path, index, total)
return res
def backtrack(self, candidates, target, res, path, index, total):
if total == target:
res.append(path[:])
return
if total > target:
return
for i in range(index, len(candidates)):
path.append(candidates[i])
self.backtrack(candidates, target, res, path, i, total + candidates[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,798 |
https://leetcode.com/problems/combination-sum-iii/discuss/1429952/Python-backtracking-solution-for-Combination-Sum-I-II-and-III | class Solution:
def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
candidates.sort()
res = []
path = []
index = 0
total = 0
self.backtrack(candidates, target, res, path, index, total)
return res
def backtrack(self, candidates, target, res, path, index, total):
if total == target:
res.append(path[:])
return
if total > target:
return
for i in range(index, len(candidates)):
if i != index and candidates[i] == candidates[i-1]:
continue
path.append(candidates[i])
self.backtrack(candidates, target, res, path, i+1, total + candidates[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,799 |
Subsets and Splits