title
stringlengths
1
100
titleSlug
stringlengths
3
77
Java
int64
0
1
Python3
int64
1
1
content
stringlengths
28
44.4k
voteCount
int64
0
3.67k
question_content
stringlengths
65
5k
question_hints
stringclasses
970 values
Full Explanation with clean code Python
linked-list-cycle-ii
1
1
# Intuition\n\nThe solution uses the Floyd\'s cycle detection algorithm, also known as the "tortoise and hare algorithm". It involves traversing the linked list with two pointers, a slow pointer (tortoise) and a fast pointer (hare). If the linked list has a cycle, the fast pointer will eventually catch up with the slow...
1
Given the `head` of a linked list, return _the node where the cycle begins. If there is no cycle, return_ `null`. There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the `next` pointer. Internally, `pos` is used to denote the index of the node that ta...
null
One iteration. Two approaches. Python C++
linked-list-cycle-ii
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nOne iteration is enough\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity...
1
Given the `head` of a linked list, return _the node where the cycle begins. If there is no cycle, return_ `null`. There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the `next` pointer. Internally, `pos` is used to denote the index of the node that ta...
null
BEST APPROACH IN C++ / C / JAVA
linked-list-cycle-ii
1
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIn which we used two pointer approach\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nwe take two pointer fast and slow which are poin head of the node .\nand if linked list in cycle then after some time fast and s...
1
Given the `head` of a linked list, return _the node where the cycle begins. If there is no cycle, return_ `null`. There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the `next` pointer. Internally, `pos` is used to denote the index of the node that ta...
null
simple solution || o(1) space complexity || python
linked-list-cycle-ii
0
1
# Intuition and Approach\n* simply traverse the linklist and replace val of node with 1000000.\n* if their is cycle you will get 1000000 again while traversing.so, when you get it return that node.\n* if their is no cycle then return the node which is at the end of list.\n\n# Complexity\n- Time complexity:O(n)\n\n- Spa...
1
Given the `head` of a linked list, return _the node where the cycle begins. If there is no cycle, return_ `null`. There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the `next` pointer. Internally, `pos` is used to denote the index of the node that ta...
null
🥇 C++ | PYTHON | JAVA || Diagram Explained ; ] ✅
linked-list-cycle-ii
1
1
**UPVOTE IF HELPFuuL**\n\n# Approach\n\nFloyd\'s Linked List Cycle Finding Algorithm\nTortoise And Hare algorithm\n\nWorking of Algo\n**Step 1: Presence of the cycle**\n1. Take two pointers `slow`\u200Aand\u200A`fast`\u200A.\n2. Both of them will point to head of the linked list initially.\n3. `slow` will move one step...
13
Given the `head` of a linked list, return _the node where the cycle begins. If there is no cycle, return_ `null`. There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the `next` pointer. Internally, `pos` is used to denote the index of the node that ta...
null
Solution
linked-list-cycle-ii
1
1
```C++ []\nclass Solution {\npublic:\n ListNode *detectCycle(ListNode *head) {\n ListNode*slow=head;\n ListNode*fast=head;\n ListNode*enter=head; \n while(fast!=NULL&&fast->next!=NULL)\n {\n slow=slow->next;\n fast=fast->next->next;\n if(slow==fast)\n ...
206
Given the `head` of a linked list, return _the node where the cycle begins. If there is no cycle, return_ `null`. There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the `next` pointer. Internally, `pos` is used to denote the index of the node that ta...
null
[C++ | Python3] Concise explanation with math & diagrams
linked-list-cycle-ii
0
1
![ll cycle.png](https://assets.leetcode.com/users/images/a348b1bc-cef0-4042-905f-e7e16f078ea2_1685637703.8367739.png)\n\nWe have illustrated the linked list in the diagram above, which consists of two main components: the linear track, denoted by the variable `t`, and the cycle, denoted by the variable `c`.\n\nLet\'s c...
2
Given the `head` of a linked list, return _the node where the cycle begins. If there is no cycle, return_ `null`. There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the `next` pointer. Internally, `pos` is used to denote the index of the node that ta...
null
Python two pointer solution
linked-list-cycle-ii
0
1
```\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution:\n def detectCycle(self, head: ListNode) -> ListNode:\n slow = fast = head\n\n while fast and fast.next:\n slow, fast = slow.next, ...
2
Given the `head` of a linked list, return _the node where the cycle begins. If there is no cycle, return_ `null`. There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the `next` pointer. Internally, `pos` is used to denote the index of the node that ta...
null
📌📌Python3 || ⚡simple solution uwu
linked-list-cycle-ii
0
1
\n```\nclass Solution:\n def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:\n slow = fast = head\n \n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n if slow == fast:\n break\n \n if not fast...
1
Given the `head` of a linked list, return _the node where the cycle begins. If there is no cycle, return_ `null`. There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the `next` pointer. Internally, `pos` is used to denote the index of the node that ta...
null
[Python] - Clean & Simple Floyd's Cycle Detaction O(1) space
linked-list-cycle-ii
0
1
\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- Here, we are incrementing Slow and Fast both.\n- Only difference is we are increasing **slow** by $$1$$ and **fast** by $$2$$.\n- If at any time slow is same as fast then we detacted cycle at there.\n- Then for finding **start** of the cycle, If t...
6
Given the `head` of a linked list, return _the node where the cycle begins. If there is no cycle, return_ `null`. There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the `next` pointer. Internally, `pos` is used to denote the index of the node that ta...
null
simple python O(1) space solution
linked-list-cycle-ii
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIf I need to get rid of the dictionary solution, there must be some feature in the problem set up that allows for space optimization. \n\nTo detect whether there is a cycle without the $$O(N)$$ of the dictionary, you can use two pointers:...
10
Given the `head` of a linked list, return _the node where the cycle begins. If there is no cycle, return_ `null`. There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the `next` pointer. Internally, `pos` is used to denote the index of the node that ta...
null
Create an array and i ~i
reorder-list
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nCreate an array and you can do i and ~i\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n)\n- Space complexity:\n<!-- Add y...
1
You are given the head of a singly linked-list. The list can be represented as: L0 -> L1 -> ... -> Ln - 1 -> Ln _Reorder the list to be on the following form:_ L0 -> Ln -> L1 -> Ln - 1 -> L2 -> Ln - 2 -> ... You may not modify the values in the list's nodes. Only nodes themselves may be changed. **Example 1:** **...
null
Worst O(n) Solution you will see. Python
reorder-list
0
1
# Approach\nReverse linked list and count number of elements\n1 -> 2 -> 3 -> 4 -> 5\n5 -> 4 -> 3 -> 2 -> 1\n\nAnd connect them, we will need len(linked list) - 1 connections, so track it.\n\n# Why?\nJust for fun, the solution is not efficient in terms of time and space complexity because we create deepcopy and use weir...
2
You are given the head of a singly linked-list. The list can be represented as: L0 -> L1 -> ... -> Ln - 1 -> Ln _Reorder the list to be on the following form:_ L0 -> Ln -> L1 -> Ln - 1 -> L2 -> Ln - 2 -> ... You may not modify the values in the list's nodes. Only nodes themselves may be changed. **Example 1:** **...
null
Python O(n) by two-pointers [w/ Visualization]
reorder-list
0
1
The first method is to reorder by **two pointers** with the help of **aux O(n)** space **array**.\n\nThe second method is to reorder by **mid-point finding**, **linked list reverse**, and **linkage update** in O(1) aux space.\n\n---\n\nMethod_#1\n\n**Visualization and Diagram**\n\n![image](https://assets.leetcode.com/u...
146
You are given the head of a singly linked-list. The list can be represented as: L0 -> L1 -> ... -> Ln - 1 -> Ln _Reorder the list to be on the following form:_ L0 -> Ln -> L1 -> Ln - 1 -> L2 -> Ln - 2 -> ... You may not modify the values in the list's nodes. Only nodes themselves may be changed. **Example 1:** **...
null
easy to understand in O(1) space complexity || fast
reorder-list
0
1
```\n# below function reverse the linklist\ndef reverse(head):\n p=head\n if(p.next==None):\n return head\n else:\n th=p.next\n p.next=None\n while(th.next):\n k=th.next\n th.next=p\n p=th\n th=k\n th.next=p\n return th\nclass Solution:\n def reorderList...
2
You are given the head of a singly linked-list. The list can be represented as: L0 -> L1 -> ... -> Ln - 1 -> Ln _Reorder the list to be on the following form:_ L0 -> Ln -> L1 -> Ln - 1 -> L2 -> Ln - 2 -> ... You may not modify the values in the list's nodes. Only nodes themselves may be changed. **Example 1:** **...
null
Beats100%✅ | O( n )✅ | Easy-To-Understand✅ | Python (Step by step explanation)✅
reorder-list
0
1
# Intuition\nThe problem asks us to reorder a given singly-linked list in a specific way. We need to find a way to split the list into two halves, reverse the second half, and merge the two halves together to achieve the desired reordering.\n\n# Approach\n1. We use the slow and fast pointer technique to find the middle...
3
You are given the head of a singly linked-list. The list can be represented as: L0 -> L1 -> ... -> Ln - 1 -> Ln _Reorder the list to be on the following form:_ L0 -> Ln -> L1 -> Ln - 1 -> L2 -> Ln - 2 -> ... You may not modify the values in the list's nodes. Only nodes themselves may be changed. **Example 1:** **...
null
understandable Python3 solution
reorder-list
0
1
\n# Code\n```\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def reorderList(self, head: Optional[ListNode]) -> None:\n """\n Do not return anything, modify head in-place inst...
2
You are given the head of a singly linked-list. The list can be represented as: L0 -> L1 -> ... -> Ln - 1 -> Ln _Reorder the list to be on the following form:_ L0 -> Ln -> L1 -> Ln - 1 -> L2 -> Ln - 2 -> ... You may not modify the values in the list's nodes. Only nodes themselves may be changed. **Example 1:** **...
null
Python3 | Beats 96% | Alternating Reordering of Linked List
reorder-list
0
1
# Intuition\nThe key insight is to first divide the list into two halves and then reverse the second half. The crux lies in the reversed second half. When nodes are reversed, the last node becomes the first, and the second-to-last becomes the second, and so on. This reversal aligns with the alternating order. By insert...
5
You are given the head of a singly linked-list. The list can be represented as: L0 -> L1 -> ... -> Ln - 1 -> Ln _Reorder the list to be on the following form:_ L0 -> Ln -> L1 -> Ln - 1 -> L2 -> Ln - 2 -> ... You may not modify the values in the list's nodes. Only nodes themselves may be changed. **Example 1:** **...
null
143: Solution with step by step explanation
reorder-list
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nTo reorder the linked list we can follow the below steps:\n\n1. Find the middle node of the linked list using slow and fast pointer approach.\n2. Reverse the second half of the linked list.\n3. Merge the first half and the r...
7
You are given the head of a singly linked-list. The list can be represented as: L0 -> L1 -> ... -> Ln - 1 -> Ln _Reorder the list to be on the following form:_ L0 -> Ln -> L1 -> Ln - 1 -> L2 -> Ln - 2 -> ... You may not modify the values in the list's nodes. Only nodes themselves may be changed. **Example 1:** **...
null
Awesome Slow Fast Logic
reorder-list
0
1
\n\n# Fast And Slow Logic\n```\nclass Solution:\n def reorderList(self, head: Optional[ListNode]) -> None:\n # divide the linked list\n slow,fast=head,head.next\n while fast and fast.next:\n slow=slow.next\n fast=fast.next.next\n second=slow.next\n # making Nu...
13
You are given the head of a singly linked-list. The list can be represented as: L0 -> L1 -> ... -> Ln - 1 -> Ln _Reorder the list to be on the following form:_ L0 -> Ln -> L1 -> Ln - 1 -> L2 -> Ln - 2 -> ... You may not modify the values in the list's nodes. Only nodes themselves may be changed. **Example 1:** **...
null
Simple Python O(n) time and space using Double-Ended Queue
reorder-list
0
1
# Intuition\n**The following are my thoughts as written before I even wrote one line of code.**\n\nThe problem is asking us to insert between every node in the first half the linked list with the reverse order node at the end of the list.\n\nI think we can push the nodes as we encounter them onto a double-ended queue. ...
1
You are given the head of a singly linked-list. The list can be represented as: L0 -> L1 -> ... -> Ln - 1 -> Ln _Reorder the list to be on the following form:_ L0 -> Ln -> L1 -> Ln - 1 -> L2 -> Ln - 2 -> ... You may not modify the values in the list's nodes. Only nodes themselves may be changed. **Example 1:** **...
null
Easy understanding python solution for beginner
reorder-list
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
0
You are given the head of a singly linked-list. The list can be represented as: L0 -> L1 -> ... -> Ln - 1 -> Ln _Reorder the list to be on the following form:_ L0 -> Ln -> L1 -> Ln - 1 -> L2 -> Ln - 2 -> ... You may not modify the values in the list's nodes. Only nodes themselves may be changed. **Example 1:** **...
null
Solution
binary-tree-preorder-traversal
1
1
```C++ []\nclass Solution {\npublic:\n vector<int> preorderTraversal(TreeNode* root) {\n vector<int> preorder;\n stack<TreeNode*> stack;\n if (root == NULL)\n return preorder;\n stack.push(root);\n while(!stack.empty()) {\n TreeNode* curr = stack.top();\n ...
208
Given the `root` of a binary tree, return _the preorder traversal of its nodes' values_. **Example 1:** **Input:** root = \[1,null,2,3\] **Output:** \[1,2,3\] **Example 2:** **Input:** root = \[\] **Output:** \[\] **Example 3:** **Input:** root = \[1\] **Output:** \[1\] **Constraints:** * The number of nodes ...
null
Binbin with phenomenal ideas is back!
binary-tree-preorder-traversal
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
1
Given the `root` of a binary tree, return _the preorder traversal of its nodes' values_. **Example 1:** **Input:** root = \[1,null,2,3\] **Output:** \[1,2,3\] **Example 2:** **Input:** root = \[\] **Output:** \[\] **Example 3:** **Input:** root = \[1\] **Output:** \[1\] **Constraints:** * The number of nodes ...
null
Recuresive solution with explanation
binary-tree-preorder-traversal
1
1
\n\n# Approach\nThe problem asks to perform a preorder traversal on a binary tree and return the node values in the traversal order. Preorder traversal visits the root, then the left subtree, and finally the right subtree.\n\nThe given C++ solution uses a recursive approach to perform the preorder traversal. It defines...
2
Given the `root` of a binary tree, return _the preorder traversal of its nodes' values_. **Example 1:** **Input:** root = \[1,null,2,3\] **Output:** \[1,2,3\] **Example 2:** **Input:** root = \[\] **Output:** \[\] **Example 3:** **Input:** root = \[1\] **Output:** \[1\] **Constraints:** * The number of nodes ...
null
Proper Tree Traversal || DFS || Python Easy || Begineer Friendly ||
binary-tree-preorder-traversal
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n- The intuition here is to perform a preorder traversal of a binary tree and collect the values of the nodes in a list as you traverse the tree.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- We can implement a ...
13
Given the `root` of a binary tree, return _the preorder traversal of its nodes' values_. **Example 1:** **Input:** root = \[1,null,2,3\] **Output:** \[1,2,3\] **Example 2:** **Input:** root = \[\] **Output:** \[\] **Example 3:** **Input:** root = \[1\] **Output:** \[1\] **Constraints:** * The number of nodes ...
null
Iterative DFS, Python
binary-tree-preorder-traversal
0
1
Probably the exact same solution as others. Did it iterative style using queue as suggested by the follow up.\n\n# Code\n```\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = rig...
0
Given the `root` of a binary tree, return _the preorder traversal of its nodes' values_. **Example 1:** **Input:** root = \[1,null,2,3\] **Output:** \[1,2,3\] **Example 2:** **Input:** root = \[\] **Output:** \[\] **Example 3:** **Input:** root = \[1\] **Output:** \[1\] **Constraints:** * The number of nodes ...
null
Using stack implementation beats 99% no recursion involved
binary-tree-preorder-traversal
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n**Here basic stack implementation is done,we have an ans array which stores the answer,as it is stack we append left node after right node\n,then,till stack exists we can keep appending till leaves returning answer**\n\n# Complexity\n- Ti...
1
Given the `root` of a binary tree, return _the preorder traversal of its nodes' values_. **Example 1:** **Input:** root = \[1,null,2,3\] **Output:** \[1,2,3\] **Example 2:** **Input:** root = \[\] **Output:** \[\] **Example 3:** **Input:** root = \[1\] **Output:** \[1\] **Constraints:** * The number of nodes ...
null
Python3 Solution Time O(n) Space O(n)
binary-tree-preorder-traversal
0
1
# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n\nfrom collections import deque\n\n\nclass Solution:\n def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:\n...
1
Given the `root` of a binary tree, return _the preorder traversal of its nodes' values_. **Example 1:** **Input:** root = \[1,null,2,3\] **Output:** \[1,2,3\] **Example 2:** **Input:** root = \[\] **Output:** \[\] **Example 3:** **Input:** root = \[1\] **Output:** \[1\] **Constraints:** * The number of nodes ...
null
Most optimal iterative solution with explanation
binary-tree-preorder-traversal
1
1
\n\n# Approach\n- Initialize an empty stack and push the root node onto the stack.\n- While the stack is not empty:\n - Pop a node from the stack and add its value to the preorder list.\n - Push the right child onto the stack (if it exists).\n - Push the left child onto the stack (if it exists).\n\n# Complexit...
4
Given the `root` of a binary tree, return _the preorder traversal of its nodes' values_. **Example 1:** **Input:** root = \[1,null,2,3\] **Output:** \[1,2,3\] **Example 2:** **Input:** root = \[\] **Output:** \[\] **Example 3:** **Input:** root = \[1\] **Output:** \[1\] **Constraints:** * The number of nodes ...
null
Python || Morris Traversal || O(1) Space Complexity
binary-tree-preorder-traversal
0
1
```\nclass Solution:\n def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:\n preorder=[]\n curr=root\n while curr:\n if curr.left==None:\n preorder.append(curr.val)\n curr=curr.right\n else:\n prev=curr.left\n ...
1
Given the `root` of a binary tree, return _the preorder traversal of its nodes' values_. **Example 1:** **Input:** root = \[1,null,2,3\] **Output:** \[1,2,3\] **Example 2:** **Input:** root = \[\] **Output:** \[\] **Example 3:** **Input:** root = \[1\] **Output:** \[1\] **Constraints:** * The number of nodes ...
null
Binbin wrote another outstanding solution!
binary-tree-postorder-traversal
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
1
Given the `root` of a binary tree, return _the postorder traversal of its nodes' values_. **Example 1:** **Input:** root = \[1,null,2,3\] **Output:** \[3,2,1\] **Example 2:** **Input:** root = \[\] **Output:** \[\] **Example 3:** **Input:** root = \[1\] **Output:** \[1\] **Constraints:** * The number of the n...
null
Recursive and interative(both using one stack and using two stacks) solution with explanation
binary-tree-postorder-traversal
1
1
\n# RECURSIVE\n## Approach\n- Define a helper function postorder that takes a node and a vector to store the postorder traversal.\n- If the node is null, return.\n- Recursively traverse the left subtree in postorder.\n- Recursively traverse the right subtree in postorder.\n- Add the node\'s value to the vector in the p...
8
Given the `root` of a binary tree, return _the postorder traversal of its nodes' values_. **Example 1:** **Input:** root = \[1,null,2,3\] **Output:** \[3,2,1\] **Example 2:** **Input:** root = \[\] **Output:** \[\] **Example 3:** **Input:** root = \[1\] **Output:** \[1\] **Constraints:** * The number of the n...
null
Easy || Recursive & Iterative || 100% || Explained (Java, C++, Python, Python3)
binary-tree-postorder-traversal
1
1
# **Java Solution (Iterative Approach Using Stack):**\nRuntime: 1 ms, faster than 89.81% of Java online submissions for Binary Tree Postorder Traversal.\nMemory Usage: 42 MB, less than 74.94% of Java online submissions for Binary Tree Postorder Traversal.\n```\nclass Solution {\n public List<Integer> postorderTraver...
47
Given the `root` of a binary tree, return _the postorder traversal of its nodes' values_. **Example 1:** **Input:** root = \[1,null,2,3\] **Output:** \[3,2,1\] **Example 2:** **Input:** root = \[\] **Output:** \[\] **Example 3:** **Input:** root = \[1\] **Output:** \[1\] **Constraints:** * The number of the n...
null
145: Solution with step by step explanation
binary-tree-postorder-traversal
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nThis solution uses a stack to implement an iterative postorder traversal of the binary tree. The algorithm starts by adding the root node to the stack. Then, while the stack is not empty, it pops the next node from the stack...
5
Given the `root` of a binary tree, return _the postorder traversal of its nodes' values_. **Example 1:** **Input:** root = \[1,null,2,3\] **Output:** \[3,2,1\] **Example 2:** **Input:** root = \[\] **Output:** \[\] **Example 3:** **Input:** root = \[1\] **Output:** \[1\] **Constraints:** * The number of the n...
null
Python || Easy || Recursive || Iterative || Both Solutions
binary-tree-postorder-traversal
0
1
**Iterative Solution:**\n```\ndef postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:\n if root is None:\n return \n a=[root]\n ans=[]\n while a:\n t=a.pop()\n ans.append(t.val)\n if t.left:\n a.append(t.left)\n ...
4
Given the `root` of a binary tree, return _the postorder traversal of its nodes' values_. **Example 1:** **Input:** root = \[1,null,2,3\] **Output:** \[3,2,1\] **Example 2:** **Input:** root = \[\] **Output:** \[\] **Example 3:** **Input:** root = \[1\] **Output:** \[1\] **Constraints:** * The number of the n...
null
Binary Tree postorder Traversal
binary-tree-postorder-traversal
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
2
Given the `root` of a binary tree, return _the postorder traversal of its nodes' values_. **Example 1:** **Input:** root = \[1,null,2,3\] **Output:** \[3,2,1\] **Example 2:** **Input:** root = \[\] **Output:** \[\] **Example 3:** **Input:** root = \[1\] **Output:** \[1\] **Constraints:** * The number of the n...
null
Python Elegant & Short | DFS + BFS | Based on generators
binary-tree-postorder-traversal
0
1
# BFS solution:\n```\nfrom typing import List, Optional\n\n\nclass Solution:\n\t"""\n\tTime: O(n)\n\tMemory: O(n)\n\t"""\n\n\tdef postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:\n\t\tif root is None:\n\t\t\treturn []\n\n\t\tpostorder = []\n\t\tstack = [root]\n\n\t\twhile stack:\n\t\t\tnode = stack.po...
9
Given the `root` of a binary tree, return _the postorder traversal of its nodes' values_. **Example 1:** **Input:** root = \[1,null,2,3\] **Output:** \[3,2,1\] **Example 2:** **Input:** root = \[\] **Output:** \[\] **Example 3:** **Input:** root = \[1\] **Output:** \[1\] **Constraints:** * The number of the n...
null
Python Easy Solution || Iteration || 100% || Beats 98%||
binary-tree-postorder-traversal
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here...
1
Given the `root` of a binary tree, return _the postorder traversal of its nodes' values_. **Example 1:** **Input:** root = \[1,null,2,3\] **Output:** \[3,2,1\] **Example 2:** **Input:** root = \[\] **Output:** \[\] **Example 3:** **Input:** root = \[1\] **Output:** \[1\] **Constraints:** * The number of the n...
null
using stack implementation,O(N), no recursion used
binary-tree-postorder-traversal
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n**Here basic stack implementation is done,we have an ans array which stores the answer,as it is stack we append left node then right node\n,till stack exists we can keep appending till leaves returning answer,\nthe required answer will be...
2
Given the `root` of a binary tree, return _the postorder traversal of its nodes' values_. **Example 1:** **Input:** root = \[1,null,2,3\] **Output:** \[3,2,1\] **Example 2:** **Input:** root = \[\] **Output:** \[\] **Example 3:** **Input:** root = \[1\] **Output:** \[1\] **Constraints:** * The number of the n...
null
Solution
lru-cache
1
1
```C++ []\nclass LRUCache {\npublic:\n inline static int M[10001];\n inline static int16_t L[10002][2];\n int cap, size = 0;\n const int NONE = 10001;\n int head = NONE, tail = NONE;\n \n LRUCache(int capacity) : cap(capacity) {\n memset(M, 0xff, sizeof M);\n }\n \n inline void eras...
434
Design a data structure that follows the constraints of a **[Least Recently Used (LRU) cache](https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU)**. Implement the `LRUCache` class: * `LRUCache(int capacity)` Initialize the LRU cache with **positive** size `capacity`. * `int get(int key)` Return the valu...
null
✅DLL + Map || C++ || JAVA || PYTHON || Beginner Friendly🔥🔥🔥
lru-cache
1
1
# Intuition:\nThe intuition is to maintain a fixed-size cache of key-value pairs using a doubly linked list and an unordered map. When accessing or adding a key-value pair, it moves the corresponding node to the front of the linked list, making it the most recently used item. This way, the least recently used item is a...
178
Design a data structure that follows the constraints of a **[Least Recently Used (LRU) cache](https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU)**. Implement the `LRUCache` class: * `LRUCache(int capacity)` Initialize the LRU cache with **positive** size `capacity`. * `int get(int key)` Return the valu...
null
Very simple and concise solution using Python OrderedDict
lru-cache
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nOrderedDicts in python maintain the order of insertion and can perform access and deletion operations in O(1). They are therefore an ideal candidate for this problem.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nU...
0
Design a data structure that follows the constraints of a **[Least Recently Used (LRU) cache](https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU)**. Implement the `LRUCache` class: * `LRUCache(int capacity)` Initialize the LRU cache with **positive** size `capacity`. * `int get(int key)` Return the valu...
null
LRU (Least Recently Used) cache✅ | O( 1 )✅ | Python(Step by step explanation)✅
lru-cache
0
1
# Intuition\nThe problem requires implementing an LRU (Least Recently Used) cache, which stores a fixed number of key-value pairs and removes the least recently used item when the cache reaches its capacity. The intuition is to use a combination of a doubly-linked list and a hash map. The linked list keeps track of the...
3
Design a data structure that follows the constraints of a **[Least Recently Used (LRU) cache](https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU)**. Implement the `LRUCache` class: * `LRUCache(int capacity)` Initialize the LRU cache with **positive** size `capacity`. * `int get(int key)` Return the valu...
null
🔥Fast Pythonic Solution🔥
lru-cache
0
1
# Intuition\nFor Python 3.7+ dictionary iteration order is guaranteed to be in order of insertion.\n\n# Complexity\n- Time complexity: $$O(1)$$ for one operation.\n\n- Space complexity: $$O(1)$$ for one operation.\n\n# Code\n```\nclass LRUCache:\n def __init__(self, capacity):\n self.dict = {}\n self.f...
25
Design a data structure that follows the constraints of a **[Least Recently Used (LRU) cache](https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU)**. Implement the `LRUCache` class: * `LRUCache(int capacity)` Initialize the LRU cache with **positive** size `capacity`. * `int get(int key)` Return the valu...
null
LRU CACHE (USING ORDERED DICT)
lru-cache
0
1
# Intuition\nOn first glimpse , I thought we could use a normal dictionary but we need to maintain the order of the cache and according to capacity we have to change it. So , instead of going for the normal dict we can go for orderedDict from collections\n\n# Approach\n<!-- Describe your approach to solving the problem...
3
Design a data structure that follows the constraints of a **[Least Recently Used (LRU) cache](https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU)**. Implement the `LRUCache` class: * `LRUCache(int capacity)` Initialize the LRU cache with **positive** size `capacity`. * `int get(int key)` Return the valu...
null
Python || Double Linked List + Hashmap
lru-cache
0
1
```\nclass LRUCache: \n class Node: \n def __init__(self,key,val):\n self.key=key\n self.val=val\n self.prev=None\n self.next=None\n\n def __init__(self, capacity: int):\n self.capacity=capacity\n self.dic={}\n self.head=self.Node(-1,-1)\...
1
Design a data structure that follows the constraints of a **[Least Recently Used (LRU) cache](https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU)**. Implement the `LRUCache` class: * `LRUCache(int capacity)` Initialize the LRU cache with **positive** size `capacity`. * `int get(int key)` Return the valu...
null
Easy Python Solution Without OrderedDict
lru-cache
0
1
# Intuition\nUsing Python Dict for O(1) searching and updation of elements and a dequeue to store order of Least Recently Used key-value pairs \n\n\n\n# Code\n```\nclass LRUCache:\n\n def __init__(self, capacity: int):\n self.cache = {}\n self.length = capacity\n self.lru_keys = []\n\n def ge...
3
Design a data structure that follows the constraints of a **[Least Recently Used (LRU) cache](https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU)**. Implement the `LRUCache` class: * `LRUCache(int capacity)` Initialize the LRU cache with **positive** size `capacity`. * `int get(int key)` Return the valu...
null
[Python 3] Double Linked List with moving existing node after using
lru-cache
0
1
```python3 []\nclass LinkedNode:\n def __init__(self, key = -1, val = -1):\n self.key = key\n self.val = val\n self.prev = None\n self.next = None\n\nclass LRUCache:\n def __init__(self, capacity: int):\n self.capacity = capacity\n self.cache = dict()\n self.head =...
12
Design a data structure that follows the constraints of a **[Least Recently Used (LRU) cache](https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU)**. Implement the `LRUCache` class: * `LRUCache(int capacity)` Initialize the LRU cache with **positive** size `capacity`. * `int get(int key)` Return the valu...
null
[Python3] doubly linked list and dictionary
lru-cache
0
1
* The most frequent operation of the problem is changing the node position in the list. \n Change position of the node means two operations, delete and insert.\n Double linked list data structure takes constant time O(1) to insert or delete nodes a linked list by repointing the previous and next pointer of th...
195
Design a data structure that follows the constraints of a **[Least Recently Used (LRU) cache](https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU)**. Implement the `LRUCache` class: * `LRUCache(int capacity)` Initialize the LRU cache with **positive** size `capacity`. * `int get(int key)` Return the valu...
null
Python Easy Solution | Dictionary | 701 ms | beats 91.59%
lru-cache
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe use a dictionary to store the key value pairs and shift their position depending on their use.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nFor the get function, if the key exists in the dictionary we store t...
10
Design a data structure that follows the constraints of a **[Least Recently Used (LRU) cache](https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU)**. Implement the `LRUCache` class: * `LRUCache(int capacity)` Initialize the LRU cache with **positive** size `capacity`. * `int get(int key)` Return the valu...
null
Python | DLL | Hashmap | Beats 95% Memory
lru-cache
0
1
# Code\n```\nclass Node:\n def __init__(self, key, value):\n self.key = key\n self.value = value\n self.next = None\n self.prev = None\n\nclass LRUCache:\n\n def __init__(self, capacity: int):\n self.head = None\n self.tail = None\n self.hash_map = {}\n self...
1
Design a data structure that follows the constraints of a **[Least Recently Used (LRU) cache](https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU)**. Implement the `LRUCache` class: * `LRUCache(int capacity)` Initialize the LRU cache with **positive** size `capacity`. * `int get(int key)` Return the valu...
null
Beats 100% | CodeDominar Solution
lru-cache
0
1
# Code\n```\nclass LRUCache:\n def __init__(self, capacity):\n self.capacity = capacity\n self.cache = OrderedDict()\n\n def get(self, key):\n if key not in self.cache:\n return -1\n value = self.cache.pop(key)\n self.cache[key] = value\n return value\n\n de...
4
Design a data structure that follows the constraints of a **[Least Recently Used (LRU) cache](https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU)**. Implement the `LRUCache` class: * `LRUCache(int capacity)` Initialize the LRU cache with **positive** size `capacity`. * `int get(int key)` Return the valu...
null
Python3 Solution
lru-cache
0
1
\n```\nclass LRUCache:\n\n def __init__(self, capacity: int):\n self.capacity=capacity\n self.cache=OrderedDict()\n \n\n def get(self, key: int) -> int:\n if key not in self.cache:\n return -1\n\n value=self.cache.pop(key)\n self.cache[key]=value\n retur...
3
Design a data structure that follows the constraints of a **[Least Recently Used (LRU) cache](https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU)**. Implement the `LRUCache` class: * `LRUCache(int capacity)` Initialize the LRU cache with **positive** size `capacity`. * `int get(int key)` Return the valu...
null
Ex-Amazon explains a solution with a video, Python, JavaScript, Java and C++
lru-cache
1
1
# Solution Video\n\nhttps://youtu.be/4Uh7nUGoeog\n\n# *** Please upvote and subscribe to my channel from here. I have 226 videos as of July 19th***\nhttp://www.youtube.com/channel/UC9RMNwYTL3SXCP6ShLWVFww?sub_confirmation=1\n\n\n---\n\n# Approach\nThis is based on Python code. Other might be differnt a bit.\n\n1. Creat...
9
Design a data structure that follows the constraints of a **[Least Recently Used (LRU) cache](https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU)**. Implement the `LRUCache` class: * `LRUCache(int capacity)` Initialize the LRU cache with **positive** size `capacity`. * `int get(int key)` Return the valu...
null
easy python solution with 69% TC
insertion-sort-list
0
1
```\ndef insertionSortList(self, head: Optional[ListNode]) -> Optional[ListNode]:\n\tdef add(node):\n\t\tcurr = self.ans\n\t\twhile(curr):\n\t\t\tif(curr.val < node.val):\n\t\t\t\tprev = curr\n\t\t\t\tcurr = curr.next\n\t\t\telse: break\n\t\tnode.next, prev.next = prev.next, node\n\tself.ans = ListNode(-5001)\n\twhile(...
2
Given the `head` of a singly linked list, sort the list using **insertion sort**, and return _the sorted list's head_. The steps of the **insertion sort** algorithm: 1. Insertion sort iterates, consuming one input element each repetition and growing a sorted output list. 2. At each iteration, insertion sort removes...
null
[Python3] 188ms Solution (explanation with visualization)
insertion-sort-list
0
1
**Idea**\n- Add `dummy_head` before `head` will help us to handle the insertion easily\n- Use two pointers\n\t- `last_sorted`: last node of the sorted part, whose value is the largest of the sorted part\n\t- `cur`: next node of `last_sorted`, which is the current node to be considered\n\n\tAt the beginning, `last_sorte...
42
Given the `head` of a singly linked list, sort the list using **insertion sort**, and return _the sorted list's head_. The steps of the **insertion sort** algorithm: 1. Insertion sort iterates, consuming one input element each repetition and growing a sorted output list. 2. At each iteration, insertion sort removes...
null
147: Solution with step by step explanation
insertion-sort-list
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nThe solution involves iterating through the linked list, removing each node from the list, and then inserting it into the sorted portion of the list. The sorted portion of the list is initially just the first node, and grows...
9
Given the `head` of a singly linked list, sort the list using **insertion sort**, and return _the sorted list's head_. The steps of the **insertion sort** algorithm: 1. Insertion sort iterates, consuming one input element each repetition and growing a sorted output list. 2. At each iteration, insertion sort removes...
null
✔️ [Python3] INSERTION SORT, Explained
insertion-sort-list
0
1
The idea is to create a dummy node that would be the head of the sorted part of the list. Iterate over the given list and one by one add nodes to the sorted list at the appropriate place following the insertion sort algorithm.\n\nTime: **O(n^2)**\nSpace: **O(1)**\n\nRuntime: 1677 ms, faster than **51.65%** of Python3 o...
7
Given the `head` of a singly linked list, sort the list using **insertion sort**, and return _the sorted list's head_. The steps of the **insertion sort** algorithm: 1. Insertion sort iterates, consuming one input element each repetition and growing a sorted output list. 2. At each iteration, insertion sort removes...
null
Singly Linked List - Insertion Sort. Python Beats 50% ✅
insertion-sort-list
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTypical inserton sort adapted to singly linked list. Presumably we should have handled the case we don\'t have a head. But I did not.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. We should create a second fun...
2
Given the `head` of a singly linked list, sort the list using **insertion sort**, and return _the sorted list's head_. The steps of the **insertion sort** algorithm: 1. Insertion sort iterates, consuming one input element each repetition and growing a sorted output list. 2. At each iteration, insertion sort removes...
null
Python Easiest Insertion sort
insertion-sort-list
0
1
```\nclass Solution:\n def insertionSortList(self, head: Optional[ListNode]) -> Optional[ListNode]:\n dummy = ListNode(0,head)\n prev, curr = head,head.next\n # we can\'t go back so keep a previous pointer \n \n while curr:\n if curr.val >= prev.val:\n pre...
1
Given the `head` of a singly linked list, sort the list using **insertion sort**, and return _the sorted list's head_. The steps of the **insertion sort** algorithm: 1. Insertion sort iterates, consuming one input element each repetition and growing a sorted output list. 2. At each iteration, insertion sort removes...
null
insertion sort on linkedList
insertion-sort-list
0
1
# Code\n```\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def insertionSortList(self, head: Optional[ListNode]) -> Optional[ListNode]:\n dummy = ListNode(0, head)\n prev, cur...
0
Given the `head` of a singly linked list, sort the list using **insertion sort**, and return _the sorted list's head_. The steps of the **insertion sort** algorithm: 1. Insertion sort iterates, consuming one input element each repetition and growing a sorted output list. 2. At each iteration, insertion sort removes...
null
Insertion sorting method in linked list beat 80%
insertion-sort-list
0
1
\n\n# Code\n```\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def insertionSortList(self, head: Optional[ListNode]) -> Optional[ListNode]:\n dummy =ListNode(0,head)\n prev,cu...
0
Given the `head` of a singly linked list, sort the list using **insertion sort**, and return _the sorted list's head_. The steps of the **insertion sort** algorithm: 1. Insertion sort iterates, consuming one input element each repetition and growing a sorted output list. 2. At each iteration, insertion sort removes...
null
Best solution for beginners in linked list using insertion sort
insertion-sort-list
0
1
\n\n# Code\n```\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def insertionSortList(self, head: Optional[ListNode]) -> Optional[ListNode]:\n dummy= ListNode(next=head)\n prev...
0
Given the `head` of a singly linked list, sort the list using **insertion sort**, and return _the sorted list's head_. The steps of the **insertion sort** algorithm: 1. Insertion sort iterates, consuming one input element each repetition and growing a sorted output list. 2. At each iteration, insertion sort removes...
null
[Python/C/C++/Java] Legit iterative solutions. O(1) space! No recursion! With detailed explaination
sort-list
1
1
# **TL;DR**\n### **Short and sweet. O(nlogn) time, O(1) space.**\n``` python []\ndef sortList(self, head: Optional[ListNode]) -> Optional[ListNode]:\n dummy = ListNode(0)\n dummy.next = head\n\n # Grab sublists of size 1, then 2, then 4, etc, until fully merged\n steps = 1\n while True:\n # Record the progress ...
412
Given the `head` of a linked list, return _the list after sorting it in **ascending order**_. **Example 1:** **Input:** head = \[4,2,1,3\] **Output:** \[1,2,3,4\] **Example 2:** **Input:** head = \[-1,5,3,4,0\] **Output:** \[-1,0,3,4,5\] **Example 3:** **Input:** head = \[\] **Output:** \[\] **Constraints:** * ...
null
148: Solution with step by step explanation
sort-list
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nThe approach we will use is Merge Sort:\n\n1. Base Case: If the length of the linked list is less than or equal to 1, then the list is already sorted.\n2. Split the linked list into two halves. We will use the "slow and fast...
38
Given the `head` of a linked list, return _the list after sorting it in **ascending order**_. **Example 1:** **Input:** head = \[4,2,1,3\] **Output:** \[1,2,3,4\] **Example 2:** **Input:** head = \[-1,5,3,4,0\] **Output:** \[-1,0,3,4,5\] **Example 3:** **Input:** head = \[\] **Output:** \[\] **Constraints:** * ...
null
Python Recursize merge sort
sort-list
0
1
\n```\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]:\n size = 0;\n t = head;\n while(t):\n ...
5
Given the `head` of a linked list, return _the list after sorting it in **ascending order**_. **Example 1:** **Input:** head = \[4,2,1,3\] **Output:** \[1,2,3,4\] **Example 2:** **Input:** head = \[-1,5,3,4,0\] **Output:** \[-1,0,3,4,5\] **Example 3:** **Input:** head = \[\] **Output:** \[\] **Constraints:** * ...
null
Python (Simple Merge Sort)
sort-list
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
1
Given the `head` of a linked list, return _the list after sorting it in **ascending order**_. **Example 1:** **Input:** head = \[4,2,1,3\] **Output:** \[1,2,3,4\] **Example 2:** **Input:** head = \[-1,5,3,4,0\] **Output:** \[-1,0,3,4,5\] **Example 3:** **Input:** head = \[\] **Output:** \[\] **Constraints:** * ...
null
✔️ Sort List | Python O(nlogn) Solution | 95% Faster
sort-list
0
1
**\uD83D\uDD3C IF YOU FIND THIS POST HELPFUL PLEASE UPVOTE \uD83D\uDC4D**\n\nVisit this blog to learn Python tips and techniques and to find a Leetcode solution with an explanation: https://www.python-techs.com/\n\n**Solution:**\n```\nclass Solution:\n def sortList(self, head: Optional[ListNode]) -> Optional[ListNod...
41
Given the `head` of a linked list, return _the list after sorting it in **ascending order**_. **Example 1:** **Input:** head = \[4,2,1,3\] **Output:** \[1,2,3,4\] **Example 2:** **Input:** head = \[-1,5,3,4,0\] **Output:** \[-1,0,3,4,5\] **Example 3:** **Input:** head = \[\] **Output:** \[\] **Constraints:** * ...
null
I don't like to implement Sort. Converted LL to Array back to LL
sort-list
0
1
\nSurprisingly Fast honestly\n# Code\n```\nclass Solution:\n def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]:\n a = []\n while head:\n a.append(head.val)\n head = head.next\n a.sort()\n\n if not a: return \n root = ListNode(a[0])\n cu...
2
Given the `head` of a linked list, return _the list after sorting it in **ascending order**_. **Example 1:** **Input:** head = \[4,2,1,3\] **Output:** \[1,2,3,4\] **Example 2:** **Input:** head = \[-1,5,3,4,0\] **Output:** \[-1,0,3,4,5\] **Example 3:** **Input:** head = \[\] **Output:** \[\] **Constraints:** * ...
null
Python || Merge Sort || O(nlogn) Solution
sort-list
0
1
```\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def divide(self,head):\n slow,fast=head,head.next\n while fast and fast.next:\n slow=slow.next\n fast=...
24
Given the `head` of a linked list, return _the list after sorting it in **ascending order**_. **Example 1:** **Input:** head = \[4,2,1,3\] **Output:** \[1,2,3,4\] **Example 2:** **Input:** head = \[-1,5,3,4,0\] **Output:** \[-1,0,3,4,5\] **Example 3:** **Input:** head = \[\] **Output:** \[\] **Constraints:** * ...
null
Using Merge sort with explanation
sort-list
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nThis approach will use Merge Sort:\n\nBase Case: If the length of the linked list is less than or equal to 1, then the list is already sorted so just return head. \n\nSplit the linked list into two halves. We will use the "s...
1
Given the `head` of a linked list, return _the list after sorting it in **ascending order**_. **Example 1:** **Input:** head = \[4,2,1,3\] **Output:** \[1,2,3,4\] **Example 2:** **Input:** head = \[-1,5,3,4,0\] **Output:** \[-1,0,3,4,5\] **Example 3:** **Input:** head = \[\] **Output:** \[\] **Constraints:** * ...
null
Python/JS by merge sort [w/ Comment]
sort-list
0
1
Python by merge sort\n\n---\n\n**Implementation** by merge sort\n\n```\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\n\nclass Solution:\n def sortList(self, head: ListNode) -> ListNode:\n \n # ...
21
Given the `head` of a linked list, return _the list after sorting it in **ascending order**_. **Example 1:** **Input:** head = \[4,2,1,3\] **Output:** \[1,2,3,4\] **Example 2:** **Input:** head = \[-1,5,3,4,0\] **Output:** \[-1,0,3,4,5\] **Example 3:** **Input:** head = \[\] **Output:** \[\] **Constraints:** * ...
null
Python O(n^2) solution for your reference
max-points-on-a-line
0
1
```\n def maxPoints(self, points: List[List[int]]) -> int:\n def dic():\n return defaultdict(int);\n ans = 0;\n hmap = defaultdict(dic) \n n = len(points)\n for i in range(0,n):\n print("------------")\n print(f\'i:{i} point[i]:{points[i]} \')\n ...
2
Given an array of `points` where `points[i] = [xi, yi]` represents a point on the **X-Y** plane, return _the maximum number of points that lie on the same straight line_. **Example 1:** **Input:** points = \[\[1,1\],\[2,2\],\[3,3\]\] **Output:** 3 **Example 2:** **Input:** points = \[\[1,1\],\[3,2\],\[5,3\],\[4,1\]...
null
Простое решение через построение уравнения прямых
max-points-on-a-line
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
2
Given an array of `points` where `points[i] = [xi, yi]` represents a point on the **X-Y** plane, return _the maximum number of points that lie on the same straight line_. **Example 1:** **Input:** points = \[\[1,1\],\[2,2\],\[3,3\]\] **Output:** 3 **Example 2:** **Input:** points = \[\[1,1\],\[3,2\],\[5,3\],\[4,1\]...
null
python solution using atan2
max-points-on-a-line
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
2
Given an array of `points` where `points[i] = [xi, yi]` represents a point on the **X-Y** plane, return _the maximum number of points that lie on the same straight line_. **Example 1:** **Input:** points = \[\[1,1\],\[2,2\],\[3,3\]\] **Output:** 3 **Example 2:** **Input:** points = \[\[1,1\],\[3,2\],\[5,3\],\[4,1\]...
null
Runtime Beats 99.56%,Python
max-points-on-a-line
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\nO(n\xB2)\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Solution:\n def maxPoints(self, points: List[List[int]]) -> int: \...
1
Given an array of `points` where `points[i] = [xi, yi]` represents a point on the **X-Y** plane, return _the maximum number of points that lie on the same straight line_. **Example 1:** **Input:** points = \[\[1,1\],\[2,2\],\[3,3\]\] **Output:** 3 **Example 2:** **Input:** points = \[\[1,1\],\[3,2\],\[5,3\],\[4,1\]...
null
Python, time=O(n^2), space=O(n)
max-points-on-a-line
0
1
# Complexity\n- Time complexity:\n O(n^2)\n\n- Space complexity:\n O(n)\n\n# Code\n```\nclass Solution:\n def maxPoints(self, points: List[List[int]]) -> int:\n count = 1\n \n for i in range(len(points)):\n seen = {}\n for j in range(i+1, len(points)):\n\n ...
1
Given an array of `points` where `points[i] = [xi, yi]` represents a point on the **X-Y** plane, return _the maximum number of points that lie on the same straight line_. **Example 1:** **Input:** points = \[\[1,1\],\[2,2\],\[3,3\]\] **Output:** 3 **Example 2:** **Input:** points = \[\[1,1\],\[3,2\],\[5,3\],\[4,1\]...
null
Hashing the (m,c) values of a line
max-points-on-a-line
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
1
Given an array of `points` where `points[i] = [xi, yi]` represents a point on the **X-Y** plane, return _the maximum number of points that lie on the same straight line_. **Example 1:** **Input:** points = \[\[1,1\],\[2,2\],\[3,3\]\] **Output:** 3 **Example 2:** **Input:** points = \[\[1,1\],\[3,2\],\[5,3\],\[4,1\]...
null
Optimised official solution. 99% less mem, 85% faster
max-points-on-a-line
0
1
# Intuition\nHere are some thoughs on offcial solution and how it can be improved:\n\n- Instead of calculating atan2 that we can do a single float division.\n- No need to calcuklate `dy` if `dx` is 0.\n- To save some space on GC we can resue the counter.\n- No need fo +1 in each iteration of the main loop as we can do ...
1
Given an array of `points` where `points[i] = [xi, yi]` represents a point on the **X-Y** plane, return _the maximum number of points that lie on the same straight line_. **Example 1:** **Input:** points = \[\[1,1\],\[2,2\],\[3,3\]\] **Output:** 3 **Example 2:** **Input:** points = \[\[1,1\],\[3,2\],\[5,3\],\[4,1\]...
null
Python solution (slope) with explanation!
max-points-on-a-line
0
1
First, the function checks if there are fewer than 3 points in the array. In this case, the maximum number of points that can lie on the same straight line is the number of points in the array, so it returns this value.\n\nNext, initialize a variable result to 0, which will be used to store the maximum number of points...
1
Given an array of `points` where `points[i] = [xi, yi]` represents a point on the **X-Y** plane, return _the maximum number of points that lie on the same straight line_. **Example 1:** **Input:** points = \[\[1,1\],\[2,2\],\[3,3\]\] **Output:** 3 **Example 2:** **Input:** points = \[\[1,1\],\[3,2\],\[5,3\],\[4,1\]...
null
python3 - straightforward - sum of points in linear equations
max-points-on-a-line
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n* to draw a line we need to find linear equation for it\n* store each equation in a hash map\n* store unique points that belongs to the equation\n* count number of points\n\n# Code\n```\nclass Solution:\n def maxPoints(self, points: Li...
1
Given an array of `points` where `points[i] = [xi, yi]` represents a point on the **X-Y** plane, return _the maximum number of points that lie on the same straight line_. **Example 1:** **Input:** points = \[\[1,1\],\[2,2\],\[3,3\]\] **Output:** 3 **Example 2:** **Input:** points = \[\[1,1\],\[3,2\],\[5,3\],\[4,1\]...
null
Python Solution O(n^2)
max-points-on-a-line
0
1
# Complexity\n- Time complexity: O(n^2)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def maxPoints(self, points: List[List[int]]) -> int:\n \n res = 0\n for p1 in point...
1
Given an array of `points` where `points[i] = [xi, yi]` represents a point on the **X-Y** plane, return _the maximum number of points that lie on the same straight line_. **Example 1:** **Input:** points = \[\[1,1\],\[2,2\],\[3,3\]\] **Output:** 3 **Example 2:** **Input:** points = \[\[1,1\],\[3,2\],\[5,3\],\[4,1\]...
null
Easy Python Solution
max-points-on-a-line
0
1
```\nclass Solution:\n def maxPoints(self, points: List[List[int]]) -> int:\n n = len(points);\n if n == 1: return 1\n res = 2;\n for i in range(n):\n d = defaultdict(int);\n for j in range(n):\n if i != j:\n d[math.atan2(points[j][1...
1
Given an array of `points` where `points[i] = [xi, yi]` represents a point on the **X-Y** plane, return _the maximum number of points that lie on the same straight line_. **Example 1:** **Input:** points = \[\[1,1\],\[2,2\],\[3,3\]\] **Output:** 3 **Example 2:** **Input:** points = \[\[1,1\],\[3,2\],\[5,3\],\[4,1\]...
null
📌📌Python3 || 159 ms, faster than 60.79% of Python3 || Clean and Easy to Understand
max-points-on-a-line
0
1
```\ndef maxPoints(self, points: List[List[int]]) -> int:\n if len(points) < 3:\n return len(points)\n\n dict = {}\n for b in points:\n for a in points:\n if a == b:\n continue\n\n k = a[0] - b[0]\n if k == 0:\n ...
1
Given an array of `points` where `points[i] = [xi, yi]` represents a point on the **X-Y** plane, return _the maximum number of points that lie on the same straight line_. **Example 1:** **Input:** points = \[\[1,1\],\[2,2\],\[3,3\]\] **Output:** 3 **Example 2:** **Input:** points = \[\[1,1\],\[3,2\],\[5,3\],\[4,1\]...
null
short solution
max-points-on-a-line
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
2
Given an array of `points` where `points[i] = [xi, yi]` represents a point on the **X-Y** plane, return _the maximum number of points that lie on the same straight line_. **Example 1:** **Input:** points = \[\[1,1\],\[2,2\],\[3,3\]\] **Output:** 3 **Example 2:** **Input:** points = \[\[1,1\],\[3,2\],\[5,3\],\[4,1\]...
null
O( n )✅ | Python (Step by step explanation)
evaluate-reverse-polish-notation
0
1
# Intuition\nThe problem requires evaluating arithmetic expressions in Reverse Polish Notation (RPN) format. In RPN, operators come after their operands, making it straightforward to perform calculations without the need for parentheses.\n\n# Approach\n1. Initialize an empty stack to store operands.\n2. Iterate through...
5
You are given an array of strings `tokens` that represents an arithmetic expression in a [Reverse Polish Notation](http://en.wikipedia.org/wiki/Reverse_Polish_notation). Evaluate the expression. Return _an integer that represents the value of the expression_. **Note** that: * The valid operators are `'+'`, `'-'`, ...
null
✅ Explained - Simple and Clear Python3 Code✅
evaluate-reverse-polish-notation
0
1
The provided solution evaluates arithmetic expressions in Reverse Polish Notation (RPN) using a stack. It iterates through the tokens of the expression, performing the corresponding arithmetic operations when encountering operators. The solution pops operands from the stack, applies the operations, and pushes the resul...
10
You are given an array of strings `tokens` that represents an arithmetic expression in a [Reverse Polish Notation](http://en.wikipedia.org/wiki/Reverse_Polish_notation). Evaluate the expression. Return _an integer that represents the value of the expression_. **Note** that: * The valid operators are `'+'`, `'-'`, ...
null
Python Solution
evaluate-reverse-polish-notation
0
1
<!-- # Intuition -->\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nSolving using stack data concept\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:$$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:$$O(...
2
You are given an array of strings `tokens` that represents an arithmetic expression in a [Reverse Polish Notation](http://en.wikipedia.org/wiki/Reverse_Polish_notation). Evaluate the expression. Return _an integer that represents the value of the expression_. **Note** that: * The valid operators are `'+'`, `'-'`, ...
null
The easiest solution using stack & lambdas
evaluate-reverse-polish-notation
0
1
# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def evalRPN(self, tokens: List[str]) -> int:\n operators = {\n \'+\': (lambda x, y: oper...
6
You are given an array of strings `tokens` that represents an arithmetic expression in a [Reverse Polish Notation](http://en.wikipedia.org/wiki/Reverse_Polish_notation). Evaluate the expression. Return _an integer that represents the value of the expression_. **Note** that: * The valid operators are `'+'`, `'-'`, ...
null
Easy Python3 Solution
evaluate-reverse-polish-notation
0
1
\n# Approach\n1. Push each token into the stack until an operator is reached.\n2. Pop the top 2 values when token = operator\n3. Evaluate the values based on the operator\n4. Push the operated value in the stack\n5. Continue this until the end of tokens\n\nNOTE: All the tokens should be an integer value\n\n\n# Code\n``...
1
You are given an array of strings `tokens` that represents an arithmetic expression in a [Reverse Polish Notation](http://en.wikipedia.org/wiki/Reverse_Polish_notation). Evaluate the expression. Return _an integer that represents the value of the expression_. **Note** that: * The valid operators are `'+'`, `'-'`, ...
null
Python | Stack and Lambda Solution
evaluate-reverse-polish-notation
0
1
\n# Code\n```\nclass Solution:\n def evalRPN(self, tokens: List[str]) -> int:\n\n stack = []\n signs = {\n \'+\': lambda x,y: x+y,\n \'-\': lambda x,y: x-y,\n \'*\': lambda x,y: x*y,\n \'/\': lambda x,y: x/y\n }\n\n\n for token in tokens:\n ...
1
You are given an array of strings `tokens` that represents an arithmetic expression in a [Reverse Polish Notation](http://en.wikipedia.org/wiki/Reverse_Polish_notation). Evaluate the expression. Return _an integer that represents the value of the expression_. **Note** that: * The valid operators are `'+'`, `'-'`, ...
null
Python 3 || 11 lines, w/ example || T/M: 95% / 97%
evaluate-reverse-polish-notation
0
1
```\nclass Solution:\n def evalRPN(self, tokens: list[str]) -> int: # Ex: tokens = ["4","13","5","/","+"]\n stack = []\n # t operation stack\n for t in tokens: # \u2013\...
19
You are given an array of strings `tokens` that represents an arithmetic expression in a [Reverse Polish Notation](http://en.wikipedia.org/wiki/Reverse_Polish_notation). Evaluate the expression. Return _an integer that represents the value of the expression_. **Note** that: * The valid operators are `'+'`, `'-'`, ...
null
150: Solution with step by step explanation
evaluate-reverse-polish-notation
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nThis solution uses a stack to keep track of operands as they are encountered in the input array. When an operator is encountered, the top two operands are popped off the stack, the operation is performed, and the result is p...
5
You are given an array of strings `tokens` that represents an arithmetic expression in a [Reverse Polish Notation](http://en.wikipedia.org/wiki/Reverse_Polish_notation). Evaluate the expression. Return _an integer that represents the value of the expression_. **Note** that: * The valid operators are `'+'`, `'-'`, ...
null
✅ Easy Solution w/ Explanation | [C++ , JAVA , Python] | No Runtime Error
evaluate-reverse-polish-notation
1
1
# \u2714\uFE0F Solution - I (Using Explicit Stack)\n<!-- Describe your approach to solving the problem. -->\nThe reverse polish is a mathematical notation in which operators follow their operands. So, we will get the operands first and then the operators.\n\n- We store all the operands in the order we receive it in.\n-...
14
You are given an array of strings `tokens` that represents an arithmetic expression in a [Reverse Polish Notation](http://en.wikipedia.org/wiki/Reverse_Polish_notation). Evaluate the expression. Return _an integer that represents the value of the expression_. **Note** that: * The valid operators are `'+'`, `'-'`, ...
null
Simple Stack imp | O(N)
evaluate-reverse-polish-notation
0
1
# Code\n```\nclass Solution:\n def evalRPN(self, tokens: List[str]) -> int:\n stack = []\n for i in tokens:\n if i in set([\'+\', \'-\', \'*\', \'/\']):\n a, b = stack.pop(), stack.pop()\n if i == \'+\':\n stack.append(a+b)\n el...
2
You are given an array of strings `tokens` that represents an arithmetic expression in a [Reverse Polish Notation](http://en.wikipedia.org/wiki/Reverse_Polish_notation). Evaluate the expression. Return _an integer that represents the value of the expression_. **Note** that: * The valid operators are `'+'`, `'-'`, ...
null
[Java / Python] Beat 91.65% Cleanest and easy understanding solution for beginners
evaluate-reverse-polish-notation
1
1
# Approach\n<!-- Describe your approach to solving the problem. -->\nStack \n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n``` Python []\nclass Solution:\n def evalRPN(self,...
3
You are given an array of strings `tokens` that represents an arithmetic expression in a [Reverse Polish Notation](http://en.wikipedia.org/wiki/Reverse_Polish_notation). Evaluate the expression. Return _an integer that represents the value of the expression_. **Note** that: * The valid operators are `'+'`, `'-'`, ...
null
Python Simple & easy to understand code
evaluate-reverse-polish-notation
0
1
\n```\nclass Solution:\n def evalRPN(self, tokens: List[str]) -> int:\n op = {\n \'+\' : lambda x, y : x + y,\n \'-\' : lambda x, y : x - y,\n \'*\' : lambda x, y : x * y,\n \'/\' : lambda x, y : int(x / y)\n }\n\n stack = []\n ...
10
You are given an array of strings `tokens` that represents an arithmetic expression in a [Reverse Polish Notation](http://en.wikipedia.org/wiki/Reverse_Polish_notation). Evaluate the expression. Return _an integer that represents the value of the expression_. **Note** that: * The valid operators are `'+'`, `'-'`, ...
null
Evaluate Reverse Polish Notation || Java || Python3 || Well Explained|| Stack
evaluate-reverse-polish-notation
1
1
# Evaluate Reverse Polish Notation.\n\n#### We can observe from the example that this problem requires stack operations.\n1. When it is operator(+,-,*,/) pop two element from stack and perform operation and store the result back into the stack.\n2. Otherwise push the element into the stack.\n**T.C. of O(N) for parsing ...
1
You are given an array of strings `tokens` that represents an arithmetic expression in a [Reverse Polish Notation](http://en.wikipedia.org/wiki/Reverse_Polish_notation). Evaluate the expression. Return _an integer that represents the value of the expression_. **Note** that: * The valid operators are `'+'`, `'-'`, ...
null
[python 3] one liner
reverse-words-in-a-string
0
1
\n# Code\n```\nclass Solution:\n def reverseWords(self, s: str) -> str:\n return (" ".join(s.split()[::-1]))\n```
2
Given an input string `s`, reverse the order of the **words**. A **word** is defined as a sequence of non-space characters. The **words** in `s` will be separated by at least one space. Return _a string of the words in reverse order concatenated by a single space._ **Note** that `s` may contain leading or trailing s...
null