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/add-two-numbers-ii/discuss/2584236/Python-Reverse-List-No-extra-space-other-than-output-O(N)or-O(1)
class Solution: def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]: # reverse the lists l1 = reverse(l1) l2 = reverse(l2) # go through both list prev = None carry = 0 while l1 or l2 or carry: # calculate the new sum new_sum = 0 if l1: new_sum += l1.val l1 = l1.next if l2: new_sum += l2.val l2 = l2.next new_sum += carry # check overflow and set carry if new_sum >= 10: carry = 1 new_sum = new_sum-10 else: carry = 0 # make a new node new_node = ListNode(val=new_sum, next=prev) prev = new_node return prev def reverse(head): prev = None while head: tmp = head.next head.next = prev prev = head head = tmp return prev
add-two-numbers-ii
[Python] - Reverse List, No extra space other than output - O(N)| O(1)
Lucew
0
32
add two numbers ii
445
0.595
Medium
7,900
https://leetcode.com/problems/add-two-numbers-ii/discuss/2432840/Stack-Python-3-w-comments
class Solution: def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]: n1 = n2 = 0 ptr1, ptr2 = l1, l2 # Pointers to the head of the given two lists stack = [] # Maintaining the stack to reverse it in the end while ptr1: n1 += 1; ptr1 = ptr1.next # counting the nuber of nodes in l1 while ptr2: n2 += 1; ptr2 = ptr2.next # counting the number of nodes in l2 max_len = n1 if n1 > n2 else n2 # taking the max value of two while max_len: v1 = v2 = 0 if max_len <= n1: v1 = l1.val; l1 = l1.next if max_len <= n2: v2 = l2.val; l2 = l2.next stack.append(v1 + v2) max_len -= 1 val, head = 0, None while stack or val: if stack: val += stack.pop() node = ListNode(val % 10) # adding the single digit to the output list node.next = head head = node val //= 10 # getting the carry return head ```
add-two-numbers-ii
Stack-Python 3 w/ comments
aman-senpai
0
19
add two numbers ii
445
0.595
Medium
7,901
https://leetcode.com/problems/add-two-numbers-ii/discuss/2304285/Python-Memory-Optimized-Solution
class Solution: def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]: s1, s2 = '', '' while l1: s1 = s1 + str(l1.val) l1 = l1.next while l2: s2 += str(l2.val) l2 = l2.next final_s = str(int(s1) + int(s2)) temp = head = ListNode(int(final_s[0])) n = 1 while n < len(final_s): temp.next = ListNode(int(final_s[n])) temp, n = temp.next, n+1 return head
add-two-numbers-ii
Python Memory Optimized Solution
zip_demons
0
51
add two numbers ii
445
0.595
Medium
7,902
https://leetcode.com/problems/add-two-numbers-ii/discuss/2242188/Python-Solution
class Solution: def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]: def convertToString(l): num = '' while l: num += str(l.val) l = l.next return num num1 = convertToString(l1) num2 = convertToString(l2) num3 = int(num1) + int(num2) num3 = str(num3) dummy = curr = ListNode(0) for i in num3: curr.next = ListNode(int(i)) curr = curr.next return dummy.next
add-two-numbers-ii
Python Solution
sadiah
0
27
add two numbers ii
445
0.595
Medium
7,903
https://leetcode.com/problems/add-two-numbers-ii/discuss/2093656/Python3-oror-faster-24.77-oror-memory-89.25
class Solution: def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]: numb1 = 0 while l1: numb1 = numb1 * 10 + l1.val l1 = l1.next numb2 = 0 while l2: numb2 = numb2 * 10 + l2.val l2 = l2.next numb_sum = numb1 + numb2 prev = None while numb_sum: numb_sum, divisor = divmod(numb_sum, 10) prev = ListNode(val=divisor, next=prev) return prev or ListNode(val=0)
add-two-numbers-ii
Python3 || faster 24.77% || memory 89.25%
grivabo
0
65
add two numbers ii
445
0.595
Medium
7,904
https://leetcode.com/problems/add-two-numbers-ii/discuss/1996965/Python-runtime-84.55-memory-90.95
class Solution: def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]: s1 = [] s2 = [] while l1 != None: s1.append(l1.val) l1 = l1.next while l2 != None: s2.append(l2.val) l2 = l2.next carry = 0 head = None while s1 !=[] or s2 !=[] or carry: e1 =0 e2 =0 if s1 != []: e1 = s1.pop() if s2 != []: e2 = s2.pop() add = e1 + e2 + carry if head != None: newhead = ListNode( add % 10 ) newhead.next = head head = newhead else: head = ListNode( add % 10 ) carry = add // 10 return head
add-two-numbers-ii
Python, runtime 84.55%, memory 90.95%
tsai00150
0
77
add two numbers ii
445
0.595
Medium
7,905
https://leetcode.com/problems/add-two-numbers-ii/discuss/1974666/Python-O(N)-time-and-O(1)-space
class Solution: def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]: def reverse(l1): itr = l1 prev = None while itr: nxt = itr.next itr.next = prev prev = itr itr = nxt return prev newL1 = reverse(l1) newL2 = reverse(l2) fakeHead = prev = ListNode() carry = 0 while newL1 or newL2: if newL1: carry += newL1.val newL1 = newL1.next if newL2: carry += newL2.val newL2 = newL2.next curr = carry % 10 carry = carry // 10 newNode = ListNode(curr) # create the answer prev.next = newNode prev = prev.next if carry: prev.next = ListNode(carry) ans = reverse(fakeHead.next) return ans
add-two-numbers-ii
Python O(N) time and O(1) space
dhananjay79
0
50
add two numbers ii
445
0.595
Medium
7,906
https://leetcode.com/problems/add-two-numbers-ii/discuss/1916953/Python3-or-Efficient-Solution-or-easy-to-understand
class Solution: def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]: sum1=0 while l1: sum1=sum1*10+l1.val l1=l1.next sum2=0 while l2: sum2=sum2*10+l2.val l2=l2.next sum1=sum1+sum2 if sum1==0: return ListNode(0) head1=ListNode() temp1=None while sum1>0: temp2=ListNode(sum1%10) temp2.next=temp1 temp1=temp2 sum1//=10 return temp1
add-two-numbers-ii
Python3 | Efficient Solution | easy to understand
RickSanchez101
0
56
add two numbers ii
445
0.595
Medium
7,907
https://leetcode.com/problems/add-two-numbers-ii/discuss/1847260/python-using-%222.-Add-Two-Numbers%22-solution.-Beats-99-for-Memory-Usage
class Solution: def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]: # Below lines are to reverse the linkedlist to match input lists to "2. Add Two Numbers" # instead of using numer 7->2->4->3, lets use it in reverse order 3->4->2->7 l1 = self.reverseLinkedList(l1) l2 = self.reverseLinkedList(l2) # Once we get the listed reversed, we can simply use the same code from the other problem here #------------- res = n = ListNode("#") carry = 0 while l1 or l2 or carry: if l1: carry += l1.val l1 = l1.next if l2: carry += l2.val l2 = l2.next carry, val = divmod(carry, 10) n.next = ListNode(val) n = n.next #------------- # Now we have gotten the addition but it is in reversed format. For example with original inputs 7->2->4->3 and 5->6->4, we need output as 7->8->0->7. But because we reveresed the linked list earlier, as of now our asnwer is 7->0->8->7 # Lets reverse the result to get it in right order. res.next = self.reverseLinkedList(res.next) # return the final result (in the correct order) return res.next # additional helper function to reverse linked list def reverseLinkedList(self, head): temp = head prev = None while temp: next = temp.next temp.next = prev prev = temp temp = next return prev
add-two-numbers-ii
python using "2. Add Two Numbers" solution. Beats 99% for Memory Usage
dipaksing
0
25
add two numbers ii
445
0.595
Medium
7,908
https://leetcode.com/problems/add-two-numbers-ii/discuss/1490556/Python-3-Working-Backward-by-Recursion-Explained
class Solution: def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]: node, carry = self.recurse(l1, l2, self.findLength(l1) - self.findLength(l2)) # Handle final carry return ListNode(carry, node) if carry > 0 else node def findLength(self, head: Optional[ListNode]) -> int: return 1 + self.findLength(head.next) if head else 0 """ len_diff: initially "length1 - length2, moving toward 0 during alignment Return (node: ListNode, carry: int) """ def recurse(self, l1: Optional[ListNode], l2: Optional[ListNode], len_diff: int) -> (Optional[ListNode], int): if len_diff != 0: # Move pointer of longer list for alignment if len_diff > 0: _next, carry = self.recurse(l1.next, l2, len_diff - 1) _sum = l1.val + carry # Not using l2.val else: _next, carry = self.recurse(l1, l2.next, len_diff + 1) _sum = l2.val + carry # Not using l1.val node = ListNode(_sum % 10, _next) return (node, _sum // 10) elif l1 and l2: # Already aligned _next, carry = self.recurse(l1.next, l2.next, 0) _sum = l1.val + l2.val + carry node = ListNode(_sum % 10, _next) return (node, _sum // 10) else: # not l1 and not l2 return (None, 0)
add-two-numbers-ii
Python 3 Working Backward by Recursion Explained
ryanleitaiwan
0
65
add two numbers ii
445
0.595
Medium
7,909
https://leetcode.com/problems/add-two-numbers-ii/discuss/1330756/Easy-Fast-Python-Solution-(faster-than-99)
class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: first = "" second = "" length1 = 0 current = l1 while current: length1 += 1 first += str(current.val) current = current.next length2 = 0 current = l2 while current: length2 += 1 second += str(current.val) current = current.next addition = str(int(first) + int(second)) if length1 >= length2: current = l1 length = length1 ret = l1 else: current = l2 length = length2 ret = l2 for i in range(length): current.val = int(addition[i]) if i != length-1: current = current.next if length < len(addition): current.next = ListNode(int(addition[-1])) return ret
add-two-numbers-ii
Easy, Fast Python Solution (faster than 99%)
the_sky_high
0
127
add two numbers ii
445
0.595
Medium
7,910
https://leetcode.com/problems/add-two-numbers-ii/discuss/1281263/Python-Solution-using-recurssion
class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: def size(head): if head == None: return 0 return size(head.next)+1 #prepending zero's for smaller size to equate sizes a,b = size(l1),size(l2) if a<b: for i in range(b-a): tmp = ListNode(0) tmp.next = l1 l1 = tmp else: for i in range(a-b): tmp = ListNode(0) tmp.next = l2 l2 = tmp #this fuction returns carry of right side part. so simply add l1.val,l2.val and func(l1.next+l2.next)(which is the carry we get when we add whole right side digits) def func(l1,l2): if l1 == None and l2 == None: return 0 # print(l1.val,l2.val) tmp = l1.val+l2.val+func(l1.next,l2.next) l1.val = tmp %10 return tmp//10 carry = func(l1,l2) if c!=0: tmp = ListNode(c) tmp.next = l1 l1 = tmp return l1
add-two-numbers-ii
Python Solution using recurssion
sandeeppoloju
0
28
add two numbers ii
445
0.595
Medium
7,911
https://leetcode.com/problems/add-two-numbers-ii/discuss/1034447/Python3-Simple-Solution-Using-Strings-(60ms)
class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: s1, s2 = "", "" cur1, cur2 = l1, l2 while True: if cur1 != None: s1+=str(cur1.val) cur1 = cur1.next if cur2 != None: s2+=str(cur2.val) cur2 = cur2.next if cur1== None and cur2 == None: break l3 = ListNode(0) cur3 = l3 sum_val = int(s1) + int(s2) for i in str(sum_val): cur3.next = ListNode(int(i)) cur3 = cur3.next return l3.next
add-two-numbers-ii
Python3 Simple Solution Using Strings (60ms)
rudranshsharma123
0
94
add two numbers ii
445
0.595
Medium
7,912
https://leetcode.com/problems/add-two-numbers-ii/discuss/652448/Python%3A-Without-modifying-input-no-str-conversion
class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: result = self.getNumberByIterList(l1) + self.getNumberByIterList(l2) divisor = 10 if result == 0: return ListNode(0) head, prev = None, None while result > 0: result, remainder = divmod(result, divisor) head = ListNode(remainder, prev) prev = head return head def getNumberByIterList(self, li): number = 0 while li is not None: number = number * 10 + li.val li = li.next return number
add-two-numbers-ii
Python: Without modifying input, no str conversion
davemate
0
129
add two numbers ii
445
0.595
Medium
7,913
https://leetcode.com/problems/arithmetic-slices-ii-subsequence/discuss/1292744/Python3-freq-tables
class Solution: def numberOfArithmeticSlices(self, nums: List[int]) -> int: ans = 0 freq = [defaultdict(int) for _ in range(len(nums))] # arithmetic sub-seqs for i, x in enumerate(nums): for ii in range(i): diff = x - nums[ii] ans += freq[ii].get(diff, 0) freq[i][diff] += 1 + freq[ii][diff] return ans
arithmetic-slices-ii-subsequence
[Python3] freq tables
ye15
2
120
arithmetic slices ii subsequence
446
0.399
Hard
7,914
https://leetcode.com/problems/arithmetic-slices-ii-subsequence/discuss/2596458/Python-Easy-Explanation-Using-weak-arithmetic-sequences-explanation
class Solution: # Intuition - # You travel through nums and reach a num # Count the number of weak Arithmetic Sequences you can make from this num # What are weak arithmetic sequences - > 2, 4 is a weak arithmetic sequence of diff = 2 ; 3, 4 is a weak arithmetic sequence of diff 1 # Accomodate all the weak arithmetic sequences you can make with previous nums # When you travel further you look back and check the previous nums and their weak arithmetic sequences using their diff dictionary[in python] {maps in general} # After the above step check in the diffs of previous nums the weak arithmetic sequences they can make and can they be used to make a proper arithmetic sequence by adding you current num # These weak arithmetic sequences can be added to this num to make a proper arithmetic sequence! so count this in the res : res += dp[j][diff] def numberOfArithmeticSlices(self, nums: List[int]) -> int: n = len(nums) if n <= 2: return 0 res = 0 dp = [defaultdict(int) for _ in range(n)] for i in range(1, n): for j in range(i): diff = nums[i] - nums[j] dp[i][diff] += 1 if diff in dp[j]: res += dp[j][diff] dp[i][diff] += dp[j][diff] return res
arithmetic-slices-ii-subsequence
Python Easy Explanation Using weak arithmetic sequences explanation
shiv-codes
0
11
arithmetic slices ii subsequence
446
0.399
Hard
7,915
https://leetcode.com/problems/arithmetic-slices-ii-subsequence/discuss/1455329/Python-Explained
class Solution: def numberOfArithmeticSlices(self, nums: List[int]) -> int: dp = [defaultdict(int) for _ in range(len(nums))] res = 0 for i in range(len(nums)): for j in range(i): dp[i][nums[i] - nums[j]] += dp[j][nums[i] - nums[j]] + 1 res += dp[j][nums[i] - nums[j]] return res
arithmetic-slices-ii-subsequence
[Python] Explained
kyttndr
0
183
arithmetic slices ii subsequence
446
0.399
Hard
7,916
https://leetcode.com/problems/number-of-boomerangs/discuss/355205/Solution-in-Python-3
class Solution: def numberOfBoomerangs(self, p: List[List[int]]) -> int: L, t = len(p), 0 D = [[0]*L for i in range(L)] for i in range(L): E = {} for j in range(L): if j > i: D[i][j] = D[j][i] = (p[j][0]-p[i][0])**2 + (p[j][1]-p[i][1])**2 E[D[i][j]] = E[D[i][j]] + 1 if D[i][j] in E else 1 t += sum(r*(r-1) for r in E.values()) return t - Junaid Mansuri (LeetCode ID)@hotmail.com
number-of-boomerangs
Solution in Python 3
junaidmansuri
2
847
number of boomerangs
447
0.547
Medium
7,917
https://leetcode.com/problems/number-of-boomerangs/discuss/1668932/Python3-Solution-with-using-hashmap.-With-comments.
class Solution: def dist(self, p1, p2): return sqrt(pow(p1[0] - p2[0], 2) + pow(p1[1] - p2[1], 2)) def numberOfBoomerangs(self, points: List[List[int]]) -> int: res = 0 for i in range(len(points)): "cache for every point" dist_cache = collections.defaultdict(int) for j in range(len(points)): if i == j: continue dist_cache[self.dist(points[i], points[j])] += 1 for key in dist_cache: """ The formula for generating permutations given n object where we are allowed to choose r of them, is: P(n, r) = n! / (n-r)! In our case we have: n = dist_cache[key] (where key is some distance). Also we can choose 2 elements at a time: r = 2. So formula now: P(n, 2) = n! / (n-2)! Using some mathematical transformations: n! / (n-2)! = n * (n-1) * (n-2)! / (n-2)! = n * (n-1) This logic applies to each point. """ res += dist_cache[key] * (dist_cache[key] - 1) return res
number-of-boomerangs
[Python3] Solution with using hashmap. With comments.
maosipov11
0
129
number of boomerangs
447
0.547
Medium
7,918
https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/discuss/313703/Python-3
class Solution: def findDisappearedNumbers(self, nums: List[int]) -> List[int]: for n in nums: a = abs(n) - 1 if nums[a] > 0: nums[a] *= -1 return [i+1 for i in range(len(nums)) if nums[i] > 0]
find-all-numbers-disappeared-in-an-array
Python 3
slight_edge
54
7,900
find all numbers disappeared in an array
448
0.597
Easy
7,919
https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/discuss/1028043/Python-3-Lines-Beats-90-With-Comments
class Solution: def findDisappearedNumbers(self, nums: List[int]) -> List[int]: result = [i for i in range(0, len(nums)+1)] # build an array (0, 1, 2, 3, ..., n) for i in nums: result[i] = 0 # we index this array, setting "found" elements to zero return [i for i in result if i != 0] # we return results that aren't zero
find-all-numbers-disappeared-in-an-array
Python 3 Lines - Beats 90% - With Comments
dev-josh
11
1,300
find all numbers disappeared in an array
448
0.597
Easy
7,920
https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/discuss/336437/Solution-in-Python-3-(five-lines)-(-O(n)-time-)-(-O(1)-space-)
class Solution: def findDisappearedNumbers(self, n: List[int]) -> List[int]: i, L = 0, len(n) while i != L: if n[i] in [i + 1, n[n[i] - 1]]: i += 1 else: n[n[i] - 1], n[i] = n[i], n[n[i] - 1] return [i + 1 for i in range(L) if n[i] != i + 1]
find-all-numbers-disappeared-in-an-array
Solution in Python 3 (five lines) ( O(n) time ) ( O(1) space )
junaidmansuri
6
1,900
find all numbers disappeared in an array
448
0.597
Easy
7,921
https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/discuss/336437/Solution-in-Python-3-(five-lines)-(-O(n)-time-)-(-O(1)-space-)
class Solution: def findDisappearedNumbers(self, n: List[int]) -> List[int]: N = set(n) return [i for i in range(1, len(n) + 1) if i not in N] - Python 3 (LeetCode ID)@hotmail.com
find-all-numbers-disappeared-in-an-array
Solution in Python 3 (five lines) ( O(n) time ) ( O(1) space )
junaidmansuri
6
1,900
find all numbers disappeared in an array
448
0.597
Easy
7,922
https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/discuss/1849912/Python-One-Liner-Simple-and-Elegant!
class Solution(object): def findDisappearedNumbers(self, nums): return set(range(1,len(nums)+1)) - set(nums)
find-all-numbers-disappeared-in-an-array
Python - One Liner - Simple and Elegant!
domthedeveloper
5
319
find all numbers disappeared in an array
448
0.597
Easy
7,923
https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/discuss/839002/Two-solutions-in-Python%3A-hash-map-and-set-operation
class Solution: def findDisappearedNumbers(self, nums: List[int]) -> List[int]: hash_table = {} result = [] for num in nums: hash_table[num] = 1 for num in range(1, len(nums) + 1): if num not in hash_table: result.append(num) return result
find-all-numbers-disappeared-in-an-array
Two solutions in Python: hash map and set operation
meilinz
4
259
find all numbers disappeared in an array
448
0.597
Easy
7,924
https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/discuss/839002/Two-solutions-in-Python%3A-hash-map-and-set-operation
class Solution: def findDisappearedNumbers(self, nums: List[int]) -> List[int]: nums_set = set(nums) ideal_set = set(range(1, len(nums) + 1)) result = list(ideal_set - nums_set) return result
find-all-numbers-disappeared-in-an-array
Two solutions in Python: hash map and set operation
meilinz
4
259
find all numbers disappeared in an array
448
0.597
Easy
7,925
https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/discuss/2371923/1-liner-no-brainer-fast-than-95
class Solution: def findDisappearedNumbers(self, nums: List[int]) -> List[int]: return set(nums) ^ set(range(1,len(nums)+1))
find-all-numbers-disappeared-in-an-array
1 liner no brainer - fast than 95%
sunakshi132
2
145
find all numbers disappeared in an array
448
0.597
Easy
7,926
https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/discuss/404022/Python-one-liner-beats-88
class Solution: def findDisappearedNumbers(self, n: List[int]) -> List[int]: S = set(n) return [x for x in range(1, len(n)+1) if x not in S]
find-all-numbers-disappeared-in-an-array
Python one liner beats 88%
saffi
2
773
find all numbers disappeared in an array
448
0.597
Easy
7,927
https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/discuss/2580212/Python3-0(n)-optimal-Solution-Negative-marking
class Solution(object): def findDisappearedNumbers(self, nums): """ :type nums: List[int] :rtype: List[int] """ for i in range(len(nums)): x = abs(nums[i]) if x-1 < len(nums) and nums[x-1] > 0: # x-1 <len(nums) to avoid out of index # nums[x-1] > 0 to check whether it is already negative(marked) nums[x-1] = -nums[x-1] # Mark element as negative return [i+1 for i in range(len(nums)) if nums[i]>0]
find-all-numbers-disappeared-in-an-array
Python3 0(n) optimal Solution Negative marking
abhisheksanwal745
1
64
find all numbers disappeared in an array
448
0.597
Easy
7,928
https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/discuss/2360629/short-easy-and-fast-python-code-or-2-ways
class Solution: def findDisappearedNumbers(self, nums: List[int]) -> List[int]: n=len(nums)+1 return list(set(range(1,n))-set(nums))
find-all-numbers-disappeared-in-an-array
short, easy & fast python code | 2 ways
ayushigupta2409
1
79
find all numbers disappeared in an array
448
0.597
Easy
7,929
https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/discuss/2360629/short-easy-and-fast-python-code-or-2-ways
class Solution: def findDisappearedNumbers(self, nums: List[int]) -> List[int]: nums1=set(nums) n=len(nums)+1 res=[i for i in range(1,n) if i not in nums1] return res
find-all-numbers-disappeared-in-an-array
short, easy & fast python code | 2 ways
ayushigupta2409
1
79
find all numbers disappeared in an array
448
0.597
Easy
7,930
https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/discuss/2160365/Three-Line-Python-Solution
class Solution: def findDisappearedNumbers(self, nums: List[int]) -> List[int]: nums_set = set(nums) res = [i for i in range(1, len(nums)+1) if i not in nums_set] return res
find-all-numbers-disappeared-in-an-array
📌 Three-Line Python Solution
croatoan
1
101
find all numbers disappeared in an array
448
0.597
Easy
7,931
https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/discuss/2094772/Python3-O(n)-oror-O(1)-Runtime%3A-443ms-54.03
class Solution: def findDisappearedNumbers(self, nums: List[int]) -> List[int]: return self.optimalSol(nums) # O(n) || O(1) # runtime: 443ms 54.03% def optimalSol(self, nums): if not nums: return nums for num in nums: index = abs(num) - 1 nums[index] = -1 * abs(nums[index]) return [i+1 for i in range(len(nums)) if nums[i] > 0] def withBuiltInSol(self, nums): allRange = list(range(min(nums), len(nums)+1)) return list(set(allRange)-set(nums)) # ORRRR! return list(set(range(min(nums), len(nums)+1))-set(nums))
find-all-numbers-disappeared-in-an-array
Python3 O(n) || O(1) Runtime: 443ms 54.03%
arshergon
1
162
find all numbers disappeared in an array
448
0.597
Easy
7,932
https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/discuss/2074859/Python-easy-solution-or-without-space-or-T%3A-O(n)-S%3A-O(1)
class Solution: def findDisappearedNumbers(self, nums: List[int]) -> List[int]: length = len(nums) result = [] # we fetch the numbers (by index) which is appeared in the list for i in range(length): ind = abs(nums[i]) - 1 if nums[ind] > 0: nums[ind] *= -1 # we append those numbers which is non negative in the list # non negative means this value is not appeared in the list for i in range(length): if nums[i] > 0: result.append(i+1) return result
find-all-numbers-disappeared-in-an-array
[Python] easy solution | without space | T: O(n), S: O(1)
jamil117
1
77
find all numbers disappeared in an array
448
0.597
Easy
7,933
https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/discuss/1972908/O(n)-time-and-O(1)-space
class Solution: def findDisappearedNumbers(self, nums: List[int]) -> List[int]: res = [] for i in nums: x = abs(i)-1 nums[x] = -1 * abs(nums[x]) #make value negative to later know that this index value is present for i,n in enumerate(nums): if n>0: res.append(i+1) return res
find-all-numbers-disappeared-in-an-array
O(n) time and O(1) space
shvmsnju
1
216
find all numbers disappeared in an array
448
0.597
Easy
7,934
https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/discuss/1583810/Python-one-line-solution
class Solution: def findDisappearedNumbers(self, nums: List[int]) -> List[int]: return list(set(range(1,len(nums)+1))-set(nums))
find-all-numbers-disappeared-in-an-array
Python one line solution
overzh_tw
1
101
find all numbers disappeared in an array
448
0.597
Easy
7,935
https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/discuss/1433080/Python-2-solution-Both-of-them-are-O(n)-With-and-without-extra-space
class Solution: def findDisappearedNumbers(self, nums: List[int]) -> List[int]: #With Extra Space - O(n) in both space and time values, missing = set(nums), [] for i in range(1,len(nums)+1): if i not in values: missing.append(i) return missing
find-all-numbers-disappeared-in-an-array
Python 2 solution - Both of them are O(n) - With and without extra space
abrarjahin
1
313
find all numbers disappeared in an array
448
0.597
Easy
7,936
https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/discuss/1433080/Python-2-solution-Both-of-them-are-O(n)-With-and-without-extra-space
class Solution: def findDisappearedNumbers(self, nums: List[int]) -> List[int]: #Cyclic Sort - Time O(n) and space O(1) #Sort the array with Cyclic Sort start, output = 0, [] while start<len(nums): index = nums[start]-1 if 0>nums[start] or nums[start]>len(nums)+1: nums[start] = -1; start+=1 elif nums[index]!=nums[start]: nums[index], nums[start] = nums[start], nums[index] else: start+=1 for i,v in enumerate(nums): if i+1!=v: output.append(i+1) return output
find-all-numbers-disappeared-in-an-array
Python 2 solution - Both of them are O(n) - With and without extra space
abrarjahin
1
313
find all numbers disappeared in an array
448
0.597
Easy
7,937
https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/discuss/1366175/Python-Optimal-in-place-sorting-and-constant-space
class Solution: def findDisappearedNumbers(self, nums: List[int]) -> List[int]: for i in range(0, len(nums)): # check if index position (use 1-index) has the correct number and while swapping do not remove a number from its correct position. O(N) sorting in-place while i+1 != nums[i] and nums[nums[i] - 1] != nums[i]: temp = nums[i] nums[i] = nums[nums[i] - 1] nums[temp - 1] = temp # return index (1-index) position of numbers not in the right place return [i+1 for i in range(0, len(nums)) if i+1 != nums[i]]
find-all-numbers-disappeared-in-an-array
Python Optimal in-place sorting and constant space
shayansadar
1
191
find all numbers disappeared in an array
448
0.597
Easy
7,938
https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/discuss/1309630/Python3-solution
class Solution: def findDisappearedNumbers(self, nums: List[int]) -> List[int]: res=[] n=len(nums) arr=[0]*(n+1) for x in nums: arr[x]+=1 for i in range(1,n+1): if arr[i]==0: res.append(i) return res
find-all-numbers-disappeared-in-an-array
Python3 solution
ana_2kacer
1
284
find all numbers disappeared in an array
448
0.597
Easy
7,939
https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/discuss/1289355/Very-Easy-Solution-Using-Set-Calculation-(Only-two-lines)-and-faster-than-96
class Solution: def findDisappearedNumbers(self, nums: List[int]) -> List[int]: lst = [x for x in range(1,len(nums)+1)] return list(set(lst)-set(nums))
find-all-numbers-disappeared-in-an-array
Very Easy Solution Using Set Calculation (Only two lines) and faster than 96%
yjin232
1
118
find all numbers disappeared in an array
448
0.597
Easy
7,940
https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/discuss/1283940/Python-one-line-or-Faster-than-98-or-EASY-to-understand
class Solution: def findDisappearedNumbers(self, nums: List[int]) -> List[int]: return set(range(1,len(nums)+1)) - set(nums)
find-all-numbers-disappeared-in-an-array
Python one line | Faster than 98% | EASY to understand
atharvapatil
1
272
find all numbers disappeared in an array
448
0.597
Easy
7,941
https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/discuss/1237685/Easy-python-solution
class Solution: def findDisappearedNumbers(self, nums: List[int]) -> List[int]: l=set(nums) s=list() for i in range(len(nums)): if i+1 not in l: s.append(i+1) return s
find-all-numbers-disappeared-in-an-array
Easy python solution
Sneh17029
1
660
find all numbers disappeared in an array
448
0.597
Easy
7,942
https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/discuss/750259/Python-Time-limit-exceeded
class Solution: def findDisappearedNumbers(self, nums: List[int]) -> List[int]: new_arr = [] x = range(1, len(nums)+1) for j in x: if j not in nums: new_arr.append(j) return new_arr
find-all-numbers-disappeared-in-an-array
Python - Time limit exceeded
PSSABISHEK
1
122
find all numbers disappeared in an array
448
0.597
Easy
7,943
https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/discuss/2846309/Beginners-friendly-using-bitwise-operand-Python
class Solution: def findDisappearedNumbers(self, nums: List[int]) -> List[int]: ans = [] n = len(nums) for i in range(len(ans)+1): while len(ans)!=n: i +=1 ans.append(i) return set(ans)^set(nums)
find-all-numbers-disappeared-in-an-array
Beginners friendly using bitwise operand Python
Belyua
0
3
find all numbers disappeared in an array
448
0.597
Easy
7,944
https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/discuss/2837551/Simple-python-solution
class Solution: def findDisappearedNumbers(self, nums: List[int]) -> List[int]: result = [] for num in nums: index = abs(num)-1 nums[index] = -1* abs(nums[index]) for i,num in enumerate(nums): if num>0: result.append(i+1) return result """ Brute Force approach: O(N) time and O(N) Space # n = len(nums) # nums = set(nums) # result = [] # for i in range(1,n+1): # if i not in nums: # result.append(i) # return result """
find-all-numbers-disappeared-in-an-array
Simple python solution
BhavyaBusireddy
0
1
find all numbers disappeared in an array
448
0.597
Easy
7,945
https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/discuss/2782027/Optimized-Solution
class Solution: def findDisappearedNumbers(self, nums: List[int]) -> List[int]: for n in nums: i = abs(n) - 1 nums[i] = -1 * abs(nums[i]) res = [] for i, n in enumerate(nums): if n > 0: res.append(i + 1) return res
find-all-numbers-disappeared-in-an-array
Optimized Solution
swaruptech
0
3
find all numbers disappeared in an array
448
0.597
Easy
7,946
https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/discuss/2741144/Simple-Python-Code
class Solution: def findDisappearedNumbers(self, nums: List[int]) -> List[int]: arr = set(nums) n = len(nums) list3 = [] for i in range(1,n+1): if i not in arr: list3.append(i) return list3
find-all-numbers-disappeared-in-an-array
Simple Python Code
dnvavinash
0
8
find all numbers disappeared in an array
448
0.597
Easy
7,947
https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/discuss/2709865/Python-solution
class Solution: def findDisappearedNumbers(self, arr: List[int]) -> List[int]: i=0 while i<len(arr): correct=arr[i]-1 if arr[i]!=arr[correct]: arr[i],arr[correct]=arr[correct],arr[i] else: i+=1 ans=[] for i in range(len(arr)): if arr[i]!=i+1: ans.append(i+1) return ans
find-all-numbers-disappeared-in-an-array
Python solution
Surenavyasri
0
8
find all numbers disappeared in an array
448
0.597
Easy
7,948
https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/discuss/2692921/Symmetric-Difference-%2B-List-Comprehension
class Solution: def findDisappearedNumbers(self, nums: List[int]) -> List[int]: return sorted(set(nums).symmetric_difference(set(x+1 for x in range(len(nums)))))
find-all-numbers-disappeared-in-an-array
Symmetric Difference + List Comprehension
keioon
0
5
find all numbers disappeared in an array
448
0.597
Easy
7,949
https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/discuss/2691315/Python-solution
class Solution: def findDisappearedNumbers(self, nums: List[int]) -> List[int]: arr = dict() listof =[] for i in range(1,len(nums)+1): arr[i] =0 for num in nums: arr[num] =1 for key, val in arr.items(): if val == 0: listof.append(key) return listof
find-all-numbers-disappeared-in-an-array
Python solution
Sheeza
0
3
find all numbers disappeared in an array
448
0.597
Easy
7,950
https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/discuss/2688084/Cyclic-Sort-Solution
class Solution: def findDisappearedNumbers(self, nums: List[int]) -> List[int]: N = len(nums) index = 0 while index < N: temp = nums[index] - 1 if nums[index] != nums[temp]: nums[temp], nums[index] = nums[index], nums[temp] else: index += 1 back = 0 for i in range(N): if nums[i] != (i + 1): nums[back] = i + 1 back += 1 return nums[ : back]
find-all-numbers-disappeared-in-an-array
Cyclic Sort Solution
user6770yv
0
6
find all numbers disappeared in an array
448
0.597
Easy
7,951
https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/discuss/2681282/Python-Easy-One-Line-Solution-or-O(n)
class Solution: def findDisappearedNumbers(self, nums: List[int]) -> List[int]: return set(n for n in range(1, len(nums) + 1)) - set(nums)
find-all-numbers-disappeared-in-an-array
Python Easy One Line Solution | O(n)
remenraj
0
4
find all numbers disappeared in an array
448
0.597
Easy
7,952
https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/discuss/2665554/Easy-Solution-oror-Python
class Solution: def findDisappearedNumbers(self, nums: List[int]) -> List[int]: lst=[] num=set(nums) for i in range(1,len(nums)+1): if i not in num: lst.append(i) return(lst)
find-all-numbers-disappeared-in-an-array
Easy Solution || Python
ankitr8055
0
2
find all numbers disappeared in an array
448
0.597
Easy
7,953
https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/discuss/2651074/Python-Easy-and-Explained
class Solution: def findDisappearedNumbers(self, nums: List[int]) -> List[int]: return set(range(1, len(nums)+1)) - set(nums)
find-all-numbers-disappeared-in-an-array
Python Easy and Explained
kunallunia22
0
1
find all numbers disappeared in an array
448
0.597
Easy
7,954
https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/discuss/2645132/Easy-Hash-table-Approach-in-O(n)
class Solution: def findDisappearedNumbers(self, nums: List[int]) -> List[int]: countDict={num:0 for num in range(1,len(nums)+1)} for num in nums: countDict[num]=1 result = [key for key in countDict if countDict[key]==0] return result
find-all-numbers-disappeared-in-an-array
Easy Hash table Approach in O(n)
AyeshaJahangir
0
4
find all numbers disappeared in an array
448
0.597
Easy
7,955
https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/discuss/2640992/Python3-O(n)-time-%2B-O(1)-space-solution
class Solution: def findDisappearedNumbers(self, nums: List[int]) -> List[int]: res = [] for i in range(len(nums)): nums[(nums[i]-1)%len(nums)] += len(nums) for i in range(len(nums)): if nums[i] <= len(nums): res.append(i+1) return res
find-all-numbers-disappeared-in-an-array
Python3 O(n) time + O(1) space solution
ys2674
0
91
find all numbers disappeared in an array
448
0.597
Easy
7,956
https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/discuss/2581482/Python-easy-solution-oror-O(n)-oror-92-Faster-oror-Counter-oror
class Solution: def findDisappearedNumbers(self, A: List[int]) -> List[int]: n=len(A) A = Counter(A) temp = [] for i in range(1,n+1): if A[i]==0: temp.append(i) return temp
find-all-numbers-disappeared-in-an-array
Python easy solution || O(n) || 92% Faster || Counter || ✅
Akash_chavan
0
71
find all numbers disappeared in an array
448
0.597
Easy
7,957
https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/discuss/2405252/Python-2-lines-with-short-explanation
class Solution: def findDisappearedNumbers(self, nums: List[int]) -> List[int]: numSet = set(nums) return [n for n in range(1, len(nums) + 1) if n not in numSet]
find-all-numbers-disappeared-in-an-array
Python 2 lines with short explanation
ichung08
0
67
find all numbers disappeared in an array
448
0.597
Easy
7,958
https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/discuss/2403583/Python-Implementation-Using-List-Comprehension-and-Enumeration
class Solution: def findDisappearedNumbers(self, nums: List[int]) -> List[int]: for i in range(len(nums)): val = abs(nums[i]) - 1 if nums[val] > 0: nums[val] *= -1 return [ind + 1 for ind, v in enumerate(nums) if nums[ind] > 0]
find-all-numbers-disappeared-in-an-array
Python Implementation Using List Comprehension & Enumeration
Abhi_-_-
0
40
find all numbers disappeared in an array
448
0.597
Easy
7,959
https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/discuss/2346016/Python-oror-89-oror-Two-Lines-oror-Sets
class Solution: def findDisappearedNumbers(self, nums: List[int]) -> List[int]: theSet = {i for i in range(1,len(nums)+1)} return set.difference(theSet,set(nums))
find-all-numbers-disappeared-in-an-array
Python || 89% || Two Lines || Sets
tq326
0
55
find all numbers disappeared in an array
448
0.597
Easy
7,960
https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/discuss/2137891/Python-oneliner
class Solution: def findDisappearedNumbers(self, nums: List[int]) -> List[int]: return {x for x in range(1,len(nums)+1)} - set(nums)
find-all-numbers-disappeared-in-an-array
Python oneliner
StikS32
0
84
find all numbers disappeared in an array
448
0.597
Easy
7,961
https://leetcode.com/problems/delete-node-in-a-bst/discuss/543124/Python-O(-h-)-with-BST-property.-85%2B-w-Comment
class Solution: def deleteNode(self, root: TreeNode, key: int) -> TreeNode: if not root: return None if root.val > key: # Target node is smaller than currnet node, search left subtree root.left = self.deleteNode( root.left, key ) elif root.val < key: # Target node is larger than currnet node, search right subtree root.right = self.deleteNode( root.right, key ) else: # Current node is target node if (not root.left) or (not root.right): # At least one child is empty # Target node is replaced by either non-empty child or None root = root.left if root.left else root.right else: # Both two childs exist # Target node is replaced by smallest element of right subtree cur = root.right while cur.left: cur = cur.left root.val = cur.val root.right = self.deleteNode( root.right, cur.val ) return root
delete-node-in-a-bst
Python O( h ) with BST property. 85%+ [w/ Comment ]
brianchiang_tw
8
605
delete node in a bst
450
0.5
Medium
7,962
https://leetcode.com/problems/delete-node-in-a-bst/discuss/822263/Python3-iterative-and-recursive
class Solution: def deleteNode(self, root: TreeNode, key: int) -> TreeNode: # search for node node = root parent = left = None while node: if node.val < key: parent, node, left = node, node.right, False elif node.val > key: parent, node, left = node, node.left, True else: break # found # delete the node if node: # if found if not node.left or not node.right: if parent: if left: parent.left = node.left or node.right else: parent.right = node.left or node.right else: return node.left or node.right else: temp = parent = node node = node.left if not node.right: parent.left = node.left else: while node.right: parent, node = node, node.right parent.right = node.left temp.val = node.val return root
delete-node-in-a-bst
[Python3] iterative & recursive
ye15
5
242
delete node in a bst
450
0.5
Medium
7,963
https://leetcode.com/problems/delete-node-in-a-bst/discuss/822263/Python3-iterative-and-recursive
class Solution: def deleteNode(self, root: Optional[TreeNode], key: int) -> Optional[TreeNode]: if root: if root.val < key: root.right = self.deleteNode(root.right, key) elif root.val == key: if not root.left or not root.right: return root.left or root.right node = root.right while node.left: node = node.left root.val = node.val root.right = self.deleteNode(root.right, node.val) else: root.left = self.deleteNode(root.left, key) return root
delete-node-in-a-bst
[Python3] iterative & recursive
ye15
5
242
delete node in a bst
450
0.5
Medium
7,964
https://leetcode.com/problems/delete-node-in-a-bst/discuss/1591075/Well-Coded-oror-Clean-and-Concise-oror-Easy-to-understand
class Solution: def deleteNode(self, root: Optional[TreeNode], key: int) -> Optional[TreeNode]: if root is None: return if key<root.val: root.left = self.deleteNode(root.left,key) elif key>root.val: root.right = self.deleteNode(root.right,key) else: if root.left is None: return root.right if root.right is None: return root.left tmp = root.right mini= tmp.val while tmp.left!=None: tmp = tmp.left mini= tmp.val root.val = mini root.right = self.deleteNode(root.right,root.val) return root
delete-node-in-a-bst
📌📌 Well-Coded || Clean & Concise || Easy-to-understand 🐍
abhi9Rai
2
144
delete node in a bst
450
0.5
Medium
7,965
https://leetcode.com/problems/delete-node-in-a-bst/discuss/1857289/python-easy-recursive-solution
class Solution: @staticmethod def nextval(node): '''Finds inorder successor''' if node.left: return Solution.nextval(node.left) return node.val def deleteNode(self, root: Optional[TreeNode], key: int) -> Optional[TreeNode]: if not root: return root if root.val == key: if not root.left: return root.right if not root.right: return root.left root.val = Solution.nextval(root.right) '''Copying inorder successor value''' root.right = self.deleteNode(root.right,root.val) return root if root.val > key: root.left = self.deleteNode(root.left,key) else: root.right = self.deleteNode(root.right,key) return root '''If any doubt regarding solution please ask in comment section if you like it please upvote '''
delete-node-in-a-bst
python easy recursive solution
coder_harshit
1
34
delete node in a bst
450
0.5
Medium
7,966
https://leetcode.com/problems/delete-node-in-a-bst/discuss/1807579/Python3-O(h)-time-and-O(1)-space
class Solution: def findMin(self, root: TreeNode) -> TreeNode: prev = None while root != None: prev = root root = root.left return prev def deleteHelper(self, node: Optional[TreeNode], parent: TreeNode, key: int): # if key does not exist within the BST if not node: return if node.val == key: nodeToMakeChild = None if node.right: # add the left subtree of the node to be deleted to the minimum node of the right subtree minRight = self.findMin(node.right) minRight.left = node.left nodeToMakeChild = node.right else: # use left node if right does not exist nodeToMakeChild = node.left # re-attach branch to BST if node.val < parent.val: parent.left = nodeToMakeChild else: parent.right = nodeToMakeChild return # move to correct node by ordering of BST if node.val < key: self.deleteHelper(node.right, node, key) else: self.deleteHelper(node.left, node, key) def deleteNode(self, root: Optional[TreeNode], key: int) -> Optional[TreeNode]: if not root: return None # edge case if root.val == key: if root.right: right = root.right # find minimum of right subtree to add left subtree as left child minRight = self.findMin(right) minRight.left = root.left return right elif root.left: return root.left else: return None if root.val < key: self.deleteHelper(root.right, root, key) else: self.deleteHelper(root.left, root, key) return root
delete-node-in-a-bst
Python3 O(h) time and O(1) space
9D76
1
46
delete node in a bst
450
0.5
Medium
7,967
https://leetcode.com/problems/delete-node-in-a-bst/discuss/1160514/Much-easier-solution-in-Python-with-comments
class Solution: def deleteNode(self, node: TreeNode, key: int) -> TreeNode: if not node: return None elif node.val > key: node.left = self.deleteNode(node.left, key) elif node.val < key: node.right = self.deleteNode(node.right, key) else: # If not left child, return right child if not node.left: return node.right # If not right child, return left child elif not node.right: return node.left # Both children are present, replce node with inorder successor else: # finding the inorder successor ptr = node.right while ptr.left: ptr = ptr.left # ptr is now the in-order successor # Delete the successor from the node's right sub-tree # because that will now be used as the root ptr.right = self.deleteNode(node.right, ptr.val) # Add the left sub-tree of the node as the # successor's left child ptr.left = node.left return ptr return node
delete-node-in-a-bst
Much easier solution in Python with comments
rohitpatwa
1
231
delete node in a bst
450
0.5
Medium
7,968
https://leetcode.com/problems/delete-node-in-a-bst/discuss/821783/Python-iterative-O(h)-time-O(1)-space
class Solution: def deleteNode(self, root: TreeNode, key: int) -> TreeNode: # search for matching node i.e. node to delete # track parent and whether node is the left or right of parent curr, prev, is_left = root, TreeNode(None, root, None), True while curr and key != curr.val: prev = curr if key < curr.val: curr = curr.left is_left = True else: curr = curr.right is_left = False # no matching node if curr is None: return root # move node.right of the matching node to the right-most node of node.left to_delete = curr if curr.left: to_keep = curr.right curr = curr.left while curr.right: curr = curr.right curr.right = to_keep # determine which child node of matching node will replace matching node valid_node = to_delete.left if to_delete.left else to_delete.right # delete matching node by changing the parent left/right of the matching node with the replacement node if prev.val is None: # if root would be deleted, return new root return valid_node elif is_left: prev.left = valid_node else: prev.right = valid_node return root
delete-node-in-a-bst
Python iterative O(h) time O(1) space
geordgez
1
178
delete node in a bst
450
0.5
Medium
7,969
https://leetcode.com/problems/delete-node-in-a-bst/discuss/2732163/striver-approach
class Solution: def deleteNode(self, root: Optional[TreeNode], key: int) -> Optional[TreeNode]: if root is None : return None if root.val == key: return self.helper(root) dummy = root while root is not None: if root.val > key: if root.left is not None and root.left.val == key: root.left = self.helper(root.left) break else: root = root.left else: if root.right is not None and root.right.val == key: root.right = self.helper(root.right) break else: root = root.right return dummy def helper(self, root): if root.left is None: return root.right if root.right is None: return root.left rightChild = root.right lastRight = self.findLastRight(root.left) lastRight.right = rightChild return root.left def findLastRight(self, root): if root.right is None: return root return self.findLastRight(root.right)
delete-node-in-a-bst
striver approach
hacktheirlives
0
8
delete node in a bst
450
0.5
Medium
7,970
https://leetcode.com/problems/delete-node-in-a-bst/discuss/2589025/Python-Easy-to-Understand-Recursive-Solution-with-comments
class Solution: def deleteNode(self, root: Optional[TreeNode], key: int) -> Optional[TreeNode]: if not root: return None if key > root.val: root.right = self.deleteNode(root.right,key) elif key < root.val: root.left = self.deleteNode(root.left,key) else: # Handling Case where the node has 0 or 1 child if not root.left: return root.right elif not root.right: return root.left #Handling case where the node has 2 children and replacing root with the minimum value node else: minNode = self.minValNode(root.right) root.val = minNode.val root.right = self.deleteNode(root.right,minNode.val) return root #Helper function to find the minimum value node def minValNode(self,root): curr = root while curr and curr.left: curr = curr.left return curr
delete-node-in-a-bst
Python Easy to Understand Recursive Solution with comments
Ron99
0
19
delete node in a bst
450
0.5
Medium
7,971
https://leetcode.com/problems/delete-node-in-a-bst/discuss/2325745/python-non-recursive-not-change-the-node-value
class Solution: def deleteNode(self, root: Optional[TreeNode], key: int) -> Optional[TreeNode]: par = None deln = root while(deln and deln.val != key): if key < deln.val: par = deln deln = deln.left else: par = deln deln = deln.right if(deln == None): return root newnode = None if deln.left == None: newnode = deln.right elif deln.right == None: newnode = deln.left else: subs = deln.right if subs.left: par2 = None while(subs.left): par2 = subs subs = subs.left par2.left = subs.right subs.left = deln.left subs.right = deln.right newnode = subs else: subs.left = deln.left newnode = subs if(par): if deln == par.left: par.left = newnode else: par.right = newnode return newnode if deln == root else root
delete-node-in-a-bst
python non recursive not change the node value
487o
0
18
delete node in a bst
450
0.5
Medium
7,972
https://leetcode.com/problems/delete-node-in-a-bst/discuss/2164608/2-method-python-solution-in-python-Java
class Solution: def deleteNode(self, root: Optional[TreeNode], key: int) -> Optional[TreeNode]: # idea: recursion to find target, to delete the target node and update tree, # edge case: empty tree if root==None: return None #if current value is greater than key, search left child if root.val>key: root.left = self.deleteNode(root.left,key) #if current value is smaller than key, search right child elif root.val<key: root.right = self.deleteNode(root.right,key) #if current value matches the key, do removing: else: #if this node has only left child, just skip this node and connect its left child if root.right == None: root = root.left return root #if this node has only right child, same sense if root.left == None: root = root.right return root # if this node has both left and right child, #find the min value that is greater than current node, #copy value to the current node, delete that min_value node: # to find a greater value node, go right first, then go left as deep as possible # this is the way to find leftmost node, # which is the successor of inorder traversal of current root node = root.right # we must let node move forward, not root, because we need to return root in the end, so we cannot modify root here. while node.left: node = node.left root.val = node.val root.right = self.deleteNode(root.right, root.val) return root
delete-node-in-a-bst
2 method python solution in python, Java
JunyiLin
0
42
delete node in a bst
450
0.5
Medium
7,973
https://leetcode.com/problems/delete-node-in-a-bst/discuss/2164608/2-method-python-solution-in-python-Java
class Solution: def deleteNode(self, root: Optional[TreeNode], key: int) -> Optional[TreeNode]: if not root: return None dummy = root prev = None while root and root.val!=key: prev = root if root.val>key: root = root.left else: root = root.right # the tree does not contain a node with key value if not root: return dummy # prev is still None, it means the root node is the node to remove if not prev: return self.my_delete(root) # else, prev is not None, the node to remove is deeper down # and if the node to remove is the left child of prev, we just modify the address of prev.left to skip that node if prev.left == root: prev.left = self.my_delete(root) # if the node to remove is the right child of prev, the same sense else: prev.right = self.my_delete(root) # in the end, return the original tree return dummy def my_delete(self, root): # if the node to remove has no left tree, we just return its right tree if not root.left: return root.right # same sense elif not root.right: return root.left # if this node has both left and right child, we have to do something more else: p, q = root, root.right while q.left: p = q q = q.left root.val = q.val if p != root: p.left = q.right else: p.right = q.right # after we update this subtree, return root address, it's already a tree with target node removed. return root
delete-node-in-a-bst
2 method python solution in python, Java
JunyiLin
0
42
delete node in a bst
450
0.5
Medium
7,974
https://leetcode.com/problems/delete-node-in-a-bst/discuss/2155776/Clean-recursive-solution-in-Python
class Solution: def deleteNode(self, root: Optional[TreeNode], key: int) -> Optional[TreeNode]: if (root == None): return None if (root.val == key): # 1. shift to right child if left child is null if (root.left == None): return root.right # 2. shift to left child if right child is null if (root.right == None): return root.left # 3. if both children exist, find min node of right child, remove the min right child, and swap the two nodes minNode = self.getMin(root.right) root.right = self.deleteNode(root.right, minNode.val) minNode.left = root.left minNode.right = root.right root = minNode # recursively find and delete the node with key value is left subtreee elif (root.val > key): root.left = self.deleteNode(root.left, key) # recursively find and delete the node with key value is right subtreee elif (root.val < key): root.right = self.deleteNode(root.right, key) return root def getMin(self, root): while (root.left): root = root.left return root
delete-node-in-a-bst
Clean recursive solution in Python
leqinancy
0
23
delete node in a bst
450
0.5
Medium
7,975
https://leetcode.com/problems/delete-node-in-a-bst/discuss/2064751/Iterative-node-manipulation-Python-solution-(not-value-copy)
class Solution: def deleteNode(self, root: Optional[TreeNode], key: int) -> Optional[TreeNode]: node = root parent = None while node: # search node if node.val == key: break parent = node if node.val > key: node = node.left else: node = node.right if not node: # not found return root if node.left: # found, delete node by placing predecessor in its place prePar = node # parent of predecessor pre = node.left if pre.right: while pre.right: prePar = pre pre = pre.right prePar.right = pre.left # delete predecessor from its parent pre.left = node.left pre.right = node.right newnode = pre else: # move right child to its place newnode = node.right if parent: if parent.left == node: parent.left = newnode else: parent.right = newnode else: root = newnode return root
delete-node-in-a-bst
Iterative node manipulation Python solution (not value copy)
pcdpractice01
0
11
delete node in a bst
450
0.5
Medium
7,976
https://leetcode.com/problems/delete-node-in-a-bst/discuss/2050989/Python-recursive
class Solution: def findSuccessor(self, root): root = root.right while root.left: root = root.left return root def findPredecessor(self, root): root = root.left while root.right: root = root.right return root def deleteNode(self, root: Optional[TreeNode], key: int) -> Optional[TreeNode]: if not root: return None if key < root.val: root.left = self.deleteNode(root.left, key) elif key > root.val: root.right = self.deleteNode(root.right, key) else: if not root.left and not root.right: return None if root.left: predecessor = self.findPredecessor(root) root.val = predecessor.val root.left = self.deleteNode(root.left, predecessor.val) else: successor = self.findSuccessor(root) root.val = successor.val root.right = self.deleteNode(root.right, successor.val) return root
delete-node-in-a-bst
Python, recursive
blue_sky5
0
49
delete node in a bst
450
0.5
Medium
7,977
https://leetcode.com/problems/delete-node-in-a-bst/discuss/1803291/Python-or-solution-with-3-situations
class Solution: def deleteNode(self, root: Optional[TreeNode], key: int) -> Optional[TreeNode]: def findMin(root: Optional[TreeNode]): if not root.left: return root return findMin(root.left) if not root: return None if root.val == key: # If the node is at the end of the BST if not root.left and not root.right: return None # If the node still have one and only child node if not root.left: return root.right if not root.right: return root.left # if the node still have 2 nodes, find the smallest node in the node.right and replace the node minNode = findMin(root.right) root.right = self.deleteNode(root.right, minNode.val) minNode.right = root.right minNode.left = root.left root = minNode if root.val < key: root.right = self.deleteNode(root.right, key) if root.val > key: root.left = self.deleteNode(root.left, key) return root
delete-node-in-a-bst
Python | solution with 3 situations
Fayeyf
0
33
delete node in a bst
450
0.5
Medium
7,978
https://leetcode.com/problems/delete-node-in-a-bst/discuss/1782701/Python3-clean-solution
class Solution: def deleteNode(self, root: Optional[TreeNode], key: int) -> Optional[TreeNode]: if not root: return if root.val==key: if not root.right: return root.left if not root.left: return root.right temp=root.right while temp.left: temp=temp.left root.val=temp.val root.right=self.deleteNode(root.right,temp.val) elif key<root.val: root.left=self.deleteNode(root.left,key) else: root.right=self.deleteNode(root.right,key) return root
delete-node-in-a-bst
Python3 clean solution
Karna61814
0
23
delete node in a bst
450
0.5
Medium
7,979
https://leetcode.com/problems/delete-node-in-a-bst/discuss/1728259/Python3-or-DFS
class Solution: def deleteNode(self, root: Optional[TreeNode], key: int) -> Optional[TreeNode]: return self.helper(root,key) def helper(self,root,key): if not root: return if root.val==key: if not root.left: return root.right else: curr,temp=root.left,root.right while curr.right: curr=curr.right curr.right=temp return root.left if root.val>key: root.left=self.helper(root.left,key) else: root.right=self.helper(root.right,key) return root
delete-node-in-a-bst
[Python3] | DFS
swapnilsingh421
0
31
delete node in a bst
450
0.5
Medium
7,980
https://leetcode.com/problems/delete-node-in-a-bst/discuss/1690739/450.-Delete-Node-in-a-BST-via-Recursion
class Solution: def deleteNode(self, root, key): if not root: return root if root.val == key: if not root.left: return root.right ### if this root has right sub-tree only, then directly return this right sub-tree if not root.right: return root.left minNode = self.findMin(root.right) minNode.right = self.deleteNode(root.right, minNode.val) minNode.left = root.left return minNode elif root.val < key: root.right = self.deleteNode(root.right, key) ### key is large, we need to search for right sub-tree and it will return node root.right or None in some cases else: root.left = self.deleteNode(root.left, key) ### similar to above, we link the updated left sub-tree to the left of original root. return root def findMin(self, root): while root.left: root = root.left return root
delete-node-in-a-bst
450. Delete Node in a BST via Recursion
zwang198
0
31
delete node in a bst
450
0.5
Medium
7,981
https://leetcode.com/problems/delete-node-in-a-bst/discuss/1672576/Detailed-Python-solution-%2B-explanation-%2B-Kotlin
class Solution: def deleteNode( self, root: Optional[TreeNode], key: int, parent=None ) -> Optional[TreeNode]: curr = root while curr: if curr.val > key: parent = curr curr = curr.left elif curr.val < key: parent = curr curr = curr.right else: # if both children if curr.left and curr.right: curr.val = self.min_node_finder(curr.right) # we change only value as otherwise we'll # remove `left` and `right` nodes as well self.deleteNode(curr.right, curr.val, curr) # if root is our target &amp;&amp; only one child exists. # If 2 children -> case above will catch it elif not parent: if curr.left: curr.right = curr.left.right curr.val = curr.left.val curr.left = curr.left.left elif curr.right: curr.left = curr.right.left curr.val = curr.right.val curr.right = curr.right.right else: # [0] root = None elif parent.left == curr: parent.left = curr.left if curr.left else curr.right elif parent.right == curr: parent.right = curr.left if curr.left else curr.right break return root def min_node_finder(self, node): curr = node while curr.left: curr = curr.left return curr.val
delete-node-in-a-bst
Detailed Python solution + explanation + Kotlin
SleeplessChallenger
0
60
delete node in a bst
450
0.5
Medium
7,982
https://leetcode.com/problems/delete-node-in-a-bst/discuss/1432593/Python3-Recursive-Solution-O(h)
class Solution: def deleteNode(self, root: Optional[TreeNode], key: int) -> Optional[TreeNode]: if not root: return None if root.val == key: # first case - no childrens if not root.left and not root.right: return None # second case - there is one of chlidren (left or right) if not root.left: return root.right if not root.right: return root.left # third case - there are both childrens (left and right) tmp = root.left while tmp.right: tmp = tmp.right root.val = tmp.val root.left = self.deleteNode(root.left, root.val) if root.val > key: root.left = self.deleteNode(root.left, key) else: root.right = self.deleteNode(root.right, key) return root
delete-node-in-a-bst
[Python3] Recursive Solution O(h)
maosipov11
0
72
delete node in a bst
450
0.5
Medium
7,983
https://leetcode.com/problems/sort-characters-by-frequency/discuss/1024318/Python3-Solution-or-24-MS-Runtime-or-15.2-MB-Memoryor-Easy-to-understand-solution
class Solution: def frequencySort(self, s: str) -> str: ans_str = '' # Find unique characters characters = set(s) counts = [] # Count their frequency for i in characters: counts.append([i,s.count(i)]) # Sort characters according to their frequency counts = sorted(counts, key= lambda x: x[1], reverse = True) # Generate answer string by multiplying frequency count with the character for i,j in counts: ans_str += i*j return ans_str
sort-characters-by-frequency
Python3 Solution | 24 MS Runtime | 15.2 MB Memory| Easy to understand solution
dakshal33
5
401
sort characters by frequency
451
0.686
Medium
7,984
https://leetcode.com/problems/sort-characters-by-frequency/discuss/2056635/Python-simple-solution
class Solution: def frequencySort(self, s: str) -> str: ans = '' l = sorted(list(set(s)), key=s.count, reverse=True) for i in l: ans += i * s.count(i) return ans
sort-characters-by-frequency
Python simple solution
StikS32
3
147
sort characters by frequency
451
0.686
Medium
7,985
https://leetcode.com/problems/sort-characters-by-frequency/discuss/1733458/python-easy-to-read-and-understand
class Solution: def frequencySort(self, s: str) -> str: d = {} for ch in s: d[ch] = d.get(ch, 0) + 1 pq = [] for key in d: heapq.heappush(pq, (-d[key], key)) ans = '' while pq: cnt, ch = heapq.heappop(pq) while cnt < 0: ans += ch cnt += 1 return ans
sort-characters-by-frequency
python easy to read and understand
sanial2001
2
179
sort characters by frequency
451
0.686
Medium
7,986
https://leetcode.com/problems/sort-characters-by-frequency/discuss/945658/Python3-Explanation-Runtime-And-Space-Analysis-O(n)-TimeO(1)-Space
class Solution: def frequencySort(self, s: str) -> str: return "".join([letter * frequency for letter, frequency in sorted(collections.Counter(s).items(), key = lambda x: x[1], reverse = True)])
sort-characters-by-frequency
[Python3] Explanation - Runtime And Space Analysis - O(n) Time/O(1) Space
numiek
2
86
sort characters by frequency
451
0.686
Medium
7,987
https://leetcode.com/problems/sort-characters-by-frequency/discuss/945658/Python3-Explanation-Runtime-And-Space-Analysis-O(n)-TimeO(1)-Space
class Solution: def frequencySort(self, s: str) -> str: character_to_index = {} characters_with_frequency = [] for character in s: if ( character not in character_to_index ): character_to_index[character] = len(characters_with_frequency) characters_with_frequency.append([character, 1]) else: index = character_to_index[character] characters_with_frequency[index][1] += 1 frequency = characters_with_frequency[index][1] if ( index > 0 and characters_with_frequency[index - 1][1] <= frequency ): while ( index > 0 and characters_with_frequency[index - 1][1] <= frequency ): character_to_index[characters_with_frequency[index - 1][0]] = index characters_with_frequency[index] = characters_with_frequency[index - 1] index -= 1 character_to_index[character] = index characters_with_frequency[index] = [character, frequency] return "".join([character * frequency for character, frequency in characters_with_frequency])
sort-characters-by-frequency
[Python3] Explanation - Runtime And Space Analysis - O(n) Time/O(1) Space
numiek
2
86
sort characters by frequency
451
0.686
Medium
7,988
https://leetcode.com/problems/sort-characters-by-frequency/discuss/2648566/Python-Solution-oror-Bucket-Sort-oror-Easy-explanation
class Solution: def frequencySort(self, s: str) -> str: dic = {} for ch in s: if ch not in dic: dic[ch]=0 dic[ch]+=1 freq = {} for key,val in dic.items(): if val not in freq: freq[val] = [] freq[val].append(key) res = "" i=len(s) while i>=0: if i in freq: for val in freq[i]: res += i*val i-=1 return res
sort-characters-by-frequency
Python Solution || Bucket Sort || Easy explanation
aryan_codes_here
1
151
sort characters by frequency
451
0.686
Medium
7,989
https://leetcode.com/problems/sort-characters-by-frequency/discuss/1958498/Python-Counter-oror-O(n)-Time-Complexity-oror-O(1)-Space-Complexity
class Solution: def frequencySort(self, s: str) -> str: data = Counter(s) data = sorted(data.items(), key=lambda x:-x[1]) ans='' for i in data: ans += i[0]*i[1] &nbsp; &nbsp; &nbsp; &nbsp;return ans
sort-characters-by-frequency
Python - Counter || O(n) Time Complexity || O(1) Space Complexity
avinash0007
1
74
sort characters by frequency
451
0.686
Medium
7,990
https://leetcode.com/problems/sort-characters-by-frequency/discuss/1927437/8-lines-of-code-using-HashMap-and-sorting
class Solution: def frequencySort(self, s: str) -> str: fq = {} for i in s: fq[i] = 1 + fq.get(i, 0) tp = [(k, v) for k, v in fq.items()] c = list(sorted(tp, key=lambda item: item[1], reverse=True)) res = '' for j, f in c: res = res + (j * f) return res
sort-characters-by-frequency
8 lines of code using HashMap and sorting
ankurbhambri
1
80
sort characters by frequency
451
0.686
Medium
7,991
https://leetcode.com/problems/sort-characters-by-frequency/discuss/1892719/Easy-python-solution-with-step-by-step-explanation.
class Solution: def frequencySort(self, s: str) -> str: #creating a dictionary for storing the number of occurences of various alphabets in 's' mydict = {} for i in s: if i in mydict: mydict[i] += 1 else: mydict[i] = 1 heap = [] heapify(heap) #creating a max heap with the alphabets and its occurences for key,value in mydict.items(): heappush(heap,(-1*value,key)) res = '' #finally adding the keys(alphabets) for values(occurences) number of times into the result while len(heap): value,key = heappop(heap) res += key * (-1*value) return res
sort-characters-by-frequency
Easy python solution with step-by-step explanation.
1903480100017_A
1
73
sort characters by frequency
451
0.686
Medium
7,992
https://leetcode.com/problems/sort-characters-by-frequency/discuss/1534304/Python-Faster-than-97%2B-Solution
class Solution: def frequencySort(self, s: str) -> str: c = collections.Counter(s) res = [] for string, times in c.items(): res.append(string * times) def magic(i): return len(i) res.sort(reverse = True, key = magic) return "".join(res)
sort-characters-by-frequency
Python Faster than 97%+ Solution
aaffriya
1
150
sort characters by frequency
451
0.686
Medium
7,993
https://leetcode.com/problems/sort-characters-by-frequency/discuss/1534000/Python-or-Easy
class Solution: def frequencySort(self, s: str) -> str: count = Counter(s) keys = sorted( count.keys(), reverse = True, key = lambda x:count[x] ) return ''.join([i*count[i] for i in keys])
sort-characters-by-frequency
Python | Easy
mshanker
1
79
sort characters by frequency
451
0.686
Medium
7,994
https://leetcode.com/problems/sort-characters-by-frequency/discuss/1398455/WEEB-DOES-PYTHON
class Solution: def frequencySort(self, s: str) -> str: result = [] for char, count in Counter(s).most_common(): result += [char] * count return result
sort-characters-by-frequency
WEEB DOES PYTHON
Skywalker5423
1
96
sort characters by frequency
451
0.686
Medium
7,995
https://leetcode.com/problems/sort-characters-by-frequency/discuss/2846926/Python-easy-solution-Memory-usage-less-than-99.81-submissions
class Solution: def frequencySort(self, s: str) -> str: d={} final='' for i in s: if i not in d: d[i]=1 elif i in s: x=d.get(i) d[i]=x+1 x=dict(sorted(d.items(), key=operator.itemgetter(1),reverse=True)) for i,j in x.items(): final=final+i*j return(final)
sort-characters-by-frequency
Python easy solution - Memory usage less than 99.81% submissions
envyTheClouds
0
1
sort characters by frequency
451
0.686
Medium
7,996
https://leetcode.com/problems/sort-characters-by-frequency/discuss/2837160/Python3-easy-to-understand
class Solution: def frequencySort(self, s: str) -> str: d = Counter(s) res = '' for K, V in sorted(d.items(), key = lambda x: -x[1]): res += K*V return res
sort-characters-by-frequency
Python3 - easy to understand
mediocre-coder
0
3
sort characters by frequency
451
0.686
Medium
7,997
https://leetcode.com/problems/sort-characters-by-frequency/discuss/2833110/defaultdict-does-the-job
class Solution: def frequencySort(self, s: str) -> str: dc=defaultdict(lambda:0) for a in s: dc[a]+=1 arr=[] for a in dc: arr.append([a,dc[a]]) arr.sort(key=lambda x:x[1],reverse=True) # print(arr) ans=[] for a in arr: for i in range(a[1]): ans.append(a[0]) ans="".join(ans) return ans
sort-characters-by-frequency
defaultdict does the job
droj
0
3
sort characters by frequency
451
0.686
Medium
7,998
https://leetcode.com/problems/sort-characters-by-frequency/discuss/2811397/PYTHON-SOLUTION-EXPLAINED-LINE-BY-LINE
class Solution: def frequencySort(self, s: str) -> str: #hashmap d={} for i in s: if i in d: d[i]+=1 else: d[i]=1 #store the [frequency,character] in array l l=[] for i in d.keys(): l.append([d[i],i]) #sort l in decreasing order based on the frequency of the characters l.sort(reverse=True) #make string of characters ans="" for i in l: ans=ans+(i[1]*i[0]) #storing as many times frequency of charcters present in s return ans
sort-characters-by-frequency
PYTHON SOLUTION - EXPLAINED LINE BY LINE✔
T1n1_B0x1
0
2
sort characters by frequency
451
0.686
Medium
7,999