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/binary-tree-postorder-traversal/discuss/1979011/Python-solution-40ms
class Solution: def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]: if(root==None): return [] stack=[] stack.append(root) ans=[] while stack: curr=stack.pop() ans.append(curr.val) if(curr.left): stack.append(curr.left) if(curr.right): stack.append(curr.right) return ans[::-1]
binary-tree-postorder-traversal
Python solution 40ms
bad_karma25
2
130
binary tree postorder traversal
145
0.668
Easy
2,100
https://leetcode.com/problems/binary-tree-postorder-traversal/discuss/867376/Iterative-solution-using-1-stack-with-explanation
class Solution: def postorderTraversal(self, root: TreeNode) -> List[int]: ans, s = [], [] curr = root while curr or s: while curr: s.append((curr, curr.right)) curr = curr.left p = s.pop() # right child is none for popped node - it means we have either # explored right subtree or it never existed. In both cases, # we can simply visit popped node i.e. add its val to ans list if not p[1]: ans.append(p[0].val) else: # Add popped node back in stack with its right child as None. # None right child denotes that when we pop this node in future, # we already explored its right subtree as we are going to do # that by setting curr to right child in the next step. s.append((p[0], None)) # Explore right subtree curr = p[1] return ans
binary-tree-postorder-traversal
Iterative solution using 1 stack with explanation
ivmarkp
2
398
binary tree postorder traversal
145
0.668
Easy
2,101
https://leetcode.com/problems/binary-tree-postorder-traversal/discuss/2084279/Python3-DFS-Recursive-Solution
class Solution: def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]: if not root: return [] res=[] def dfs(root): if not root: return dfs(root.left) dfs(root.right) res.append(root.val) dfs(root) return(res)
binary-tree-postorder-traversal
Python3 DFS Recursive Solution
rohith4pr
1
71
binary tree postorder traversal
145
0.668
Easy
2,102
https://leetcode.com/problems/binary-tree-postorder-traversal/discuss/1994763/Python-solution
class Solution: def postorderTraversal(self, root): traversal, stack = [], [root] while stack: node = stack.pop() if node: traversal.append(node.val) stack.append(node.left) stack.append(node.right) return traversal[::-1]
binary-tree-postorder-traversal
Python solution
nomanaasif9
1
87
binary tree postorder traversal
145
0.668
Easy
2,103
https://leetcode.com/problems/binary-tree-postorder-traversal/discuss/1430634/Python3-Pre-Order-Post-Order-Inorder-Solution-through-recursion
class Solution: def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]: res = [] self.dfs(root, res) return res def dfs(self, root, res): if root: self.dfs(root.left, res) self.dfs(root.right, res) res.append(root.val)
binary-tree-postorder-traversal
Python3 Pre Order, Post Order, Inorder Solution through recursion
Sanyamx1x
1
287
binary tree postorder traversal
145
0.668
Easy
2,104
https://leetcode.com/problems/binary-tree-postorder-traversal/discuss/1430634/Python3-Pre-Order-Post-Order-Inorder-Solution-through-recursion
class Solution: def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]: res = [] self.dfs(root, res) return res def dfs(self, root, res): if root: self.dfs(root.left, res) res.append(root.val) self.dfs(root.right, res)
binary-tree-postorder-traversal
Python3 Pre Order, Post Order, Inorder Solution through recursion
Sanyamx1x
1
287
binary tree postorder traversal
145
0.668
Easy
2,105
https://leetcode.com/problems/binary-tree-postorder-traversal/discuss/251415/clean-python-both-recursive-and-iterative-solutions
class Solution(object): def postorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ rst = [] self.helper(root, rst) return rst def helper(self, node, rst): if node: self.helper(node.left, rst) self.helper(node.right, rst) rst.append(node.val)
binary-tree-postorder-traversal
clean python both recursive and iterative solutions
mazheng
1
138
binary tree postorder traversal
145
0.668
Easy
2,106
https://leetcode.com/problems/binary-tree-postorder-traversal/discuss/251415/clean-python-both-recursive-and-iterative-solutions
class Solution(object): def postorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ rst = [] stack = [] while root or stack: if root: rst.insert(0, root.val) stack.append(root) root = root.right else: root = stack.pop().left return rst
binary-tree-postorder-traversal
clean python both recursive and iterative solutions
mazheng
1
138
binary tree postorder traversal
145
0.668
Easy
2,107
https://leetcode.com/problems/binary-tree-postorder-traversal/discuss/2837835/python-beats-97.37
class Solution: def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]: if not root: return [] left = right = [] if root.left: left = self.postorderTraversal(root.left) if root.right: right = self.postorderTraversal(root.right) return *left, *right, root.val
binary-tree-postorder-traversal
[python] - beats 97.37%
ceolantir
0
4
binary tree postorder traversal
145
0.668
Easy
2,108
https://leetcode.com/problems/binary-tree-postorder-traversal/discuss/2828864/python-oror-simple-solution-oror-recursion
class Solution: def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]: # if tree empty if not root: return [] # answer list ans = [] def traverse(node: Optional[TreeNode]) -> None: # if empty node if not node: return # first, check left child traverse(node.left) # second, check right child traverse(node.right) # third, check cur val ans.append(node.val) # fill ans traverse(root) return ans
binary-tree-postorder-traversal
python || simple solution || recursion
wduf
0
2
binary tree postorder traversal
145
0.668
Easy
2,109
https://leetcode.com/problems/binary-tree-postorder-traversal/discuss/2789117/Python-one-liner
class Solution: def postorderTraversal(self, root): return self.postorderTraversal(root.left) + self.postorderTraversal(root.right) + [root.val] if root else []
binary-tree-postorder-traversal
Python one-liner
Pirmil
0
3
binary tree postorder traversal
145
0.668
Easy
2,110
https://leetcode.com/problems/binary-tree-postorder-traversal/discuss/2647141/Python-PostOrder-Recursion
class Solution: def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]: lst = [] return self.helper(root, lst) def helper(self, root, lst): if root: self.helper(root.left, lst) self.helper(root.right, lst) lst.append(root.val) return lst
binary-tree-postorder-traversal
Python PostOrder Recursion
axce1
0
31
binary tree postorder traversal
145
0.668
Easy
2,111
https://leetcode.com/problems/binary-tree-postorder-traversal/discuss/2646457/Ans-to-follow-up%3A-Iterative-straight-forward-Python-solution-same-logic-as-recursion
class Solution: def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]: if not root: return [] stack = [root] result = [] while stack: node = stack.pop() if node.left: stack.append(node.left) if node.right: stack.append(node.right) result.append(node.val) # Importat to Reverse the result return result[::-1]
binary-tree-postorder-traversal
Ans to follow-up: Iterative straight-forward Python solution, same logic as recursion 🫣
saadbash
0
3
binary tree postorder traversal
145
0.668
Easy
2,112
https://leetcode.com/problems/binary-tree-postorder-traversal/discuss/2502131/python3-recursive-with-comments
class Solution: ''' Postorder traversal is left to right, bottom to top, visiting root last 1. recursively traverse left subtree 2. recursively traverse right subtree 3. visit root node ''' def recursivetraverse(self, root, output): if root: self.recursivetraverse(root.left, output) self.recursivetraverse(root.right, output) output.append(root.val) return output def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]: return self.recursivetraverse(root, output = [])
binary-tree-postorder-traversal
python3 recursive with comments
shwetachandole
0
14
binary tree postorder traversal
145
0.668
Easy
2,113
https://leetcode.com/problems/binary-tree-postorder-traversal/discuss/2502128/Python3-iterativerecursive-with-comment
class Solution: # Postorder traversal is left to right, bottom to top, visiting root last def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]: self.output = [] def check_node(node): if node.left: check_node(node.left) if node.right: check_node(node.right) self.output.append(node.val) if root: check_node(root) return self.output
binary-tree-postorder-traversal
Python3 iterative/recursive with comment
shwetachandole
0
34
binary tree postorder traversal
145
0.668
Easy
2,114
https://leetcode.com/problems/binary-tree-postorder-traversal/discuss/2352724/Python-simple-iterative-with-explanation
class Solution: def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]: # Init store ans = deque() # Init stack stack = [root] # Iterate through stack while stack: node = stack.pop() # Base case if not node: continue else: print(node.val) # Log value ans.appendleft(node.val) # Add right and left nodes to the stack stack.append(node.left) stack.append(node.right) return ans
binary-tree-postorder-traversal
Python simple iterative with explanation
drblessing
0
66
binary tree postorder traversal
145
0.668
Easy
2,115
https://leetcode.com/problems/binary-tree-postorder-traversal/discuss/2314230/Python-Time%3A-69-ms-oror-Mem%3A-13.8MB-oror-Recursive-Easy-Understand
class Solution: def __init__(self): self.mylist: List[int] = [] def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]: if root: self.postorderTraversal(root.left) self.postorderTraversal(root.right) self.mylist.append(root.val) return self.mylist
binary-tree-postorder-traversal
[Python] Time: 69 ms || Mem: 13.8MB || Recursive Easy Understand
Buntynara
0
37
binary tree postorder traversal
145
0.668
Easy
2,116
https://leetcode.com/problems/binary-tree-postorder-traversal/discuss/2294305/python3-oror-easy-oror-2-stack-iterative-approach
class Solution: def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]: if root is None: return root stack=[root] stack2=[] ans=[] while stack!=[]: node=stack.pop() stack2.append(node.val) if node.left is not None: stack.append(node.left) if node.right is not None: stack.append(node.right) while stack2!=[]: ans.append(stack2.pop()) return ans
binary-tree-postorder-traversal
python3 || easy || 2 stack iterative approach
_soninirav
0
85
binary tree postorder traversal
145
0.668
Easy
2,117
https://leetcode.com/problems/binary-tree-postorder-traversal/discuss/1930210/Python-Functional-or-Stack-or-Morris-Traversal-Multiple-Solutions!
class Solution: def postorderTraversal(self, root): self.res = [] self.helper(root) return self.res def helper(self, root): if root: self.helper(root.left) self.helper(root.right) self.res.append(root.val)
binary-tree-postorder-traversal
Python - Functional | Stack | Morris Traversal - Multiple Solutions!
domthedeveloper
0
96
binary tree postorder traversal
145
0.668
Easy
2,118
https://leetcode.com/problems/binary-tree-postorder-traversal/discuss/1930210/Python-Functional-or-Stack-or-Morris-Traversal-Multiple-Solutions!
class Solution: def postorderTraversal(self, root): return self.postorderTraversal(root.left) + self.postorderTraversal(root.right) + [root.val] if root else []
binary-tree-postorder-traversal
Python - Functional | Stack | Morris Traversal - Multiple Solutions!
domthedeveloper
0
96
binary tree postorder traversal
145
0.668
Easy
2,119
https://leetcode.com/problems/binary-tree-postorder-traversal/discuss/1930210/Python-Functional-or-Stack-or-Morris-Traversal-Multiple-Solutions!
class Solution: def postorderTraversal(self, root): return [*self.postorderTraversal(root.left), *self.postorderTraversal(root.right), root.val] if root else []
binary-tree-postorder-traversal
Python - Functional | Stack | Morris Traversal - Multiple Solutions!
domthedeveloper
0
96
binary tree postorder traversal
145
0.668
Easy
2,120
https://leetcode.com/problems/binary-tree-postorder-traversal/discuss/1930210/Python-Functional-or-Stack-or-Morris-Traversal-Multiple-Solutions!
class Solution: def postorderTraversal(self, root): res, stack = deque(), [root] while stack: node = stack.pop() if node: res.appendleft(node.val) stack.append(node.left) stack.append(node.right) return res
binary-tree-postorder-traversal
Python - Functional | Stack | Morris Traversal - Multiple Solutions!
domthedeveloper
0
96
binary tree postorder traversal
145
0.668
Easy
2,121
https://leetcode.com/problems/binary-tree-postorder-traversal/discuss/1930210/Python-Functional-or-Stack-or-Morris-Traversal-Multiple-Solutions!
class Solution: def postorderTraversal(self, root): res = deque() while root: if root.right: temp = root.right while temp.left and temp.left != root: temp = temp.left if not temp.left: res.appendleft(root.val) temp.left = root root = root.right else: temp.left = None root = root.left else: res.appendleft(root.val) root = root.left return res
binary-tree-postorder-traversal
Python - Functional | Stack | Morris Traversal - Multiple Solutions!
domthedeveloper
0
96
binary tree postorder traversal
145
0.668
Easy
2,122
https://leetcode.com/problems/binary-tree-postorder-traversal/discuss/1856712/Iterative-Simple-Solution-using-stack-and-deque-in-Python
class Solution: def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]: stack = [] result = deque() if root: stack.append(root) while len(stack): node = stack.pop() result.appendleft(node.val) if node.left: stack.append(node.left) if node.right: stack.append(node.right) return list(result)
binary-tree-postorder-traversal
Iterative Simple Solution using stack and deque in Python
anmolg
0
49
binary tree postorder traversal
145
0.668
Easy
2,123
https://leetcode.com/problems/binary-tree-postorder-traversal/discuss/1803481/Python-Simple-Python-Solution-Using-Recursion
class Solution: def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]: self.result = [] def PostOrder(node): if node == None: return None PostOrder(node.left) PostOrder(node.right) self.result.append(node.val) PostOrder(root) return self.result
binary-tree-postorder-traversal
[ Python ] βœ”βœ” Simple Python Solution Using Recursion πŸ”₯✌
ASHOK_KUMAR_MEGHVANSHI
0
74
binary tree postorder traversal
145
0.668
Easy
2,124
https://leetcode.com/problems/binary-tree-postorder-traversal/discuss/1790591/Faster-then-64-of-speed
class Solution: def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]: result = [] def dfs(root,result): if root != None: dfs(root.left,result) dfs(root.right,result) result.append(root.val) return result return dfs(root,result)
binary-tree-postorder-traversal
Faster then 64% of speed
xevb
0
19
binary tree postorder traversal
145
0.668
Easy
2,125
https://leetcode.com/problems/binary-tree-postorder-traversal/discuss/1743949/textbook-solution-actually-the-definition-why-it-is-post-order
class Solution: def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]: res = [] def helper(root, res): if not root: return helper(root.left, res) helper(root.right, res) res.append(root.val) helper(root, res) return res
binary-tree-postorder-traversal
textbook solution, actually the definition why it is post-order
752937603
0
49
binary tree postorder traversal
145
0.668
Easy
2,126
https://leetcode.com/problems/binary-tree-postorder-traversal/discuss/1508475/Python3-simple-recursive-approach
class Solution: def __init__(self): self.ans = [] def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]: if not root: return if root.left: self.postorderTraversal(root.left) if root.right: self.postorderTraversal(root.right) self.ans.append(root.val) return self.ans
binary-tree-postorder-traversal
Python3 simple recursive approach
EklavyaJoshi
0
42
binary tree postorder traversal
145
0.668
Easy
2,127
https://leetcode.com/problems/binary-tree-postorder-traversal/discuss/1398447/Java-%2B-Python3
class Solution: def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]: res = [] if not root: return res def dfs(node): if not node: return dfs(node.left) dfs(node.right) res.append(node.val) pass dfs(root) return res
binary-tree-postorder-traversal
Java + Python3
jlee9077
0
72
binary tree postorder traversal
145
0.668
Easy
2,128
https://leetcode.com/problems/lru-cache/discuss/442751/Python3-hashmap-and-doubly-linked-list
class ListNode: def __init__(self, key=0, val=0, prev=None, next=None): self.key = key self.val = val self.prev = prev self.next = next class LRUCache: def __init__(self, capacity: int): """Initialize hash table & dll""" self.cpty = capacity self.htab = dict() #hash table self.head = ListNode() #doubly linked list self.tail = ListNode() self.head.next = self.tail self.tail.prev = self.head def _del(self, key: int) -> int: """Delete given key from hash table & dll""" node = self.htab.pop(key) node.prev.next = node.next node.next.prev = node.prev return node.val def _ins(self, key: int, value: int) -> None: """Insert at tail""" node = ListNode(key, value, self.tail.prev, self.tail) self.tail.prev.next = self.tail.prev = node self.htab[key] = node def get(self, key: int) -> int: if key not in self.htab: return -1 value = self._del(key) self._ins(key, value) return value def put(self, key: int, value: int) -> None: if key in self.htab: self._del(key) self._ins(key, value) if len(self.htab) > self.cpty: self._del(self.head.next.key) # Your LRUCache object will be instantiated and called as such: # obj = LRUCache(capacity) # param_1 = obj.get(key) # obj.put(key,value)
lru-cache
[Python3] hashmap & doubly-linked list
ye15
8
457
lru cache
146
0.405
Medium
2,129
https://leetcode.com/problems/lru-cache/discuss/442751/Python3-hashmap-and-doubly-linked-list
class LRUCache: def __init__(self, capacity: int): self.cpty = capacity self.data = dict() def get(self, key: int) -> int: if key not in self.data: return -1 value = self.data.pop(key) self.data[key] = value return value def put(self, key: int, value: int) -> None: if key in self.data: self.data.pop(key) self.data[key] = value if len(self.data) > self.cpty: self.data.pop(next(iter(self.data.keys())))
lru-cache
[Python3] hashmap & doubly-linked list
ye15
8
457
lru cache
146
0.405
Medium
2,130
https://leetcode.com/problems/lru-cache/discuss/442751/Python3-hashmap-and-doubly-linked-list
class LRUCache: def __init__(self, capacity: int): self.cpty = capacity self.data = OrderedDict() def get(self, key: int) -> int: if key not in self.data: return -1 self.data.move_to_end(key) return self.data[key] def put(self, key: int, value: int) -> None: if key in self.data: self.data.pop(key) self.data[key] = value if len(self.data) > self.cpty: self.data.popitem(last=False)
lru-cache
[Python3] hashmap & doubly-linked list
ye15
8
457
lru cache
146
0.405
Medium
2,131
https://leetcode.com/problems/lru-cache/discuss/1677936/Python-Dict-Only
class LRUCache: def __init__(self, capacity: int): self.cache = {} self.capacity = capacity self.items = 0 def get(self, key: int) -> int: if key in self.cache: val = self.cache[key] # get value of key and delete the key - value del self.cache[key] self.cache[key] = val # Puts the key - value to end of cache return self.cache[key] return -1 def put(self, key: int, value: int) -> None: if key in self.cache: del self.cache[key] # delete key self.cache[key] = value #place the key - value pair in the end of cache elif self.items == self.capacity: del self.cache[next(iter(self.cache))] #delete the first key - value pair which is the LRU self.cache[key] = value else: self.cache[key] = value self.items += 1
lru-cache
Python Dict Only
Kenchir
7
338
lru cache
146
0.405
Medium
2,132
https://leetcode.com/problems/lru-cache/discuss/1374660/Python-Guys-NextIter
class LRUCache: def __init__(self, capacity: int): self.return1={} self.capacity=capacity def get(self, key: int) -> int: if key in self.return1: get = self.return1[key] del self.return1[key] self.return1[key]=get return get return -1 def put(self, key: int, value: int) -> None: if key in self.return1: del self.return1[key] self.return1[key]=value else: if len(self.return1)<self.capacity: self.return1[key]=value else: del self.return1[next(iter(self.return1))] ###This Guy Here is super important, Learn what this is in python self.return1[key]=value # Your LRUCache object will be instantiated and called as such: # obj = LRUCache(capacity) # param_1 = obj.get(key) # obj.put(key,value)
lru-cache
Python Guys #NextIter
peanuts092
6
697
lru cache
146
0.405
Medium
2,133
https://leetcode.com/problems/lru-cache/discuss/1655397/Python3-Dictionary-%2B-LinkedList-or-Clean-%2B-Detailed-Explanation-or-O(1)-Time-For-All-Operations
class Node: def __init__(self, key=-1, val=-1, nxt=None, prv=None): self.key, self.val, self.next, self.prev = key, val, nxt, prv class LinkedList: def __init__(self): # Head is the Most Recently Used -- Tail is the Least Recently Used self.head = self.tail = None def appendleft(self, node): # Makes node the new head (appends left) if self.head: node.next, self.head.prev, self.head = self.head, node, node else: self.head = self.tail = node def remove(self, node): # Removes node from linkedlist (if statements are necessary to take care of edge cases) if node == self.head == self.tail: self.head = self.tail = None elif node == self.head: self.popleft() elif node == self.tail: self.pop() else: node.prev.next, node.next.prev = node.next, node.prev def pop(self): # Removing tail and reassigning tail to the previous node, then we return the old tail oldTail, self.tail, self.tail.next = self.tail, self.tail.prev, None return oldTail def popleft(self): # Removing head and reassigning head to the next node self.head, self.head.prev = self.head.next, None class LRUCache: def __init__(self, capacity: int): # Linkedlist will hold nodes in the following order: Most recent -> ... -> Least recent self.cap, self.elems, self.l = capacity, {}, LinkedList() def get(self, key: int) -> int: if key in self.elems: # Before returning the value, we update position of the element in the linkedlist self.l.remove(self.elems[key]) self.l.appendleft(self.elems[key]) return self.elems[key].val return -1 def put(self, key: int, value: int) -> None: # Remove from linked list if node exists, because we will later appendleft the NEW node if key in self.elems: self.l.remove(self.elems[key]) # Create new node, then add and appenleft self.elems[key] = Node(key, value) self.l.appendleft(self.elems[key]) # Check if we have more elements than capacity, delete LRU from linked list and dictionary if len(self.elems) > self.cap: del self.elems[self.l.pop().key]
lru-cache
[Python3] Dictionary + LinkedList | Clean + Detailed Explanation | O(1) Time For All Operations
PatrickOweijane
5
539
lru cache
146
0.405
Medium
2,134
https://leetcode.com/problems/lru-cache/discuss/2090397/Brute-Force-greater-Optimized-Approach-O(1)-Time-Solution-Easy-To-Understand
class LRUCache: def __init__(self, capacity): self.capacity = capacity self.dic = {} self.arr = [] def get(self, key): if key in self.arr: i = self.arr.index(key) res = self.arr[i] self.arr.pop(i) self.arr.append(res) return self.dic[res] else: return - 1 def put(self, key, value): if key in self.arr: i = self.arr.index(key) self.arr.pop(i) self.arr.append(key) self.dic[key] = value else: if len(self.arr) >= self.capacity: self.arr.pop(0) self.arr.append(key) self.dic[key] = value # Time Complexity: O(N) ; as O(N) for searching in array and O(N) for rearranging the indexing after popping. so time = O(N) + O(N) = O(N) # Space Complexity: O(N) ; for making the array and dictionary to store key and value
lru-cache
Brute Force => Optimized Approach O(1) Time Solution Easy To Understand✨
samirpaul1
3
291
lru cache
146
0.405
Medium
2,135
https://leetcode.com/problems/lru-cache/discuss/2090397/Brute-Force-greater-Optimized-Approach-O(1)-Time-Solution-Easy-To-Understand
class LRUCache: def __init__(self, capacity): self.dic = collections.OrderedDict() self.capacity = capacity self.cacheLen = 0 def get(self, key): if key in self.dic: ans = self.dic.pop(key) self.dic[key] = ans # set this this key as new one (most recently used) return ans else: return -1 def put(self, key, value): if key in self.dic: ans = self.dic.pop(key) self.dic[key] = ans else: if self.cacheLen >= self.capacity: # self.dic is full self.dic.popitem(last = False) # pop the last recently used element (lru) self.cacheLen -= 1 self.dic[key] = value self.cacheLen += 1 # Time Complexity = O(1) ; as search and pop operation from dictionary is of O(1) # Space Complexity = O(N) ; for making the dictionary
lru-cache
Brute Force => Optimized Approach O(1) Time Solution Easy To Understand✨
samirpaul1
3
291
lru cache
146
0.405
Medium
2,136
https://leetcode.com/problems/lru-cache/discuss/2090397/Brute-Force-greater-Optimized-Approach-O(1)-Time-Solution-Easy-To-Understand
class Node(object): def __init__(self, key, x): self.key = key self.value = x self.next = None self.prev = None class LRUCache(object): def __init__(self, capacity): """ :type capacity: int """ self.capacity = capacity self.dic = {} self.head = None self.tail = None def get(self, key): """ :type key: int :rtype: int """ if key in self.dic: node = self.dic[key] self.makeMostRecent(node) return node.value else: return -1 def put(self, key, value): """ :type key: int :type value: int :rtype: None """ if key not in self.dic: # Invalidate oldest if required: if len(self.dic) == self.capacity: del self.dic[self.head.key] self.removeHead() node = Node(key, value) self.dic[key] = node else: # Update the value: node = self.dic[key] node.value = value self.makeMostRecent(node) def makeMostRecent(self, node): if self.head and self.head.key == node.key: self.removeHead() # Make this item the most recently accessed (tail): if self.tail and not self.tail.key == node.key: if node.prev: node.prev.next = node.next if node.next: node.next.prev = node.prev node.next = None self.tail.next = node # Old tail's next is the node. node.prev = self.tail # Node's previous is the old tail. self.tail = node # New tail is the node. if not self.head: self.head = node # If this is the first item make it the head as well as tail. def removeHead(self): self.head = self.head.next if self.head: self.head.prev = None # Time Complexity = O(1) ; as search and pop operation from dictionary is of O(1) and deleting and adding links in double linkedlist also takes O(1) time. # Space Complexity = O(N) ; for making the dictionary and double linkedlist
lru-cache
Brute Force => Optimized Approach O(1) Time Solution Easy To Understand✨
samirpaul1
3
291
lru cache
146
0.405
Medium
2,137
https://leetcode.com/problems/lru-cache/discuss/2075556/Python3-oror-faster-86.25-oror-memory-83.75
class LRUCache: def __init__(self, capacity: int): self.capacity = capacity self.items = dict() def get(self, key: int) -> int: result = self.items.pop(key, -1) if result == -1: return -1 else: self.items[key] = result return result def put(self, key: int, value: int) -> None: result = self.items.pop(key, -1) if result == -1 and len(self.items) == self.capacity: del self.items[next(iter(self.items))] self.items[key] = value
lru-cache
Python3 || faster 86.25% || memory 83.75%
grivabo
3
171
lru cache
146
0.405
Medium
2,138
https://leetcode.com/problems/lru-cache/discuss/2656078/Python3-Dict-solution-or-No-Doubly-linked-List-or-No-OrderedDict
class LRUCache: def __init__(self, capacity): self.dic = {} self.remain = capacity def get(self, key): if key not in self.dic: return -1 v = self.dic.pop(key) self.dic[key] = v # set key as the newest one return v def put(self, key, value): if key in self.dic: self.dic.pop(key) else: if self.remain > 0: self.remain -= 1 else: # self.dic is full left_key = next(iter(self.dic)) self.dic.pop(left_key) self.dic[key] = value
lru-cache
Python3 Dict solution | No Doubly linked List | No OrderedDict
ivan_shelonik
2
164
lru cache
146
0.405
Medium
2,139
https://leetcode.com/problems/lru-cache/discuss/1970603/python-3-oror-ordered-map
class LRUCache: def __init__(self, capacity: int): self.capacity = capacity self.cache = collections.OrderedDict() def get(self, key: int) -> int: if key in self.cache: self.cache.move_to_end(key) return self.cache[key] return -1 def put(self, key: int, value: int) -> None: if key in self.cache: self.cache.move_to_end(key) elif len(self.cache) == self.capacity: self.cache.popitem(last=False) self.cache[key] = value
lru-cache
python 3 || ordered map
dereky4
2
236
lru cache
146
0.405
Medium
2,140
https://leetcode.com/problems/lru-cache/discuss/1950628/OrderedDict-simple
class LRUCache: def __init__(self, capacity: int): self._ordered_dict = collections.OrderedDict() self._capacity = capacity def get(self, key: int) -> int: if key in self._ordered_dict: self._ordered_dict[key] = self._ordered_dict.pop(key) return self._ordered_dict[key] else: return -1 def put(self, key: int, value: int) -> None: if key in self._ordered_dict: _ = self.get(key) # put the key on top elif len(self._ordered_dict) == self._capacity: self._ordered_dict.popitem(last=False) # evict LRU element self._ordered_dict[key] = value
lru-cache
OrderedDict simple
ismaj
2
98
lru cache
146
0.405
Medium
2,141
https://leetcode.com/problems/lru-cache/discuss/2676308/Python-or-DLL-or-Hashmap-or-Beats-95-Memory
class Node: def __init__(self, key, value): self.key = key self.value = value self.next = None self.prev = None class LRUCache: def __init__(self, capacity: int): self.head = None self.tail = None self.hash_map = {} self.capacity = capacity def prepend(self, new_node: Node): if self.head: self.head.prev = new_node new_node.next = self.head if not self.tail: self.tail = new_node self.head = new_node def unlink_node(self, node: Node) -> None: # Unlink the node from cache if not node: return None prev_node = node.prev next_node = node.next if prev_node: prev_node.next = next_node if next_node: next_node.prev = prev_node if self.head == node: self.head = next_node if self.tail == node: self.tail = prev_node node.prev = None node.next = None def delete_node(self, node: Node): self.unlink_node(node) del self.hash_map[node.key] del node def evict_lru_node(self) -> Node or None: if not self.tail: return None lru_node = self.tail self.delete_node(lru_node) def get(self, key: int) -> int: if key not in self.hash_map: return -1 node = self.hash_map[key] if self.head != node: self.unlink_node(node) self.prepend(node) return node.value def put(self, key: int, value: int) -> None: new_node = Node(key, value) if key in self.hash_map: self.delete_node(self.hash_map[key]) if len(self.hash_map) >= self.capacity: self.evict_lru_node() self.prepend(new_node) self.hash_map[key] = new_node # Your LRUCache object will be instantiated and called as such: # obj = LRUCache(capacity) # param_1 = obj.get(key) # obj.put(key,value)
lru-cache
Python | DLL | Hashmap | Beats 95% Memory
gurubalanh
1
33
lru cache
146
0.405
Medium
2,142
https://leetcode.com/problems/lru-cache/discuss/2654152/Python-using-default-dict()
class LRUCache: def __init__(self, capacity: int): self.capacity = capacity self.cache = dict() # using default dict in Python def get(self, key: int) -> int: if key not in self.cache.keys(): return -1 data = self.cache.pop(key) self.cache[key] = data return data def put(self, key: int, value: int) -> None: if key in self.cache.keys(): self.cache.pop(key) self.cache[key] = value if self.capacity < len(self.cache): # Pop first index key in dict() # I know dict() does not have index inside it # i mean ... # example: {'1': 1, '2': 2, '3': 3} -> '1' key = next(iter(self.cache)) self.cache.pop(key)
lru-cache
Pythonη­”γˆγ€€using default dict()
namashin
1
106
lru cache
146
0.405
Medium
2,143
https://leetcode.com/problems/lru-cache/discuss/2115259/Python-oror-Easy-Double-Linked-List-solution
class Node: def __init__(self, key, val): self.key, self.val = key, val self.prev = self.next = None class LRUCache: def __init__(self, capacity: int): self.cap = capacity self.cache = {} # left helps to find LRU and right helps to find MRU self.left, self.right = Node(0, 0), Node(0, 0) self.left.next, self.right.prev = self.right, self.left # remove any node from any place def remove(self, node): prev, nxt = node.prev, node.next prev.next, nxt.prev = nxt, prev # insert into right most node def insert(self, node): prev = self.right.prev self.right.prev = prev.next = node node.next, node.prev = self.right, prev def get(self, key: int) -> int: if key in self.cache: self.remove(self.cache[key]) self.insert(self.cache[key]) return self.cache[key].val return -1 def put(self, key: int, value: int) -> None: if key in self.cache: self.remove(self.cache[key]) self.cache[key] = Node(key, value) self.insert(self.cache[key]) if len(self.cache) > self.cap: lru_node = self.left.next self.remove(lru_node) del self.cache[lru_node.key]
lru-cache
Python || Easy Double Linked List solution
sagarhasan273
1
125
lru cache
146
0.405
Medium
2,144
https://leetcode.com/problems/lru-cache/discuss/1959893/Easy-to-Understand-Python-code-that-beats-90-solutions.
class LRUCache: def __init__(self, capacity: int): self.capacity = capacity self.dic = dict() self.head = Node(0, 0) self.tail = Node(0, 0) self.head.next = self.tail self.tail.prev = self.head def get(self, key: int) -> int: if key in self.dic: n = self.dic[key] self.remove(n) self.add(n) return n.val return -1 def put(self, key: int, value: int) -> None: if key in self.dic: self.remove(self.dic[key]) n = Node(key, value) self.add(n) self.dic[key] = n if len(self.dic) > self.capacity: n = self.head.next self.remove(n) del self.dic[n.key] def remove(self,node): p = node.prev n = node.next p.next = n n.prev = p def add(self,node): p = self.tail.prev p.next = node self.tail.prev = node node.prev = p node.next = self.tail class Node: def __init__(self, k, v): self.key = k self.val = v self.prev = None self.next = None
lru-cache
Easy to Understand Python code that beats 90% solutions.
tkdhimanshusingh
1
194
lru cache
146
0.405
Medium
2,145
https://leetcode.com/problems/lru-cache/discuss/1766553/Simple-Python3-solution-using-dict-beats-89
class LRUCache: """ 1. Python's dictionaries support insertion order by default. 2. You can grab access to the first key in a dictionary using either next(iter(dict)) or list(dict[0]) """ def __init__(self, capacity: int): self.cache = dict() self.capacity = capacity def get(self, key: int) -> int: if key not in self.cache: return -1 else: value = self.cache[key] self.cache.pop(key) self.cache[key] = value return value def put(self, key: int, value: int) -> None: if key in self.cache: self.cache.pop(key) else: if len(self.cache) >= self.capacity: self.cache.pop(next(iter(self.cache))) self.cache[key] = value
lru-cache
Simple Python3 solution using dict beats 89%
kunalnarang
1
237
lru cache
146
0.405
Medium
2,146
https://leetcode.com/problems/lru-cache/discuss/1707041/Python-Solution
class Node: def __init__(s, key, value): s.key = key s.value = value s.next = None s.prev = None class LRUCache: def __init__(self, capacity: int): self.mru = Node(-1, -1) self.lru = Node(-1, -1) self.mru.next = self.lru self.lru.prev = self.mru self.hash = {} self.size = capacity def get(self, key: int) -> int: if key not in self.hash: return -1 node = self.hash[key] self.delete(node) self.insert(node) return node.value def put(self, key: int, value: int) -> None: if key in self.hash: node = self.hash[key] self.delete(node) if self.size == len(self.hash): self.delete(self.lru.prev) self.insert(Node(key, value)) def insert(self, node): self.mru.next.prev = node node.next = self.mru.next self.mru.next = node node.prev = self.mru self.hash[node.key] = node def delete(self, node): self.hash.pop(node.key) node.next.prev = node.prev node.prev.next = node.next
lru-cache
Python Solution
ayush_kushwaha
1
191
lru cache
146
0.405
Medium
2,147
https://leetcode.com/problems/lru-cache/discuss/554251/Python3-O(1)-solution-using-doubly-linked-list
class LRUCache: class Node: ''' A class that represents a cache-access node in the doubly-linked list ''' def __init__(self, key, value, prev_n = None, next_n = None): self.key = key self.value = value self.prev_n = prev_n self.next_n = next_n def __init__(self, capacity): self.capacity = capacity self.cache = {} self.lru_head = None # cache-access list head self.lru_tail = None # cache-access list tail def _add_node(self, key, value): ''' Add cache-access node to the tail of the list. Basic doubly-linked wizardy ''' node = LRUCache.Node(key, value, self.lru_tail) if self.lru_tail: self.lru_tail.next_n = node self.lru_tail = node if not self.lru_head: self.lru_head = node return node def _remove_node(self, node): ''' Remove specified cache-access node from the list. Basic doubly-linked wizardy ''' if node.prev_n: node.prev_n.next_n = node.next_n if node.next_n: node.next_n.prev_n = node.prev_n if self.lru_head == node: self.lru_head = node.next_n if self.lru_tail == node: self.lru_tail = node.prev_n def get(self, key): if key in self.cache: node = self.cache[key] self._remove_node(node) # remove existing cache-access entry # add new node representing 'get' cache-access new_node = self._add_node(key, node.value) self.cache[key] = new_node return node.value else: return -1 def put(self, key, value): if key in self.cache: # remove existing cache-access entry self._remove_node(self.cache[key]) # add new node representing 'update' or 'insert' cache-access node = self._add_node(key, value) self.cache[key] = node if len(self.cache) > self.capacity: # capacity exceeded, time to pop the latest item from the front del self.cache[self.lru_head.key] self._remove_node(self.lru_head)
lru-cache
Python3 O(1) solution using doubly-linked list
coolhazcker
1
220
lru cache
146
0.405
Medium
2,148
https://leetcode.com/problems/lru-cache/discuss/517055/Clear-Logic-Details-Explained-Python-beats-93
class Node: def __init__(self, key, val): self.val = val self.key = key self.prev = None self.nxt_ = None # use a DL class DLinked: def __init__(self): self.head = None self.tail = None def remove(self, node): """ return the deleted node key """ # 3 basic postion cases prev = node.prev nxt_ = node.nxt_ # if the removing node is the single node in the list if prev is None and nxt_ is None: # eariler termination self.head = None self.tail = None return node.key # head node and not single, happy 2.14's day ! if prev is None: self.head = nxt_ nxt_.prev = None # tail node not single elif nxt_ is None: self.tail = prev prev.nxt_ = None else: # mid node prev.nxt_ = nxt_ nxt_.prev = prev # either way you should return the old key return node.key def add(self, node): """ return the node ref if added """ # when head is None if self.head is None: self.head = node if self.tail is None: self.tail = node else: node.nxt_ = self.head node.prev = None self.head.prev = node self.head = node return self.head class LRUCache: def __init__(self, capacity): self.cap = capacity self.table = {} self.dlinked = DLinked() def get(self, key): # also check key first node = self.table.get(key, None) if node is not None: # update hit self.dlinked.remove(node) self.dlinked.add(node) return node.val else: return -1 def put(self, key, val): # let Dlinked class to handle add / remove # let cache class to handle capacity cases # use forward logic to make thing clear # no need to check cap first, instead, we need to check key in table or not. # becase if key exist, there is nothing to deal with the capacity node = self.table.get(key, None) if node is not None: # update key hit self.dlinked.remove(node) node.val = val # same key overwrite self.dlinked.add(node) # return as soon as possible to prevent logic twists return # if key not in table, then we need to add key, hence we need to check capacity if len(self.table) == self.cap: # cache full, kill the tail and add to head # seperating the operations by returning the old key old_key = self.dlinked.remove(self.dlinked.tail) del self.table[old_key] node = self.dlinked.add(Node(key, val)) self.table[key] = node else: # cache not full, add directly node = self.dlinked.add(Node(key, val)) self.table[key] = node return
lru-cache
Clear Logic, Details Explained, Python beats 93%
xia50
1
144
lru cache
146
0.405
Medium
2,149
https://leetcode.com/problems/lru-cache/discuss/469599/Python3-O(n)-time-complexity-using-a-list()-and-a-hash-table
class LRUCache: def __init__(self, capacity: int): self.capacity=capacity self.frequency = [] self.cache = {} def get(self, key: int) -> int: if key not in self.frequency: return -1 index = self.frequency.index(key) del self.frequency[index] self.frequency.append(key) return self.cache[key] def put(self, key: int, value: int) -> None: if key in self.frequency: index = self.frequency.index(key) del self.frequency[index] elif len(self.frequency) == self.capacity: self.frequency.pop(0) self.frequency.append(key) self.cache[key] = value # Your LRUCache object will be instantiated and called as such: # obj = LRUCache(capacity) # param_1 = obj.get(key) # obj.put(key,value)
lru-cache
Python3 O(n) time complexity using a list() and a hash table
jb07
1
269
lru cache
146
0.405
Medium
2,150
https://leetcode.com/problems/lru-cache/discuss/2845990/Using-Pythons-ordered-dict-property
class LRUCache: def __init__(self, capacity: int): self.orderedDict = {} self.cap = capacity def updateToTop(self, key): v = self.orderedDict[key] del self.orderedDict[key] self.orderedDict[key] = v def get(self, key: int) -> int: if key in self.orderedDict: self.updateToTop(key) return self.orderedDict[key] else: return -1 def put(self, key: int, value: int) -> None: if key in self.orderedDict: self.updateToTop(key) self.orderedDict[key] = value if len(self.orderedDict) > self.cap: del self.orderedDict[next(iter(self.orderedDict))] # Your LRUCache object will be instantiated and called as such: # obj = LRUCache(capacity) # param_1 = obj.get(key) # obj.put(key,value)
lru-cache
Using Pythons ordered dict property
Jacomatt
0
4
lru cache
146
0.405
Medium
2,151
https://leetcode.com/problems/lru-cache/discuss/2839753/Python-solution-with-no-Ordered-Dict-nor-linked-list
class LRUCache: def __init__(self, capacity: int): self.capacity = capacity self.cache = {} def get(self, key: int) -> int: if key in self.cache: v = self.cache.pop(key) self.cache[key] = v return v else: return -1 def put(self, key: int, value: int) -> None: if key in self.cache: self.cache.pop(key) else: if len(self.cache) == self.capacity: # get the first key in thie cache dict and pop. k = next(iter(self.cache)) self.cache.pop(k) self.cache[key] = value # Your LRUCache object will be instantiated and called as such: # obj = LRUCache(capacity) # param_1 = obj.get(key) # obj.put(key,value)
lru-cache
Python solution with no Ordered Dict nor linked list
woaying
0
2
lru cache
146
0.405
Medium
2,152
https://leetcode.com/problems/lru-cache/discuss/2838553/Hashmap-%2B-Doubly-LinkedList
class Node: def __init__(self, key: Optional[int] = None, value: Optional[int] = None) -> None: self.key = key self.val = value self.next = None self.prev = None class DoublyLinkedList: def __init__(self) -> None: self.head = Node() # dummy head. The real head actually starts from head.next self.tail = Node() # dummy tail. The real tail actually starts from tail.prev self.head.next = self.tail self.tail.prev = self.head def add_to_head(self, node: Node) -> None: """Moves a node to the head.""" tmp = self.head.next self.head.next = node node.prev = self.head node.next = tmp tmp.prev = node def remove_node(self, node: Node) -> None: """Removes a node from the list.""" prev = node.prev next = node.next prev.next = next next.prev = prev node.prev = None node.next = None def move_to_head(self, node: Node) -> None: """Moves a node to the head.""" self.remove_node(node) self.add_to_head(node) def remove_tail(self) -> int: """Removes tail and returns the key.""" node = self.tail.prev self.remove_node(node) return node.key class LRUCache: def __init__(self, capacity: int): self.hashmap: Dict[int, Node] = {} # stores the key-node pair self.capacity = capacity self.ddl = DoublyLinkedList() def get(self, key: int) -> int: if key in self.hashmap: node = self.hashmap[key] self.ddl.move_to_head(node) return node.val else: return -1 def put(self, key: int, value: int) -> None: if key in self.hashmap: node = self.hashmap[key] node.val = value self.ddl.move_to_head(node) else: if len(self.hashmap) == self.capacity: tail_key = self.ddl.remove_tail() del self.hashmap[tail_key] node = Node(key=key, value=value) self.ddl.add_to_head(node) self.hashmap[key] = node # Your LRUCache object will be instantiated and called as such: # obj = LRUCache(capacity) # param_1 = obj.get(key) # obj.put(key,value)
lru-cache
Hashmap + Doubly LinkedList
fengdi2020
0
5
lru cache
146
0.405
Medium
2,153
https://leetcode.com/problems/lru-cache/discuss/2836402/PYTHON3-EASY-EXPLANATION-ONLY-1-DICTor-99.71
class LRUCache: def __init__(self, capacity: int): self.cap, self.cache = capacity, {} def get(self, key: int) -> int: if key in self.cache: temp = self.cache[key] del self.cache[key] self.cache[key] = temp return self.cache[key] return -1 def put(self, key: int, value: int) -> None: # IF key is in cache delete it and re-enter making it the most recently used. if key in self.cache: del self.cache[key] self.cache[key] = value else: #If we have more capacity keep appendings keys : values. if len(self.cache) < self.cap: self.cache[key] = value else: # If we go over the capacity . Delete the FIRST KEY and append the new key. # Here we loop through the keys and we immediately stop after we remove the first key. for k in self.cache: del self.cache[k] break self.cache[key] = value # Your LRUCache object will be instantiated and called as such: # obj = LRUCache(capacity) # param_1 = obj.get(key) # obj.put(key,value)
lru-cache
[PYTHON3] EASY EXPLANATION πŸ”₯ ONLY 1 DICT| 99.71%
papaggalos
0
3
lru cache
146
0.405
Medium
2,154
https://leetcode.com/problems/lru-cache/discuss/2834061/Python-Use-a-single-dict-for-keyvalues-and-doubly-linked-list
class LRUCache: def __init__(self, capacity: int): self.n = capacity self.byKey = {} self.head = None self.tail = None def extract(self, key, new): if new[1] is not None: self.byKey[new[1]][2] = new[2] if new[2] is not None: self.byKey[new[2]][1] = new[1] if self.head == key: self.head = new[2] if self.tail == key: self.tail = new[1] new[1] = self.tail new[2] = None def get(self, key: int) -> int: new = self.byKey.pop(key, None) if not new: return -1 # need to move self.extract(key, new) self.byKey[key] = new if self.head is None: self.head = key if self.tail is not None: self.byKey[self.tail][2] = key self.tail = key return new[0] def put(self, key: int, value: int) -> None: new = self.byKey.pop(key, None) if new: # need to move self.extract(key, new) new[0] = value else: if len(self.byKey) == self.n: # need to evict old = self.byKey.pop(self.head, None) if old[1] is not None: self.byKey[old[1]][2] = old[2] if old[2] is not None: self.byKey[old[2]][1] = old[1] if self.tail == self.head: self.tail = None self.head = old[2] new = [value, self.tail, None] self.byKey[key] = new if self.head is None: self.head = key if self.tail is not None: self.byKey[self.tail][2] = key self.tail = key
lru-cache
[Python] Use a single dict for key/values and doubly linked list
constantstranger
0
2
lru cache
146
0.405
Medium
2,155
https://leetcode.com/problems/lru-cache/discuss/2832485/Python3-98-faster-with-explanation
class LRUCache: def __init__(self, capacity: int): self.cap = capacity self.imap = {} def get(self, key: int) -> int: if key in self.imap: tmp = self.imap[key] del self.imap[key] self.imap[key] = tmp return self.imap[key] else: return -1 def put(self, key: int, value: int) -> None: if len(self.imap) >= self.cap and not key in self.imap: for item in self.imap: del self.imap[item] break elif key in self.imap: del self.imap[key] self.imap[key] = value return self.imap[key] = value # Your LRUCache object will be instantiated and called as such: # obj = LRUCache(capacity) # param_1 = obj.get(key) # obj.put(key,value)
lru-cache
Python3, 98% faster with explanation
cvelazquez322
0
6
lru cache
146
0.405
Medium
2,156
https://leetcode.com/problems/lru-cache/discuss/2830129/Python3.7%2B-or-No-OrderedDict-Short-Python-Solution-using-DictionaryHashmap
class LRUCache: def __init__(self, capacity: int): self.d = {} self.size = capacity def get(self, key: int) -> int: if key not in self.d: return -1 self.d[key] = self.d.pop(key) return self.d[key] def put(self, key: int, value: int) -> None: if key in self.d: self.d.pop(key) self.d[key] = value if len(self.d) > self.size: self.d.pop(next(iter(self.d)))
lru-cache
Python3.7+ | No OrderedDict Short Python Solution using Dictionary/Hashmap
Aleph-Null
0
1
lru cache
146
0.405
Medium
2,157
https://leetcode.com/problems/lru-cache/discuss/2810727/Python-or-Simple-or-HashTable-or-LinkedList-or-Fast
class Node: def __init__(self, key = -1, val = -1): self.key, self.val = key, val self.prev, self.next = None, None class LRUCache: def __init__(self, capacity: int): self.size = capacity self.cache = {} self.head, self.tail = Node(), Node() self.head.next, self.tail.prev = self.tail, self.head def get(self, key: int) -> int: if key in self.cache: node = self.cache[key] self.remove(node) self.insert(node) return node.val return -1 def put(self, key: int, value: int) -> None: if self.size == 0: return if key in self.cache: node = self.cache[key] node.val = value self.remove(node) self.insert(node) return node = Node(key, value) if len(self.cache) == self.size: node_to_be_deleted = self.tail.prev self.remove(node_to_be_deleted) del self.cache[node_to_be_deleted.key] self.insert(node) self.cache[key] = node def remove(self, node): prev, next = node.prev, node.next prev.next, next.prev = next, prev def insert(self, node): next_node = self.head.next self.head.next, node.prev = node, self.head node.next, next_node.prev = next_node, node # Your LRUCache object will be instantiated and called as such: # obj = LRUCache(capacity) # param_1 = obj.get(key) # obj.put(key,value)
lru-cache
Python | Simple | HashTable | LinkedList | Fast
david-cobbina
0
5
lru cache
146
0.405
Medium
2,158
https://leetcode.com/problems/lru-cache/discuss/2759827/Python-orderedict
class LRUCache: def __init__(self, capacity: int): self.cache = collections.OrderedDict() self.capacity = capacity def get(self, key: int) -> int: if key not in self.cache: return -1 value = self.cache.get(key) self.cache.move_to_end(key) return value def put(self, key: int, value: int) -> None: if key in self.cache: self.cache[key] = value self.cache.move_to_end(key) else: if self.capacity == 0: self.cache.popitem(last=False) else: self.capacity -= 1 self.cache[key] = value # Your LRUCache object will be instantiated and called as such: # obj = LRUCache(capacity) # param_1 = obj.get(key) # obj.put(key,value)
lru-cache
Python orderedict
ychhhen
0
7
lru cache
146
0.405
Medium
2,159
https://leetcode.com/problems/lru-cache/discuss/2756623/Python%3A-dict()%2BDoubly-linkedList
class node: def __init__(self, key: int, val: int, pre = None, nxt = None): self.key = key self.val = val self.pre = pre self.nxt = nxt class LRUCache: def __init__(self, capacity: int): self.key2val = dict() self.MAXLEN = capacity self.size = 0 self.head = None self.tail = None def get(self, key: int) -> int: if key in self.key2val: value = self.key2val[key].val # Move to head self.__del(self.key2val[key]) self.__ins_head(key, value) return value return -1 def put(self, key: int, value: int) -> None: # 1.if key exists, update map value, move to head, then return if key in self.key2val: self.__del(self.key2val[key]) self.__ins_head(key, value) return # 2. if not in, check if LRU is full # Remove LRU item from hash map and list if self.size == self.MAXLEN: self.__del(self.tail) # add item self.__ins_head(key, value) ''' Del tail of list ''' def __del(self, v: node): ## Remove from dict self.key2val.pop(v.key) ## Del from list # if v is the only node if v.nxt == v: self.head = None self.tail = None else: v.nxt.pre = v.pre v.pre.nxt = v.nxt if v == self.tail: self.tail = v.pre if v == self.head: self.head = v.nxt # detach v from list v.nxt = None v.pre = None # Update cnt self.size -= 1 ''' Insert new node at the head of the list ''' def __ins_head(self, key: int, val: int): # Create node v = node(key, val) ## Add to dict self.key2val[key] = v ## Insert to list head # if empty list if self.size == 0: self.head = v self.tail = v v.nxt = v v.pre = v else: self.tail.nxt = v v.nxt = self.head self.head.pre = v v.pre = self.tail self.head = v # Update cnt self.size += 1 # Your LRUCache object will be instantiated and called as such: # obj = LRUCache(capacity) # param_1 = obj.get(key) # obj.put(key,value)
lru-cache
Python: dict()+Doubly-linkedList
KKCrush
0
4
lru cache
146
0.405
Medium
2,160
https://leetcode.com/problems/lru-cache/discuss/2756622/Python%3A-dict()%2BDoubly-linkedList
class node: def __init__(self, key: int, val: int, pre = None, nxt = None): self.key = key self.val = val self.pre = pre self.nxt = nxt class LRUCache: def __init__(self, capacity: int): self.key2val = dict() self.MAXLEN = capacity self.size = 0 self.head = None self.tail = None def get(self, key: int) -> int: if key in self.key2val: value = self.key2val[key].val # Move to head self.__del(self.key2val[key]) self.__ins_head(key, value) return value return -1 def put(self, key: int, value: int) -> None: # 1.if key exists, update map value, move to head, then return if key in self.key2val: self.__del(self.key2val[key]) self.__ins_head(key, value) return # 2. if not in, check if LRU is full # Remove LRU item from hash map and list if self.size == self.MAXLEN: self.__del(self.tail) # add item self.__ins_head(key, value) ''' Del tail of list ''' def __del(self, v: node): ## Remove from dict self.key2val.pop(v.key) ## Del from list # if v is the only node if v.nxt == v: self.head = None self.tail = None else: v.nxt.pre = v.pre v.pre.nxt = v.nxt if v == self.tail: self.tail = v.pre if v == self.head: self.head = v.nxt # detach v from list v.nxt = None v.pre = None # Update cnt self.size -= 1 ''' Insert new node at the head of the list ''' def __ins_head(self, key: int, val: int): # Create node v = node(key, val) ## Add to dict self.key2val[key] = v ## Insert to list head # if empty list if self.size == 0: self.head = v self.tail = v v.nxt = v v.pre = v else: self.tail.nxt = v v.nxt = self.head self.head.pre = v v.pre = self.tail self.head = v # Update cnt self.size += 1 # Your LRUCache object will be instantiated and called as such: # obj = LRUCache(capacity) # param_1 = obj.get(key) # obj.put(key,value)
lru-cache
Python: dict()+Doubly-linkedList
KKCrush
0
3
lru cache
146
0.405
Medium
2,161
https://leetcode.com/problems/lru-cache/discuss/2690470/LRU-Cache
class ListNode: def __init__(self, key = 0, val = 0): self.key = key self.val = val self.prev = None self.next = None class LRUCache: def __init__(self, capacity: int): self.capacity = capacity self.hashmap = {} self.head = ListNode() self.tail = ListNode() self.head.next = self.tail self.tail.prev = self.head def remove_node(self, node): node.prev.next = node.next node.next.prev = node.prev def add_node_to_last(self, node): self.tail.prev.next = node node.prev = self.tail.prev node.next = self.tail self.tail.prev = node def move_node_to_last(self, node): self.remove_node(node) self.add_node_to_last(node) def get(self, key: int) -> int: if key not in self.hashmap: return -1 node = self.hashmap[key] self.move_node_to_last(node) return node.val def put(self, key: int, value: int) -> None: if key in self.hashmap: node = self.hashmap[key] node.val = value self.move_node_to_last(node) return if len(self.hashmap) == self.capacity: del self.hashmap[self.head.next.key] self.remove_node(self.head.next) node = ListNode(key, value) self.hashmap[key] = node self.add_node_to_last(node)
lru-cache
LRU Cache
Erika_v
0
7
lru cache
146
0.405
Medium
2,162
https://leetcode.com/problems/lru-cache/discuss/2669692/Python-or-Easy-way-or-Ordered-Dictionary
class LRUCache: def __init__(self, capacity: int): self.lru_cache = collections.OrderedDict() self.capacity = capacity def get(self, key: int) -> int: if key not in self.lru_cache: return -1 self.lru_cache.move_to_end(key) return self.lru_cache[key] def put(self, key: int, value: int) -> None: if key in self.lru_cache: self.lru_cache[key] = value self.lru_cache.move_to_end(key) return if len(self.lru_cache) >= self.capacity: lru_key = next(iter(self.lru_cache)) del self.lru_cache[lru_key] self.lru_cache[key] = value # Your LRUCache object will be instantiated and called as such: # obj = LRUCache(capacity) # param_1 = obj.get(key) # obj.put(key,value)
lru-cache
Python | Easy way | Ordered Dictionary
gurubalanh
0
10
lru cache
146
0.405
Medium
2,163
https://leetcode.com/problems/lru-cache/discuss/2636368/LRU-or-three-solutions
class LinkedNode: def __init__(self, key = None, value = None, next = None): self.key = key self.value = value self.next = next class LRUCache: def __init__(self, capacity: int): self.capacity = capacity self.dummy = LinkedNode() self.tail = self.dummy self.added_precious_dict = dict() def get(self, key: int) -> int: if key not in self.added_precious_dict: return -1 self.setLRU(key) return self.tail.value def put(self, key: int, value: int) -> None: if key in self.added_precious_dict: self.setLRU(key) self.tail.value = value return node = LinkedNode(key, value) self.modifyLRU(node) if len(self.added_precious_dict) > self.capacity: self.removeNotLRU() # print(self.dummy.next.key, self.tail.value, node.key, node.value) def modifyLRU(self, node): self.added_precious_dict[node.key] = self.tail self.tail.next = node self.tail = node def removeNotLRU(self): head = self.dummy.next del self.added_precious_dict[head.key] self.dummy.next = head.next self.added_precious_dict[head.next.key] = self.dummy def setLRU(self, key): pre_node = self.added_precious_dict[key] target_node = pre_node.next if target_node == self.tail: return pre_node.next = target_node.next self.added_precious_dict[target_node.next.key] = pre_node target_node.next = None self.modifyLRU(target_node)
lru-cache
LRU | three solutions
MichelleZou
0
50
lru cache
146
0.405
Medium
2,164
https://leetcode.com/problems/lru-cache/discuss/2626540/Python-simple-solution-with-DoubleLinkedList
class Node: def __init__(self, key, value): self.key = key self.value = value self.prev = None self.next = None class LRUCache: def __init__(self, capacity: int): self.cap = capacity self.cache = {} #key : key, value: node self.head, self.tail = Node(0,0), Node(0, 0) self.head.next = self.tail self.tail.prev = self.head def insert(self, node): node.next = self.tail node.prev = self.tail.prev self.tail.prev.next = node self.tail.prev = node def remove(self, node): node.prev.next = node.next node.next.prev = node.prev def get(self, key: int) -> int: if key in self.cache: self.remove(self.cache[key]) self.insert(self.cache[key]) return self.cache[key].value else: return -1 def put(self, key: int, value: int) -> None: if key in self.cache: self.remove(self.cache[key]) self.cache[key] = Node(key, value) self.insert(self.cache[key]) if len(self.cache) > self.cap: del self.cache[self.head.next.key] self.remove(self.head.next) # Your LRUCache object will be instantiated and called as such: # obj = LRUCache(capacity) # param_1 = obj.get(key) # obj.put(key,value)
lru-cache
Python simple solution with DoubleLinkedList
ljxowen
0
57
lru cache
146
0.405
Medium
2,165
https://leetcode.com/problems/lru-cache/discuss/2611952/Python-EasyUnderstanding-Solution
class Node: def __init__(self,key=0,value=0): self.key,self.value = key,value self.prev = self.next = None class LRUCache: def __init__(self, capacity: int): self.capacity = capacity self.cache = {} self.left,self.right = Node(),Node() self.right.prev = self.left self.left.next = self.right self.left.next = self.right self.right.prev = self.left def insert(self,node): node.next = self.right node.prev = self.right.prev self.right.prev.next = node self.right.prev = node def remove(self,node): node.prev.next = node.next node.next.prev = node.prev def get(self, key: int) -> int: if key not in self.cache: return -1 else: self.remove(self.cache[key]) self.insert(self.cache[key]) return self.cache[key].value def put(self, key: int, value: int) -> None: if key not in self.cache: self.cache[key] = Node(key,value) else: self.remove(self.cache[key]) self.cache[key] = Node(key,value) # insert self.insert(self.cache[key]) if len(self.cache) > self.capacity: toremove = self.left.next self.remove(toremove) del self.cache[toremove.key] # Your LRUCache object will be instantiated and called as such: # obj = LRUCache(capacity) # param_1 = obj.get(key) # obj.put(key,value)
lru-cache
Python EasyUnderstanding Solution
al5861
0
59
lru cache
146
0.405
Medium
2,166
https://leetcode.com/problems/lru-cache/discuss/2601550/Extremely-Simple-Python-solution-with-Explanation
class LRUCache: # Easy peasy timer based solution def __init__(self, capacity: int): # Cache for value storage of a key # lru for lru priority storage of the key # Can a priority queue minheap also work? I think it will i just need to figure out how! self.cache = {} self.lru = {} self.size = capacity self.cc = 0 # timer def get(self, key: int) -> int: # If key is there return its value and also update the lru for it if key in self.cache: self.lru[key] = self.cc self.cc += 1 return self.cache[key] else: return -1 def put(self, key: int, value: int) -> None: # Key already exists if key in self.cache: self.cache[key] = value self.lru[key] = self.cc return # Size is still left to accomodate new keys no need to remove anything if self.size: self.cache[key] = value self.lru[key] = self.cc self.size -= 1 # find out lru key and evict it to accomodate the new one else: mini = min(self.lru, key=self.lru.get) del self.cache[mini] del self.lru[mini] self.cache[key] = value self.lru[key] = self.cc self.cc += 1
lru-cache
Extremely Simple Python solution with Explanation
shiv-codes
0
89
lru cache
146
0.405
Medium
2,167
https://leetcode.com/problems/lru-cache/discuss/2516850/146.-My-PythonandJAVA-Solution-with-comments
class Node: def __init__(self, key, val): self.key = key self.val = val self.prev = None self.next = None class LRUCache: def __init__(self, capacity: int): self.capacity = capacity self.cache = dict() # elem in dict are pair [key, node] #note that head and tail node are not included in the cache. they just indicate where the cache starts and ends self.head = Node(0,0) self.tail = Node(0,0) self.head.next = self.tail self.tail.prev = self.head def get(self, key: int) -> int: if key not in self.cache: return -1 node = self.cache[key] self.remove_node(node) self.add_node(node) return node.val def put(self, key: int, value: int) -> None: if key in self.cache: self.remove_node(self.cache[key]) node = Node(key,value) self.cache[key] = node self.add_node(node) # the beginning node, which is, head.next, would be the LRU to pop out if len(self.cache)>self.capacity: lru_node = self.head.next key = lru_node.key # note: remove the node not only from the chain, but also from the dict self.remove_node(lru_node) del self.cache[key] return def remove_node(self, node): # remove node: locate the node's previous node and next node, connect these two, which would skip the target node p = node.prev n = node.next p.next = n n.prev = p return def add_node(self,node): # add node into the chain, we define it as adding to the node before tail, so we have to locate the original end node before tail, and add the new node between this end node and self.tail prev_end = self.tail.prev prev_end.next = node node.next = self.tail self.tail.prev = node node.prev = prev_end return
lru-cache
146. My Python&JAVA Solution with comments
JunyiLin
0
23
lru cache
146
0.405
Medium
2,168
https://leetcode.com/problems/lru-cache/discuss/2516850/146.-My-PythonandJAVA-Solution-with-comments
class LRUCache: def __init__(self, capacity: int): self.capacity = capacity self.cache = collections.OrderedDict() # we use collecitons toolbox # orderedDict is a dictionary that will remember the order that each (key,value) pair that comes in # we also have function to remove item in this dict, from either the beginning or the end of the dict # we define the end as the most_recently used position, and the beginning as the least recently used position. Like a queue, FIFO. def get(self, key: int) -> int: if key not in self.cache: return -1 val = self.cache[key] # if we succeefully access this item, it means we have used it once, so we have to move it to the most_recently_used position, which is the end self.cache.move_to_end(key, last= True) # last = True means it moves the key-value pair to the end. IF last = False, it moves the the beginning. return val def put(self, key: int, value: int) -> None: if key in self.cache: # if this key is already in cache, we just need to move it to the most_recently used position, and the update it self.cache.move_to_end(key, last=True) # if we do not have this key in cache before, that's fine, we just add it into cache, it automatically goes into the end. self.cache[key] = value if len(self.cache)> self.capacity: # if after adding this new key, we run out of capacity, we will pop out the LRU elem, which is in the beginning. # last = False means we pop the beginning. self.cache.popitem(last=False)
lru-cache
146. My Python&JAVA Solution with comments
JunyiLin
0
23
lru cache
146
0.405
Medium
2,169
https://leetcode.com/problems/lru-cache/discuss/2491820/Python-runtime-42.97-memory-11.54
class LinkedList: def __init__(self, val): self.val = val self.next = None self.prev = None class LRUCache: def __init__(self, capacity: int): self.capacity = capacity self.d = {} self.head = None self.end = None def get(self, key: int) -> int: if key in self.d and self.d[key].val != -1: self.updateUsed(key) return self.d[key].val else: return -1 def put(self, key: int, value: int) -> None: if key in self.d and self.d[key].val != -1: self.updateUsed(key) self.d[key].val = value else: self.d[key] = LinkedList(value) if not self.head: self.head = self.d[key] self.end = self.d[key] else: self.head.prev = self.d[key] self.d[key].next = self.head self.head = self.d[key] if len(self.d.keys()) > self.capacity: delete = self.end if self.end.prev != None: self.end.prev.next = None self.end = self.end.prev delete.val = -1 def updateUsed(self, key): if not self.d[key].prev: # already at head return if not self.d[key].next: # already at end self.d[key].prev.next = None self.end = self.d[key].prev if self.d[key].prev and self.d[key].next: self.d[key].prev.next = self.d[key].next self.d[key].next.prev = self.d[key].prev self.d[key].prev = None self.d[key].next = self.head self.head.prev = self.d[key] self.head = self.d[key]
lru-cache
Python, runtime 42.97%, memory 11.54%
tsai00150
0
59
lru cache
146
0.405
Medium
2,170
https://leetcode.com/problems/lru-cache/discuss/2491820/Python-runtime-42.97-memory-11.54
class LinkedList: def __init__(self, key, val): self.key = key self.val = val self.next = None self.prev = None class LRUCache: def __init__(self, capacity: int): self.capacity = capacity self.d = {} self.head = None self.head = LinkedList(0,0) self.tail = LinkedList(0,0) self.head.next = self.tail self.tail.prev = self.head def get(self, key: int) -> int: if key in self.d: self.updateUsed(key) return self.d[key].val else: return -1 def put(self, key: int, value: int) -> None: if key in self.d: self.updateUsed(key) self.d[key].val = value else: # input new node self.d[key] = LinkedList(key, value) target_node = self.d[key] self.head.next.prev = target_node target_node.next = self.head.next self.head.next = target_node target_node.prev = self.head if len(self.d.keys()) > self.capacity: delete = self.tail.prev delete.prev.next = self.tail self.tail.prev = delete.prev del self.d[delete.key] def updateUsed(self, key): target_node = self.d[key] target_node.prev.next = target_node.next target_node.next.prev = target_node.prev self.head.next.prev = target_node target_node.next = self.head.next self.head.next = target_node target_node.prev = self.head
lru-cache
Python, runtime 42.97%, memory 11.54%
tsai00150
0
59
lru cache
146
0.405
Medium
2,171
https://leetcode.com/problems/lru-cache/discuss/2437043/Python-Hashtable
class Node: def __init__(self, key: int , val: int): self.key, self.val = key, val self.prev = self.next = None class LRUCache: def __init__(self, capacity: int): self.cap = capacity self.cache = {} # key : node # init double linked list self.head, self.tail = Node(0, 0), Node(0,0) self.head.next = self.tail self.tail.prev = self.head def remove(self, node): left = node.prev right = node.next left.next = right right.prev = left def insert(self, node): left = self.tail.prev left.next = node node.prev = left node.next = self.tail self.tail.prev = node def get(self, key: int) -> int: if key in self.cache: node = self.cache[key] self.remove(node) self.insert(node) return node.val return -1 def put(self, key: int, value: int) -> None: if key in self.cache: node = self.cache[key] node.val = value self.remove(node) self.insert(node) else: node = Node(key, value) if self.cap == len(self.cache): firstNode = self.head.next del self.cache[firstNode.key] self.remove(firstNode) self.insert(node) self.cache[key] = node
lru-cache
Python Hashtable
cccandj
0
70
lru cache
146
0.405
Medium
2,172
https://leetcode.com/problems/lru-cache/discuss/2431064/Python-Easy-to-Understand-oror-O(1)-Time-Complexity
class Node: def __init__(self,key, value): self.key, self.value = key, value self.next, self.prev = None, None class LRUCache: def __init__(self, capacity: int): self.cap = capacity self.cache = {} self.left = self.right = Node(0, 0) self.left.next, self.right.prev = self.right, self.left def remove(self, node): prev, nxt = node.prev, node.next prev.next, nxt.prev = nxt, prev def insert(self, node): prev, nxt = self.right.prev, self.right prev.next = nxt.prev = node node.next, node.prev = nxt, prev def get(self, key: int) -> int: if key in self.cache: self.remove(self.cache[key]) self.insert(self.cache[key]) return self.cache[key].value return -1 def put(self, key: int, value: int) -> None: if key in self.cache: self.remove(self.cache[key]) self.cache[key] = Node(key, value) self.insert(self.cache[key]) if len(self.cache) > self.cap: lru = self.left.next self.remove(lru) del self.cache[lru.key] # Your LRUCache object will be instantiated and called as such: # obj = LRUCache(capacity) # param_1 = obj.get(key) # obj.put(key,value)
lru-cache
Python - Easy to Understand || O(1) Time Complexity
dayaniravi123
0
75
lru cache
146
0.405
Medium
2,173
https://leetcode.com/problems/lru-cache/discuss/2238187/Python3-oror-List-oror-Simple-and-Easy-Approach-oror-Explained
class LRUCache: def __init__(self, capacity: int): self.lru = {} self.capacity = capacity def get(self, key: int) -> int: # check if key exists in lru if key not in self.lru: return -1 # repriotize the cache with the input key, which means bring this key to the top self.priotize(key) # return value for the input key return self.lru[key] def priotize(self, key): # collect the value of the key in the variable val = self.lru[key] # delete key from cache del self.lru[key] # push your key back to the top of the stack self.lru[key] = val def evict(self): # check if the length of the lru is getting higher than its capacity # and delete the least used key if len(self.lru) > self.capacity: del self.lru[list(self.lru)[0]] def put(self, key: int, value: int) -> None: # add key and value to the stack, prioritize and evict, if there is a need to evict. self.lru[key] = value self.priotize(key) self.evict()
lru-cache
Python3 || List || Simple and Easy Approach || Explained
mrusmanshahid
0
82
lru cache
146
0.405
Medium
2,174
https://leetcode.com/problems/lru-cache/discuss/2133141/Clear-Linked-Hashmap-solution-in-Python
class ListNode: def __init__(self, key, val): self.key = key self.val = val self.next = None self.prev = None class LRUCache: def __init__(self, capacity: int): self.capacity = capacity # a hashmap stores key to ListNode(key, value) pair self.map = dict() # dummy nodes to mitigate edge cases self.head = ListNode(0, 0) self.tail = ListNode(0, 0) # init the doubly linked list with [head<->tail] self.head.next = self.tail self.tail.prev = self.head def get(self, key: int) -> int: if (key in self.map): curr = self.map.get(key) self.removeX(curr) self.addX(curr) return curr.val return -1 def put(self, key: int, value: int) -> None: if (key in self.map): self.removeX(self.map[key]) self.map[key] = ListNode(key, value) self.addX(self.map[key]) if (len(self.map) > self.capacity): # remove the first(LRU) element in the list n = self.head.next self.removeX(n) self.map.pop(n.key, None) def addX(self, head): # set the current head pointer's prev to tail's prev pointer head.prev = self.tail.prev # set the current head pointer's next to tail pointer head.next = self.tail # set the tail pointer's old prev's next to the current head pointer self.tail.prev.next = head # set the tail pointer's old prev pointer to the new prev(head) pointer self.tail.prev = head def removeX(self, head): # set the old prev's next pointer to current head's next pointer head.prev.next = head.next # set old next's prev pointer to current head's prev pointer head.next.prev = head.prev
lru-cache
Clear Linked Hashmap solution in Python
leqinancy
0
30
lru cache
146
0.405
Medium
2,175
https://leetcode.com/problems/insertion-sort-list/discuss/1176552/Python3-188ms-Solution-(explanation-with-visualization)
class Solution: def insertionSortList(self, head: ListNode) -> ListNode: # No need to sort for empty list or list of size 1 if not head or not head.next: return head # Use dummy_head will help us to handle insertion before head easily dummy_head = ListNode(val=-5000, next=head) last_sorted = head # last node of the sorted part cur = head.next # cur is always the next node of last_sorted while cur: if cur.val >= last_sorted.val: last_sorted = last_sorted.next else: # Search for the position to insert prev = dummy_head while prev.next.val <= cur.val: prev = prev.next # Insert last_sorted.next = cur.next cur.next = prev.next prev.next = cur cur = last_sorted.next return dummy_head.next
insertion-sort-list
[Python3] 188ms Solution (explanation with visualization)
EckoTan0804
28
834
insertion sort list
147
0.503
Medium
2,176
https://leetcode.com/problems/insertion-sort-list/discuss/1629375/Python3-INSERTION-SORT-Explained
class Solution: def insertionSortList(self, head: Optional[ListNode]) -> Optional[ListNode]: sort = ListNode() #dummy node cur = head while cur: sortCur = sort while sortCur.next and cur.val >= sortCur.next.val: sortCur = sortCur.next tmp, sortCur.next = sortCur.next, cur cur = cur.next sortCur.next.next = tmp return sort.next
insertion-sort-list
βœ”οΈ [Python3] INSERTION SORT, Explained
artod
7
1,700
insertion sort list
147
0.503
Medium
2,177
https://leetcode.com/problems/insertion-sort-list/discuss/920840/Python-Solution-Explained-(video-%2B-code)
class Solution: def insertionSortList(self, head: ListNode) -> ListNode: dummy_head = ListNode() curr = head while curr: prev_pointer = dummy_head next_pointer = dummy_head.next while next_pointer: if curr.val < next_pointer.val: break prev_pointer = prev_pointer.next next_pointer = next_pointer.next temp = curr.next curr.next = next_pointer prev_pointer.next = curr curr = temp return dummy_head.next
insertion-sort-list
Python Solution Explained (video + code)
spec_he123
5
295
insertion sort list
147
0.503
Medium
2,178
https://leetcode.com/problems/insertion-sort-list/discuss/2474623/Python-Easiest-Insertion-sort
class Solution: def insertionSortList(self, head: Optional[ListNode]) -> Optional[ListNode]: dummy = ListNode(0,head) prev, curr = head,head.next # we can't go back so keep a previous pointer while curr: if curr.val >= prev.val: prev = curr curr = curr.next continue temp = dummy while curr.val > temp.next.val: temp = temp.next prev.next = curr.next curr.next = temp.next temp.next = curr curr = prev.next return dummy.next
insertion-sort-list
Python Easiest Insertion sort
Abhi_009
1
103
insertion sort list
147
0.503
Medium
2,179
https://leetcode.com/problems/insertion-sort-list/discuss/1630153/Python3-O(1)-space-solution-with-comments
class Solution: def insertionSortList(self, head: ListNode) -> ListNode: dummy = ListNode(0, next=head) cur = head while cur.next: # beginning of the list begin = dummy #traverse every element from begin of the list while not found element large or equal cur.next.val while cur.next.val > begin.next.val: begin = begin.next # transferring an element. If all the elements are smaller, then we change the element to ourselves tmp = cur.next cur.next = cur.next.next tmp.next = begin.next begin.next = tmp # if you did not move during the permutation, then move the pointer if cur.next == tmp: cur = cur.next return dummy.next
insertion-sort-list
[Python3] O(1) space solution with comments
maosipov11
1
79
insertion sort list
147
0.503
Medium
2,180
https://leetcode.com/problems/insertion-sort-list/discuss/2813143/python-fast-sol.-faster-then-98.95
class Solution: def insertionSortList(self, head: Optional[ListNode]) -> Optional[ListNode]: nums = [] cur = ans = head while head: nums.append(head.val) head = head.next nums = sorted(nums) count = 0 while cur: cur.val = nums[count] count+=1 cur = cur.next return ans
insertion-sort-list
python fast sol. faster then 98.95 %
pranjalmishra334
0
6
insertion sort list
147
0.503
Medium
2,181
https://leetcode.com/problems/insertion-sort-list/discuss/2801894/Python-solution
class Solution: def insertionSortList(self, head: Optional[ListNode]) -> Optional[ListNode]: dummy = ListNode(float('inf')) dummy.next = None lists = [dummy] while head: for i in range(len(lists)): if head.val < lists[i].val: lists.insert(i, head) break head = head.next for i in range(len(lists) - 1): lists[i].next = lists[i+1] if i != len(lists) - 2 else None return lists[0]
insertion-sort-list
Python solution
maomao1010
0
1
insertion sort list
147
0.503
Medium
2,182
https://leetcode.com/problems/insertion-sort-list/discuss/2605607/Mixture-of-bubble-and-insertion-sort-Python
class Solution: # Mixture of bubble and insertion sort def insertionSortList(self, head: ListNode) -> ListNode: dummy = ListNode(0, head) prev, curr = head, head.next while curr: if prev.val <= curr.val: prev, curr = prev.next, curr.next continue temp = dummy while temp.next and temp.next.val < curr.val: temp = temp.next prev.next = prev.next.next curr.next = temp.next temp.next = curr curr = prev.next return dummy.next
insertion-sort-list
Mixture of bubble and insertion sort Python
shiv-codes
0
22
insertion sort list
147
0.503
Medium
2,183
https://leetcode.com/problems/insertion-sort-list/discuss/2518977/Python-Clearly-commented-insertion-sort-Sentinel-Node
class Solution: def insertionSortList(self, head: Optional[ListNode]) -> Optional[ListNode]: # keep the start of the list -> sentinel node # this really helps us to keep the code concise sentinel = ListNode(val=-50001, next=head) # we need to iterate through the list and check whether we are smaller then # the previous node # once this happens we need to do the following steps: # 1) cut out the node (set previous node.next to current.next) # 2) find the position to put the node # 2a) We need to start from the beginning and as soon we are smaller or equal # to the next node # 2b) we insert by setting current.next to us and us.next to current.next # 3) We need to got back to the node we were and continue previous = sentinel current = head while current: # check whether we are smaller than previous node if current.val < previous.val: # delete the current node from the list (1) previous.next = current.next # go through the list until we encounter a node (2a) # that is bigger than us start = sentinel while start.next.val < current.val: start = start.next # insert our node in the list again (2b) current.next = start.next start.next = current # return to the previous node (3) current = previous # everything is fine and we can go on previous = current current = current.next return sentinel.next
insertion-sort-list
[Python] - Clearly commented insertion sort - Sentinel Node
Lucew
0
69
insertion sort list
147
0.503
Medium
2,184
https://leetcode.com/problems/insertion-sort-list/discuss/1996065/python-3-oror-simple-iterative-solution-oror-O(n2)O(1)
class Solution: def insertionSortList(self, head: Optional[ListNode]) -> Optional[ListNode]: dummy = ListNode(0, head) prevI, i = dummy, head while i: prevJ, j = dummy, dummy.next while j.val < i.val: prevJ, j = j, j.next if i is j: prevI, i = i, i.next else: prevI.next = i.next i.next = j prevJ.next = i i = prevI.next return dummy.next
insertion-sort-list
python 3 || simple iterative solution || O(n^2)/O(1)
dereky4
0
168
insertion sort list
147
0.503
Medium
2,185
https://leetcode.com/problems/insertion-sort-list/discuss/1963960/Naive-approach-with-99.10-efficiency
class Solution: def insertionSortList(self, head: Optional[ListNode]) -> Optional[ListNode]: temp=head l=[] while temp: l.append(temp.val) temp=temp.next l.sort() d=ListNode(-1) res=d for i in l: res.next=ListNode(i) res=res.next return d.next
insertion-sort-list
Naive approach with 99.10% efficiency
captain_sathvik
0
78
insertion sort list
147
0.503
Medium
2,186
https://leetcode.com/problems/insertion-sort-list/discuss/1630404/Python3-Easy-to-follow-up-solution
class Solution: def insertionSortList(self, head: Optional[ListNode]) -> Optional[ListNode]: last_sorted = head it = last_sorted.next temp = ListNode(val=-1, next=last_sorted) while it is not None: if last_sorted.val <= it.val: last_sorted = it it = it.next else: nxt = it.next prev = temp while prev.next and prev.next.val <= it.val: prev = prev.next it.next = prev.next prev.next = it last_sorted.next = nxt it = last_sorted return temp.next
insertion-sort-list
[Python3] Easy to follow up solution
varian97
0
29
insertion sort list
147
0.503
Medium
2,187
https://leetcode.com/problems/insertion-sort-list/discuss/1629650/Python3-Insertion-Sort-or-Inplace-or-O(1)-memory-or-98.51-Memory-Usage-or-O(n2)-Time-complexity
class Solution: def insertionSortList(self, head: Optional[ListNode]) -> Optional[ListNode]: temp=head #Iterate over list while(temp): #store next value of current node n=temp.next # To avoid circular loop if(temp==head): prev=temp temp=n continue #Find correct position for current node temprep=head while(temprep and temprep.val<temp.val): prevrep=temprep temprep=temprep.next #Find previous of current node(node to be replaced) while(prev.next!=temp): prev=prev.next #Two cases: #1 - If current node to be replaced is start of list if(temprep==head): prev.next=temp.next temp.next=temprep head=temp #2 - If node to be replaced is in between else: prevrep.next=temp temp.next=temprep if(temprep.next==temp): temprep.next=n else: prev.next=n #Iterate over list temp=n return head
insertion-sort-list
[Python3] Insertion Sort | Inplace | O(1) memory | 98.51% Memory Usage | O(n^2) Time complexity
Cdeo05
0
79
insertion sort list
147
0.503
Medium
2,188
https://leetcode.com/problems/insertion-sort-list/discuss/1072564/python-3-solution-O(N*N)
class Solution: def insertionSortList(self, head: ListNode) -> ListNode: if head==None: return head h=head prev=head head=head.next while(head): node=h while(node!=head): if node.val>head.val and node==h: prev.next=head.next head.next=node h=head head=prev.next break elif node.val>head.val: prev.next=head.next head.next=node previous.next=head head=prev.next break previous=node node=node.next if node==head: prev=head head=head.next return h
insertion-sort-list
python 3 solution O(N*N)
AchalGupta
0
119
insertion sort list
147
0.503
Medium
2,189
https://leetcode.com/problems/insertion-sort-list/discuss/921121/Python3-solution
class Solution: def insertionSortList(self, head: ListNode) -> ListNode: if not head: return head e = head # end of sorted portion n = e.next # next node to sort while n: # if next node exists s = head p = None while s != n: #scan from head to thru e (n is e.next) if s.val <= n.val: p, s = s, s.next else: if p: p.next, n.next, e.next = n, s, n.next else: head, n.next, e.next = n, s, n.next break if s==n: e = e.next # if didn't break n = e.next return head
insertion-sort-list
Python3 solution
dalechoi
0
208
insertion sort list
147
0.503
Medium
2,190
https://leetcode.com/problems/insertion-sort-list/discuss/920733/insertionSortList-or-python3-intuitive-two-pointer
class Solution: def insertionSortList(self, head: ListNode) -> ListNode: if not head: return None hi, hp = head.next, head while hi: lo, lp = head, None while lo: if lo == hi: hp, hi = hi, hi.next break if lo.val >= hi.val: hp.next = hi.next if lp: lp.next = hi else: head = hi hi.next, hi = lo, hp.next break lp, lo = lo, lo.next return head
insertion-sort-list
insertionSortList | python3 intuitive two pointer
hangyu1130
0
62
insertion sort list
147
0.503
Medium
2,191
https://leetcode.com/problems/insertion-sort-list/discuss/715153/Python3-O(N2)-algo
class Solution: def insertionSortList(self, head: ListNode) -> ListNode: node, prev = head, None # ...<-###<-prev, node->###->... while node: if not prev or prev.val <= node.val: node.next, node, prev = prev, node.next, node #set new head of reversed list &amp; move prev/node else: temp = prev while temp.next and temp.next.val > node.val: #locate where to insert node temp = temp.next node.next, node, temp.next = temp.next, node.next, node #insert node after temp #reverse linked list node, prev = prev, None while node: node.next, node, prev = prev, node.next, node return prev
insertion-sort-list
[Python3] O(N^2) algo
ye15
0
60
insertion sort list
147
0.503
Medium
2,192
https://leetcode.com/problems/insertion-sort-list/discuss/715153/Python3-O(N2)-algo
class Solution: def insertionSortList(self, head: ListNode) -> ListNode: #collect values nums = [] node = head while node: nums.append(node.val) node = node.next #sort nums.sort() #reconstruct linked list dummy = node = ListNode() for x in nums: node.next = ListNode(x) node = node.next return dummy.next
insertion-sort-list
[Python3] O(N^2) algo
ye15
0
60
insertion sort list
147
0.503
Medium
2,193
https://leetcode.com/problems/insertion-sort-list/discuss/715153/Python3-O(N2)-algo
class Solution: def insertionSortList(self, head: ListNode) -> ListNode: dummy = node = ListNode(next=head) # dummy head while (temp := node.next): prev = dummy while prev.next.val < temp.val: prev = prev.next if prev.next != temp: node.next = node.next.next # remove temp out of linked list temp.next = prev.next prev.next = temp else: node = node.next return dummy.next
insertion-sort-list
[Python3] O(N^2) algo
ye15
0
60
insertion sort list
147
0.503
Medium
2,194
https://leetcode.com/problems/insertion-sort-list/discuss/715153/Python3-O(N2)-algo
class Solution: def insertionSortList(self, head: ListNode) -> ListNode: dummy = node = ListNode(val=-inf, next=head) while node.next: if node.val <= node.next.val: node = node.next else: temp = node.next prev = dummy while prev.next and prev.next.val <= temp.val: prev = prev.next node.next = node.next.next temp.next = prev.next prev.next = temp return dummy.next
insertion-sort-list
[Python3] O(N^2) algo
ye15
0
60
insertion sort list
147
0.503
Medium
2,195
https://leetcode.com/problems/insertion-sort-list/discuss/1176570/Python3-44ms-(beats-98.25)-by-using-Python-sorted()-function
class Solution: def insertionSortList(self, head: ListNode) -> ListNode: # No need to sort for empty list or list of size 1 if not head or not head.next: return head nodes = [] cur = head while head: nodes.append(head) head = head.next # Sort nodes by their values ascendingly nodes = sorted(nodes, key=lambda node: node.val) # Re-organize list cur = head = nodes[0] for node in nodes[1:]: cur.next = node cur = cur.next cur.next = None return head
insertion-sort-list
[Python3] 44ms (beats 98.25%) by using Python sorted() function
EckoTan0804
-5
227
insertion sort list
147
0.503
Medium
2,196
https://leetcode.com/problems/sort-list/discuss/1796085/Sort-List-or-Python-O(nlogn)-Solution-or-95-Faster
class Solution: def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]: if not head or not head.next: return head # Split the list into two halfs left = head right = self.getMid(head) tmp = right.next right.next = None right = tmp left = self.sortList(left) right = self.sortList(right) return self.merge(left, right) def getMid(self, head): slow = head fast = head.next while fast and fast.next: slow = slow.next fast = fast.next.next return slow # Merge the list def merge(self, list1, list2): newHead = tail = ListNode() while list1 and list2: if list1.val > list2.val: tail.next = list2 list2 = list2.next else: tail.next = list1 list1 = list1.next tail = tail.next if list1: tail.next = list1 if list2: tail.next = list2 return newHead.next
sort-list
βœ”οΈ Sort List | Python O(nlogn) Solution | 95% Faster
pniraj657
25
1,900
sort list
148
0.543
Medium
2,197
https://leetcode.com/problems/sort-list/discuss/1795826/Python-Simple-Python-Solution-With-Two-Approach
class Solution: def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]: new_node=head result = new_node array = [] while head != None: array.append(head.val) head=head.next array = sorted(array) for num in array: new_node.val = num new_node = new_node.next return result
sort-list
[ Python ] βœ”βœ” Simple Python Solution With Two Approach πŸ”₯✌
ASHOK_KUMAR_MEGHVANSHI
8
315
sort list
148
0.543
Medium
2,198
https://leetcode.com/problems/sort-list/discuss/1795136/Python3-Clean%2BSimple-or-FastandSlow-or-Mergesort
class Solution: def split(self, head): prev = None slow = fast = head while fast and fast.next: prev = slow slow = slow.next fast = fast.next.next if prev: prev.next = None return slow def merge(self, l1, l2): dummy = tail = ListNode() while l1 or l2: v1 = l1.val if l1 else inf v2 = l2.val if l2 else inf if v1 <= v2: tail.next = l1 l1 = l1.next else: tail.next = l2 l2 = l2.next tail = tail.next return dummy.next def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]: if not head or not head.next: return head head2 = self.split(head) head1 = self.sortList(head) head2 = self.sortList(head2) return self.merge(head1, head2)
sort-list
[Python3] Clean+Simple | Fast&Slow | Mergesort
PatrickOweijane
5
720
sort list
148
0.543
Medium
2,199