question_slug
stringlengths
3
77
title
stringlengths
1
183
slug
stringlengths
12
45
summary
stringlengths
1
160
author
stringlengths
2
30
certification
stringclasses
2 values
created_at
stringdate
2013-10-25 17:32:12
2025-04-12 09:38:24
updated_at
stringdate
2013-10-25 17:32:12
2025-04-12 09:38:24
hit_count
int64
0
10.6M
has_video
bool
2 classes
content
stringlengths
4
576k
upvotes
int64
0
11.5k
downvotes
int64
0
358
tags
stringlengths
2
193
comments
int64
0
2.56k
reverse-linked-list
Rust 100%
rust-100-by-astroex-6d68
\nimpl Solution {\n pub fn reverse_list(head: Option<Box<ListNode>>) -> Option<Box<ListNode>> {\n let (mut prev, mut curr) = (None, head);\n wh
astroex
NORMAL
2021-09-21T20:42:30.430379+00:00
2021-09-21T20:55:24.980455+00:00
1,901
false
```\nimpl Solution {\n pub fn reverse_list(head: Option<Box<ListNode>>) -> Option<Box<ListNode>> {\n let (mut prev, mut curr) = (None, head);\n while let Some(mut node) = curr {\n curr = node.next;\n \n node.next = prev;\n \n prev = Some(node);\n }\n prev\n }\n}\n```
38
0
['Rust']
6
reverse-linked-list
O( n )✅ | Recursive approach✅ | Python (Step by step explanation)✅
o-n-recursive-approach-python-step-by-st-zsas
Intuition\nThe code aims to reverse a singly-linked list. It utilizes a recursive approach to achieve this.\n\n# Approach\nThe approach used in the code is a re
monster0Freason
NORMAL
2023-10-30T18:12:35.171832+00:00
2023-10-31T11:38:38.924464+00:00
2,263
false
# Intuition\nThe code aims to reverse a singly-linked list. It utilizes a recursive approach to achieve this.\n\n# Approach\nThe approach used in the code is a recursive algorithm for reversing a singly-linked list. The code defines a function `reverseList` that takes the head of the linked list as input. It proceeds as follows:\n1. Check if the input `head` is `None` (an empty list). If it is, return `None` since there\'s nothing to reverse.\n2. Create a variable `newHead` and initialize it with the current `head`.\n3. If the `head` has a `next` node, call the `reverseList` function recursively on the `next` node to reverse the sublist starting from the next node.\n4. After the recursive call returns, set `head.next.next` to the current `head`. This step effectively reverses the direction of the `next` pointer.\n5. Set `head.next` to `None` to make the original head the new tail.\n6. Return the `newHead` as the new head of the reversed linked list.\n\n# Visualization\nLet\'s visualize the reversal of the input list `1 -> 2 -> 3 -> 4 -> 5` step by step:\n\n1. **Input**: `1 -> 2 -> 3 -> 4 -> 5`\n\n2. **First call (head=1)**:\n - `head != NULL`, so it goes into the recursion.\n - Recursively calls `reverseList(2)`.\n\n3. **Second call (head=2)**:\n - `head != NULL`, so it goes into the recursion.\n - Recursively calls `reverseList(3)`.\n\n4. **Third call (head=3)**:\n - `head != NULL`, so it goes into the recursion.\n - Recursively calls `reverseList(4)`.\n\n5. **Fourth call (head=4)**:\n - `head != NULL`, so it goes into the recursion.\n - Recursively calls `reverseList(5)`.\n\n6. **Fifth call (head=5)**:\n - `head != NULL`, but there is no next node (head->next == NULL), so it returns 5 itself.\n\n7. **Back to the fourth call (head=4)**:\n - Now, `newHead` is 5.\n - `head->next->next` points to 4 (which is 5->4 now).\n - `head->next` is set to NULL (making 4->NULL).\n - `newHead` (which is 5) is returned to the third call.\n\n8. **Back to the third call (head=3)**:\n - Now, `newHead` is 5.\n - `head->next->next` points to 3 (which is 4->3->NULL now).\n - `head->next` is set to NULL (making 3->NULL).\n - `newHead` (which is 5) is returned to the second call.\n\n9. **Back to the second call (head=2)**:\n - Now, `newHead` is 5.\n - `head->next->next` points to 2 (which is 3->2->NULL now).\n - `head->next` is set to NULL (making 2->NULL).\n - `newHead` (which is 5) is returned to the first call.\n\n10. **Back to the first call (head=1)**:\n - Now, `newHead` is 5.\n - `head->next->next` points to 1 (which is 2->1->NULL now).\n - `head->next` is set to NULL (making 1->NULL).\n - `newHead` (which is 5) is returned as the new head of the reversed list.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g., O(n) -->\n\nThe time complexity of this code is O(n), where n is the number of nodes in the linked list. This is because the code processes each node once in a linear fashion.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g., O(n) -->\n\nThe space complexity of this code is O(n) due to the recursive call stack. In the worst case, there will be n recursive calls on the stack, each consuming space for function parameters and local variables.\n\n\n# Complexity\n- Time complexity: O(N), where N is the number of nodes in the linked list. This is because the code processes each node exactly once in a recursive manner.\n- Space complexity: O(N), as the space used by the recursive call stack can go up to the number of nodes in the linked list. The recursion depth is N in the worst case.\n\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 reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:\n \n if not head :\n return None\n\n newHead = head\n if head.next :\n newHead = self.reverseList(head.next)\n head.next.next = head\n head.next = None \n\n return newHead \n \n```\n\n# Please upvote the solution if you understood it.\n![1_3vhNKl1AW3wdbkTshO9ryQ.jpg](https://assets.leetcode.com/users/images/74b74c8c-0582-476a-a7fd-13b05654e8f9_1698689547.252958.jpeg)\n
37
0
['Linked List', 'Recursion', 'Python3']
2
reverse-linked-list
Very Easy and Fast Python Solution
very-easy-and-fast-python-solution-by-kh-7xxi
\nclass Solution:\n def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:\n prev=None\n while(head):\n nxt=head.nex
Khan_Baba
NORMAL
2022-10-17T18:06:26.969030+00:00
2022-10-19T13:55:55.262120+00:00
4,473
false
```\nclass Solution:\n def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:\n prev=None\n while(head):\n nxt=head.next\n head.next=prev\n prev=head\n head=nxt\n return prev\n \n```\n\n**Explanation**\nOne think to keep in mind, we are not going change the value of node, actually we are just reversing the link between the nodes. address of nodes will remain same; values will remain same only the connection between nodes get reversed.\n![image](https://assets.leetcode.com/users/images/3bce9aca-20e6-4bf3-ae4e-770c64a09771_1666187753.9647837.jpeg)\n
36
0
['Iterator']
5
reverse-linked-list
Very Very Easy C++ code
very-very-easy-c-code-by-thekalyan001-ynyz
Upvote if you liked it\n\n\nListNode* reverseList(ListNode* head) {\n ListNode *b=NULL,*c=NULL;\n \n while(head!=NULL)\n {\n
thekalyan001
NORMAL
2021-09-20T15:48:39.830558+00:00
2021-09-20T15:49:08.787600+00:00
2,878
false
Upvote if you liked it\n\n```\nListNode* reverseList(ListNode* head) {\n ListNode *b=NULL,*c=NULL;\n \n while(head!=NULL)\n {\n c=b;\n b=head;\n head=head->next;\n b->next=c;\n }\n return b;\n \n }\n```
36
2
['C']
3
reverse-linked-list
JavaScript solution (both iterative and recursive)
javascript-solution-both-iterative-and-r-m5m4
\n\n function reverseList(head) {\n var prev = null;\n while (head) {\n var next = head.next;\n head.next = prev;\n
linfongi
NORMAL
2016-05-04T03:30:16+00:00
2018-09-28T02:30:46.464718+00:00
5,089
false
\n\n function reverseList(head) {\n var prev = null;\n while (head) {\n var next = head.next;\n head.next = prev;\n prev = head;\n head = next;\n }\n return prev;\n }\n \n \n function reverseList(head) {\n if (!head || !head.next) {\n return head;\n }\n var newHead = reverseList(head.next);\n head.next.next = head;\n head.next = null;\n return newHead;\n }
34
1
[]
4
reverse-linked-list
8ms Golang solution
8ms-golang-solution-by-linfongi-rp3y
func reverseList(head *ListNode) *ListNode {\n \tvar prev *ListNode\n \tfor head != nil {\n \t\thead.Next, prev, head = prev, head, head.Next\n \t}\
linfongi
NORMAL
2016-03-28T05:17:46+00:00
2016-03-28T05:17:46+00:00
2,808
false
func reverseList(head *ListNode) *ListNode {\n \tvar prev *ListNode\n \tfor head != nil {\n \t\thead.Next, prev, head = prev, head, head.Next\n \t}\n \treturn prev\n }
32
0
['Go']
3
reverse-linked-list
🌟Best Solution Ever! 🚀 Python|| Java|| C++|| C|| JavaScript|| Go|| C#....... 💻🌟
best-solution-ever-python-java-c-javascr-upma
🌀 IntuitionReversing a linked list involves flipping the direction of the links between the nodes. Instead of having each node point to the next node, we revers
alantomanu
NORMAL
2025-01-06T17:39:04.691030+00:00
2025-01-11T12:32:05.551166+00:00
5,675
false
# 🌀 Intuition <!-- Describe your first thoughts on how to solve this problem. --> Reversing a linked list involves flipping the direction of the links between the nodes. Instead of having each node point to the next node, we reverse the pointers so that each node points to the previous node. --- # 🛠️ Approach <!-- Describe your approach to solving the problem. --> 1. Start with two pointers: - `prev` initialized to `None` (the new end of the reversed list). - `curr` initialized to `head` (the node currently being processed). 2. Traverse the list while: - Saving the next node (`next_node`). - Reversing the `next` pointer of the current node (`curr.next = prev`). - Advancing both `prev` and `curr` to the next nodes. 3. Once the traversal is complete, `prev` will point to the new head of the reversed list. --- # ⏱️ Complexity - **Time complexity:** $$O(n)$$ — We traverse each node once. - **Space complexity:** $$O(1)$$ — We reverse the list in place using constant extra space. --- ## 🌟 **Visual Explanation of the Algorithm** ### Problem: Reverse a Singly Linked List We want to transform: ``` 1 -> 2 -> 3 -> 4 -> 5 -> None ``` Into: ``` 5 -> 4 -> 3 -> 2 -> 1 -> None ``` --- ### **Initialization** We start with: - `prev = None` - `curr = head` (points to `1 -> 2 -> 3 -> 4 -> 5 -> None`). **Initial state:** ``` None <- 1 -> 2 -> 3 -> 4 -> 5 -> None ^ curr ``` --- ### **Step-by-Step Reversal** #### **Step 1: Process the first node** 1. Save `next_node = curr.next` (points to `2 -> 3 -> 4 -> 5 -> None`). 2. Reverse the link: `curr.next = prev` (`1 -> None`). 3. Move the pointers forward: - `prev = curr` (now points to `1 -> None`). - `curr = next_node` (now points to `2 -> 3 -> 4 -> 5 -> None`). **State after step 1:** ``` None <- 1 2 -> 3 -> 4 -> 5 -> None ^ ^ prev curr ``` --- #### **Step 2: Process the second node** 1. Save `next_node = curr.next` (points to `3 -> 4 -> 5 -> None`). 2. Reverse the link: `curr.next = prev` (`2 -> 1 -> None`). 3. Move the pointers forward: - `prev = curr` (now points to `2 -> 1 -> None`). - `curr = next_node` (now points to `3 -> 4 -> 5 -> None`). **State after step 2:** ``` None <- 1 <- 2 3 -> 4 -> 5 -> None ^ ^ prev curr ``` --- #### **Step 3: Process the third node** 1. Save `next_node = curr.next` (points to `4 -> 5 -> None`). 2. Reverse the link: `curr.next = prev` (`3 -> 2 -> 1 -> None`). 3. Move the pointers forward: - `prev = curr` (now points to `3 -> 2 -> 1 -> None`). - `curr = next_node` (now points to `4 -> 5 -> None`). **State after step 3:** ``` None <- 1 <- 2 <- 3 4 -> 5 -> None ^ ^ prev curr ``` --- #### **Step 4: Process the fourth node** 1. Save `next_node = curr.next` (points to `5 -> None`). 2. Reverse the link: `curr.next = prev` (`4 -> 3 -> 2 -> 1 -> None`). 3. Move the pointers forward: - `prev = curr` (now points to `4 -> 3 -> 2 -> 1 -> None`). - `curr = next_node` (now points to `5 -> None`). **State after step 4:** ``` None <- 1 <- 2 <- 3 <- 4 5 -> None ^ ^ prev curr ``` --- #### **Step 5: Process the fifth node** 1. Save `next_node = curr.next` (points to `None`). 2. Reverse the link: `curr.next = prev` (`5 -> 4 -> 3 -> 2 -> 1 -> None`). 3. Move the pointers forward: - `prev = curr` (now points to `5 -> 4 -> 3 -> 2 -> 1 -> None`). - `curr = next_node` (now points to `None`). **State after step 5:** ``` None <- 1 <- 2 <- 3 <- 4 <- 5 ^ prev curr=None ``` --- ### **Termination** When `curr` becomes `None`, the traversal ends. At this point: - `prev` points to the new head of the reversed list: ``` 5 -> 4 -> 3 -> 2 -> 1 -> None ``` Return `prev` as the new head of the reversed list. --- ## 🎯 **Final Illustration of Reversal** ### Before: ``` 1 -> 2 -> 3 -> 4 -> 5 -> None ``` ### After: ``` 5 -> 4 -> 3 -> 2 -> 1 -> None ``` --- ### Key Takeaways 1. The algorithm uses **three pointers** (`prev`, `curr`, `next_node`) to traverse and reverse the list. 2. Each node's `next` pointer is reversed in-place, resulting in an $$O(1)$$ space complexity. 3. The process stops when all nodes are traversed, and `prev` holds the new head. --- 💡 **Found this helpful?** Hit that **upvote** ⬆️ to fuel more amazing content! 🚀✨ # 🚀 Code ## Python 🐍 ```python # Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]: prev = None curr = head while curr is not None: next_node = curr.next # Save next node curr.next = prev # Reverse the pointer prev = curr # Move prev forward curr = next_node # Move curr forward return prev ``` 💡 Found this helpful? Hit that **upvote** ⬆️ to fuel more amazing content! 🚀✨ --- ## Java ☕ ```java class ListNode { int val; ListNode next; ListNode(int x) { val = x; } } class Solution { public ListNode reverseList(ListNode head) { ListNode prev = null; ListNode curr = head; while (curr != null) { ListNode nextNode = curr.next; // Save next node curr.next = prev; // Reverse the pointer prev = curr; // Move prev forward curr = nextNode; // Move curr forward } return prev; } } ``` 💡 Found this helpful? Hit that **upvote** ⬆️ to fuel more amazing content! 🚀✨ --- ## C++ 💻 ```cpp struct ListNode { int val; ListNode* next; ListNode(int x) : val(x), next(nullptr) {} }; class Solution { public: ListNode* reverseList(ListNode* head) { ListNode* prev = nullptr; ListNode* curr = head; while (curr != nullptr) { ListNode* nextNode = curr->next; // Save next node curr->next = prev; // Reverse the pointer prev = curr; // Move prev forward curr = nextNode; // Move curr forward } return prev; } }; ``` 💡 Found this helpful? Hit that **upvote** ⬆️ to fuel more amazing content! 🚀✨ --- ## JavaScript 🖥️ ```javascript class ListNode { constructor(val = 0, next = null) { this.val = val; this.next = next; } } var reverseList = function(head) { let prev = null; let curr = head; while (curr !== null) { let nextNode = curr.next; // Save next node curr.next = prev; // Reverse the pointer prev = curr; // Move prev forward curr = nextNode; // Move curr forward } return prev; }; ``` 💡 Found this helpful? Hit that **upvote** ⬆️ to fuel more amazing content! 🚀✨ --- ## Go 🦫 ```go type ListNode struct { Val int Next *ListNode } func reverseList(head *ListNode) *ListNode { var prev *ListNode curr := head for curr != nil { nextNode := curr.Next // Save next node curr.Next = prev // Reverse the pointer prev = curr // Move prev forward curr = nextNode // Move curr forward } return prev } ``` 💡 Found this helpful? Hit that **upvote** ⬆️ to fuel more amazing content! 🚀✨ --- ## C 🌟 ```c #include <stdlib.h> struct ListNode { int val; struct ListNode* next; }; struct ListNode* reverseList(struct ListNode* head) { struct ListNode* prev = NULL; struct ListNode* curr = head; while (curr != NULL) { struct ListNode* nextNode = curr->next; // Save next node curr->next = prev; // Reverse the pointer prev = curr; // Move prev forward curr = nextNode; // Move curr forward } return prev; } ``` 💡 Found this helpful? Hit that **upvote** ⬆️ to fuel more amazing content! 🚀✨ --- ## C# 💻 ```csharp public class ListNode { public int val; public ListNode next; public ListNode(int x) { val = x; } } public class Solution { public ListNode ReverseList(ListNode head) { ListNode prev = null; ListNode curr = head; while (curr != null) { ListNode nextNode = curr.next; // Save next node curr.next = prev; // Reverse the pointer prev = curr; // Move prev forward curr = nextNode; // Move curr forward } return prev; } } ``` 💡 Found this helpful? Hit that **upvote** ⬆️ to fuel more amazing content! 🚀✨ --- ## Kotlin 🚀 ```kotlin class ListNode(var `val`: Int) { @JvmField // This annotation exposes the field directly without getter/setter var next: ListNode? = null } class Solution { fun reverseList(head: ListNode?): ListNode? { var prev: ListNode? = null var curr: ListNode? = head while (curr != null) { val nextNode = curr.next curr.next = prev prev = curr curr = nextNode } return prev } } ``` 💡 Found this helpful? Hit that **upvote** ⬆️ to fuel more amazing content! 🚀✨ --- ## TypeScript 🌐 ```typescript class ListNode { val: number; next: ListNode | null; constructor(val?: number, next?: ListNode | null) { this.val = val ?? 0; this.next = next ?? null; } } function reverseList(head: ListNode | null): ListNode | null { let prev: ListNode | null = null; let curr: ListNode | null = head; while (curr !== null) { const nextNode = curr.next; // Save next node curr.next = prev; // Reverse the pointer prev = curr; // Move prev forward curr = nextNode; // Move curr forward } return prev; } ``` 💡 Found this helpful? Hit that **upvote** ⬆️ to fuel more amazing content! 🚀✨ --- ## Swift 🍎 ```swift class ListNode { var val: Int var next: ListNode? init(_ val: Int, _ next: ListNode? = nil) { self.val = val self.next = next } } class Solution { func reverseList(_ head: ListNode?) -> ListNode? { var prev: ListNode? = nil var curr = head while curr != nil { let nextNode = curr?.next // Save next node curr?.next = prev // Reverse the pointer prev = curr // Move prev forward curr = nextNode // Move curr forward } return prev } } ``` --- 💡 Found this helpful? Hit that **upvote** ⬆️ to fuel more amazing content! 🚀✨ --- # 🌈 Visual Explanation ### Input: ``` 1 -> 2 -> 3 -> 4 -> None ``` ### Step-by-Step Reversal: 1. **Initial State:** - `prev = None` - `curr = 1 -> 2 -> 3 -> 4 -> None` 2. **Iteration 1:** - Save `next_node = 2 -> 3 -> 4 -> None` - Reverse: `1 -> None` - Move pointers: `prev = 1`, `curr = 2 -> 3 -> 4 -> None` 3. **Iteration 2:** - Save `next_node = 3 -> 4 -> None` - Reverse: `2 -> 1 -> None` - Move pointers: `prev = 2`, `curr = 3 -> 4 -> None` 4. **Iteration 3:** - Save `next_node = 4 -> None` - Reverse: `3 -> 2 -> 1 -> None` - Move pointers: `prev = 3`, `curr = 4 -> None` 5. **Iteration 4:** - Save `next_node = None` - Reverse: `4 -> 3 -> 2 -> 1 -> None` - Move pointers: `prev = 4`, `curr = None` ### Output: ``` 4 -> 3 -> 2 -> 1 -> None ``` Now, `prev` points to the new head of the reversed list. 🎉 To make the explanation of the algorithm perfectly visible and easy to understand, I'll break it down into **visual diagrams** that mimic the process step-by-step. 💡 Found this helpful? Hit that **upvote** ⬆️ to fuel more amazing content! 🚀✨ ### Key Takeaways 1. The algorithm uses **three pointers** (`prev`, `curr`, `next_node`) to traverse and reverse the list. 2. Each node's `next` pointer is reversed in-place, resulting in an $$O(1)$$ space complexity. 3. The process stops when all nodes are traversed, and `prev` holds the new head. 💡 Found this helpful? Hit that **upvote** ⬆️ to fuel more amazing content! 🚀✨
31
0
['Linked List', 'Swift', 'C++', 'Java', 'Go', 'TypeScript', 'Python3', 'Kotlin', 'JavaScript']
8
reverse-linked-list
Python iterative and recursive solution, both O(n) time complexity.
python-iterative-and-recursive-solution-mqhtx
# Iteratively\n def reverseList1(self, head):\n node = None\n while head:\n tmp = head.next\n head.next = node\n
oldcodingfarmer
NORMAL
2015-07-15T13:34:12+00:00
2015-07-15T13:34:12+00:00
7,041
false
# Iteratively\n def reverseList1(self, head):\n node = None\n while head:\n tmp = head.next\n head.next = node\n node = head\n head = tmp\n return node\n \n # Recursively \n def reverseList(self, head):\n return self.helper(head, None)\n \n def helper(self, head, node):\n if not head:\n return node\n tmp = head.next\n head.next = node\n return self.helper(tmp, head)
31
0
['Recursion', 'Iterator', 'Python']
2
reverse-linked-list
Reverse Linked List || Easy recursive solution with image explanation
reverse-linked-list-easy-recursive-solut-y5nk
Easy C++ solution--->\n Let us take an example->\n \n \n\n1) reverseByRecursion(node1) is called.\n2) Neither node1 nor node1->next is NULL, so newHead = revers
rawat_abhi33
NORMAL
2022-06-03T07:06:59.079965+00:00
2022-06-03T07:08:14.152878+00:00
2,283
false
Easy C++ solution--->\n Let us take an example->\n \n ![image](https://assets.leetcode.com/users/images/96b7d4a6-64b6-4a11-922e-55c148b558a7_1654239510.008161.png)\n\n1) reverseByRecursion(node1) is called.\n2) Neither node1 nor node1->next is NULL, so newHead = reverseList(head2); is called.\n3) Neither node2 nor node2->next is NULL, so newHead = reverseList(head3); is called.\n4) head3->next is NULL, so head3 is returned from reverseList(head3).\n5) head = node2 and head->next = node3, so head->next->next = head; will set node3->next to node2.\n6) head->next = NULL; will set node2->next to NULL. (image 2)\n7) newHead, which is node3, is returned from reverseList(head2).\n8) head = node1 and head->next = node2, so head->next->next = head; will set node2->next to node1.\n9) head->next = NULL; will set node1->next to NULL. (image 3)\n10) newHead, which is node3, is returned from reverseList(node1).\n11) Now the list is reversed with having node3 as the head.\n \n\t **image 2**\n \n ![image](https://assets.leetcode.com/users/images/2e6f2ddf-4f5e-4892-bdc0-99d27289ff9d_1654239786.5388136.png)\n\n **image 3**\n\n![image](https://assets.leetcode.com/users/images/9791019b-b072-42e3-ac2a-622cef5e9aa2_1654239949.2522185.png)\n\nimplimentation--->\n\n```\n ListNode* reverseList(ListNode* head) {\n \n if (head == NULL || head->next == NULL) return head;\n \n ListNode* newHead = reverseList(head->next);\n \n head->next->next = head;\n head->next = NULL;\n \n return newHead ;\n }\n\t\n\t```
30
0
['Linked List', 'Recursion', 'C', 'C++']
7
reverse-linked-list
Fast Recursive Java solution
fast-recursive-java-solution-by-second_x-l94w
public class Solution {\n public ListNode reverseList(ListNode head) {\n if(head == null ||head.next == null){\n return head;\n
second_xia
NORMAL
2015-10-14T07:34:33+00:00
2015-10-14T07:34:33+00:00
7,693
false
public class Solution {\n public ListNode reverseList(ListNode head) {\n if(head == null ||head.next == null){\n return head;\n }\n \n ListNode root = reverseList(head.next);\n \n head.next.next = head;\n head.next = null;\n return root;\n }\n }
30
0
[]
2
reverse-linked-list
Easy Solution | | Optimal Solution | | C++ | | Java | | Python3 | | Kotlin | | ✅✅✅🔥🔥
easy-solution-optimal-solution-c-java-py-b04c
\n\n## Intuition\nTo reverse a singly linked list, we can iterate through the list while maintaining pointers to the previous, current, and next nodes. During e
Hunter_0718
NORMAL
2024-03-21T00:05:53.805121+00:00
2024-03-21T00:15:00.328850+00:00
9,180
false
\n![image.png](https://assets.leetcode.com/users/images/4a07c315-3f02-439e-84dd-8eb0690e0fbd_1710979909.9290335.png)\n## Intuition\nTo reverse a singly linked list, we can iterate through the list while maintaining pointers to the previous, current, and next nodes. During each iteration, we update the `next` pointer of the current node to point to the previous node. After updating pointers, we move forward in the list until we reach the end, effectively reversing the list.\n\n## Approach\n1. Initialize three pointers: `prev`, `curr`, and `nextNode`.\n2. Iterate through the linked list.\n3. Inside the loop, update `nextNode` to store the next node of `curr`.\n4. Update the `next` pointer of `curr` to point to `prev`.\n5. Move `prev` to `curr`, and `curr` to `nextNode`.\n6. Continue iterating until `curr` becomes `NULL`.\n7. Return `prev`, which is the new head of the reversed list.\n\n## Complexity\n- **Time complexity:** \\( O(n) \\), where \\( n \\) is the number of nodes in the linked list. We traverse the entire list once.\n- **Space complexity:** \\( O(1) \\). We are using constant space for pointers `prev`, `curr`, and `nextNode`.\n\n\n# Code : \n```C++ []\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode() : val(0), next(nullptr) {}\n * ListNode(int x) : val(x), next(nullptr) {}\n * ListNode(int x, ListNode *next) : val(x), next(next) {}\n * };\n */\nclass Solution {\npublic:\n ListNode* reverseList(ListNode* head) {\n ListNode *prev = NULL;\n ListNode *curr = head;\n ListNode *nextNode = NULL;\n while(curr != NULL){\n nextNode = curr->next;\n curr->next = prev;\n prev = curr;\n curr = nextNode;\n }\n return prev;\n }\n};\n```\n```Java []\n/*class ListNode {\n int val;\n ListNode next;\n ListNode() {}\n ListNode(int val) { this.val = val; }\n ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n}*/\n\nclass Solution {\n public ListNode reverseList(ListNode head) {\n ListNode prev = null;\n ListNode curr = head;\n ListNode nextNode = null;\n while (curr != null) {\n nextNode = curr.next;\n curr.next = prev;\n prev = curr;\n curr = nextNode;\n }\n return prev;\n }\n}\n\n\n```\n```Python3 []\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 reverseList(self, head: ListNode) -> ListNode:\n prev = None\n curr = head\n nextNode = None\n while curr:\n nextNode = curr.next\n curr.next = prev\n prev = curr\n curr = nextNode\n return prev\n\n```\n```Kotlin []\n/**\n * Example:\n * var li = ListNode(5)\n * var v = li.`val`\n * Definition for singly-linked list.\n * class ListNode(var `val`: Int) {\n * var next: ListNode? = null\n * }\n */\nclass Solution {\n fun reverseList(head: ListNode?): ListNode? {\n var prev: ListNode? = null\n var curr: ListNode? = head\n var nextNode: ListNode? = null\n while (curr != null) {\n nextNode = curr.next\n curr.next = prev\n prev = curr\n curr = nextNode\n }\n return prev\n }\n}\n\n```\n```JavaScript []\n/**\n * Definition for singly-linked list.\n * function ListNode(val) {\n * this.val = val;\n * this.next = null;\n * }\n */\n\n/**\n * @param {ListNode} head\n * @return {ListNode}\n */\nvar reverseList = function(head) {\n let prev = null;\n let curr = head;\n let nextNode = null;\n while (curr !== null) {\n nextNode = curr.next;\n curr.next = prev;\n prev = curr;\n curr = nextNode;\n }\n return prev;\n};\n\n```\n\n\n\n## Dry Run\nLet\'s dry run the first example: `Input: head = [1,2,3,4,5]`\n\n1. Initially: `prev = NULL`, `curr = head`, `nextNode = NULL`.\n2. Loop 1:\n - `nextNode = 2`, `curr->next = NULL`, `prev = 1`, `curr = 2`.\n3. Loop 2:\n - `nextNode = 3`, `curr->next = 1`, `prev = 2`, `curr = 3`.\n4. Loop 3:\n - `nextNode = 4`, `curr->next = 2`, `prev = 3`, `curr = 4`.\n5. Loop 4:\n - `nextNode = 5`, `curr->next = 3`, `prev = 4`, `curr = 5`.\n6. Loop 5:\n - `nextNode = NULL`, `curr->next = 4`, `prev = 5`, `curr = NULL`.\n7. Return `prev` as the new head: `[5,4,3,2,1]`.\n\nThe linked list has been successfully reversed.
29
0
['Linked List', 'C++', 'Java', 'Python3', 'Kotlin', 'JavaScript']
4
reverse-linked-list
C++ / Python simple iterative solution
c-python-simple-iterative-solution-by-to-dm82
C++ :\n\n\nListNode* reverseList(ListNode* head) {\n\tListNode *nextNode, *prevNode = NULL;\n\twhile (head) {\n\t\tnextNode = head->next;\n\t\thead->next = prev
TovAm
NORMAL
2021-10-10T11:04:57.419141+00:00
2021-10-10T11:04:57.419174+00:00
4,067
false
**C++ :**\n\n```\nListNode* reverseList(ListNode* head) {\n\tListNode *nextNode, *prevNode = NULL;\n\twhile (head) {\n\t\tnextNode = head->next;\n\t\thead->next = prevNode;\n\t\tprevNode = head;\n\t\thead = nextNode;\n\t}\n\treturn prevNode;\n}\n```\n\n**Python :**\n\n```\ndef reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:\n\tprev = None\n\n\twhile head:\n\t\tnext_node = head.next\n\t\thead.next = prev\n\t\tprev = head\n\t\thead = next_node\n\n\treturn prev\n```\n\n**Like it ? please upvote !**
28
0
['C', 'Python', 'C++', 'Python3']
4
reverse-linked-list
0ms 100% Faster 100% less memory
0ms-100-faster-100-less-memory-by-sreeje-muf4
Iterative solution\nLanguage: Go\nSpeed: 0ms\nMemory: 2.5 MB\n\nfunc reverseList(head *ListNode) (prev *ListNode) {\n\tfor head != nil {\n\t\thead.Next, prev, h
sreejeet
NORMAL
2020-05-22T17:56:59.057360+00:00
2020-05-22T17:56:59.057414+00:00
1,780
false
Iterative solution\nLanguage: Go\nSpeed: 0ms\nMemory: 2.5 MB\n```\nfunc reverseList(head *ListNode) (prev *ListNode) {\n\tfor head != nil {\n\t\thead.Next, prev, head = prev, head, head.Next\n\t}\n\treturn\n}\n\n```
28
0
['Go']
2
reverse-linked-list
Iteratively and recursively Java Solution
iteratively-and-recursively-java-solutio-rd92
\tpublic class Solution {\n\t public ListNode reverseList(ListNode head) {\n\t \tif(head == null) return head;\n\t \t\n\t \tListNode next = head.nex
syftalent
NORMAL
2015-05-29T04:22:19+00:00
2015-05-29T04:22:19+00:00
9,265
false
\tpublic class Solution {\n\t public ListNode reverseList(ListNode head) {\n\t \tif(head == null) return head;\n\t \t\n\t \tListNode next = head.next;\n\t \thead.next = null;\n\t \n\t \twhile(next != null){\n\t \tListNode temp = next.next;\n\t \tnext.next = head;\n\t \thead = next;\n\t \tnext = temp;\n\t }\n\t \treturn head;\n\t }\n\t}\n\n\n\tpublic class Solution {\n\t public ListNode reverseList(ListNode head) {\n\t \tif(head == null) return head;\n\t \tListNode next = head.next;\n\t \thead.next = null;\n\t \t\n\t \treturn recursive(head,next);\n\t }\n\t \n\t private ListNode recursive(ListNode head, ListNode next){\n\t \tif(next == null)\treturn head;\n\t \tListNode temp = next.next;\n\t \tnext.next = head;\n\t \treturn recursive(next,temp);\n\t \t\n\t }\n\t}
28
0
['Java']
2
reverse-linked-list
C# Shortest & Fastest Iterative Solution. Time: O(n)❤
c-shortest-fastest-iterative-solution-ti-577a
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# Co
Din_Srg
NORMAL
2023-01-24T05:52:13.337882+00:00
2023-06-19T05:57:27.445683+00:00
3,562
false
# 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```\npublic ListNode ReverseList(ListNode head)\n{\n ListNode resultNode = null;\n while(head != null)\n {\n resultNode = new ListNode(head.val, resultNode);\n head = head.next;\n }\n return resultNode;\n}\n```\n\nOr even **shorter** :\n\n```\npublic ListNode ReverseList(ListNode h)\n{\n ListNode r = null;\n while(h != null) (r, h) = (new(h.val, r), h.next);\n return r;\n}\n```\n
27
0
['Linked List', 'C#']
6
reverse-linked-list
The simplest way on javascript
the-simplest-way-on-javascript-by-kathan-2a8z
var reverseList = function(head){\n \n var tmp = null;\n var newHead = null;\n while(head !== null){\n tmp = head;\n head = he
kathandra
NORMAL
2015-05-28T23:45:11+00:00
2018-10-25T22:16:06.607267+00:00
5,479
false
var reverseList = function(head){\n \n var tmp = null;\n var newHead = null;\n while(head !== null){\n tmp = head;\n head = head.next;\n tmp.next = newHead;\n newHead = tmp;\n }\n \n return newHead;\n }
26
0
['JavaScript']
5
reverse-linked-list
Java iterative 0ms solution with explanation
java-iterative-0ms-solution-with-explana-es34
This seems to be a classic question that I have received multiple times in real interviews. Typically, it is asked as a phone screen or initial screening quest
bdwalker
NORMAL
2016-02-12T20:50:53+00:00
2016-02-12T20:50:53+00:00
9,805
false
This seems to be a classic question that I have received multiple times in real interviews. Typically, it is asked as a phone screen or initial screening questions. Regardless, it can seem a bit tricky but it really doesn't take a whole lot of code to accomplish this. \n\nMy solution is as follows:\n\n public ListNode reverseList(ListNode head) {\n // is there something to reverse?\n if (head != null && head.next != null)\n {\n ListNode pivot = head;\n ListNode frontier = null;\n while (pivot != null && pivot.next != null)\n {\n frontier = pivot.next;\n pivot.next = pivot.next.next;\n frontier.next = head;\n head = frontier;\n }\n }\n \n return head;\n } \n\nThis is a very quick, O(n) reversal that times at 0ms in Leetcode OJ. The trick is to think of the first element as the new last item in the list. After reversing, this must be true. Then, we just move the element that pivot .next points to (the initial head of the list) and we move it to become the new head. This essentially grows the list backwards until the initial pivot no longer has anything to move. \n\nFor example; if we have a list [1, 2, 3, 4], the algorithm will do the following:\n- Set pivot to 1, set frontier to 2, keep head at 1\n- We see that pivot still has items after it, so set pivots .next to .next.next, and move the pivot to be set to the current head\n- Now move the head back to point to the new head, which is the frontier node we just set\n- Now reset frontier to pivots .next and repeat. \n\nSo with each iteration of the loop the list becomes:\n- [1, 2, 3, 4]\n- [2, 1, 3, 4]\n- [3, 2, 1, 4]\n- [4, 3, 2, 1]\n\nThen we return the new final head which points to 4.
26
2
[]
4
reverse-linked-list
very easy to understand in python
very-easy-to-understand-in-python-by-raj-ytfa
\n\n \n\nref :: https://learnersbucket.com/examples/algorithms/learn-how-to-reverse-a-linked-list/ \n\n\n# Definition for singly-linked list.\n# class ListNode
rajitkumarchauhan99
NORMAL
2022-08-18T17:10:26.633345+00:00
2022-08-23T14:34:37.068531+00:00
3,569
false
\n![image](https://assets.leetcode.com/users/images/2b86378e-05fd-4bff-a789-2e0b9224feaa_1661265253.8641996.png)\n \n\nref :: https://learnersbucket.com/examples/algorithms/learn-how-to-reverse-a-linked-list/ \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\nclass Solution:\n def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:\n curr = head\n pre = None\n nxt = None\n while(curr):\n nxt = curr.next # hold the next address of curr\n curr.next = pre # connect current to pre " <- " (reverse node)\n pre = curr # move previous\n curr = nxt # move curr \n \n return pre\n \n```\nplease upvote if you like
25
0
['Python', 'Python3']
5
reverse-linked-list
[Python] 2 pointers solution, explained
python-2-pointers-solution-explained-by-3e11x
The idea is to keep 2 pointers for current and next node and then iterate through nodes and reconnect nodes. The best way to understand this solution is to take
dbabichev
NORMAL
2021-09-07T07:20:42.681156+00:00
2021-09-07T07:20:42.681201+00:00
812
false
The idea is to keep `2` pointers for current and next node and then iterate through nodes and reconnect nodes. The best way to understand this solution is to take some small list, for example `1 -> 2 -> 3 -> 4 -> None` and see what is going on on the each step.\n\n1. In the beginning `curr = None, nxt = 1`.\n2. On the first step we have: `tmp = 2`, `nxt.next = None`, `curr = 1`, `nxt = 2`. So what we have is the following: `None <- 1 2 -> 3 -> 4 -> None`. That is we cut one link between `1` and `2` and create new link `1 -> None`.\n3. On the next step we have `None <- 1 <- 2 3 -> 4 -> None` and so on.\n\nTry to draw it on the paper, step by step, it is the best way to feel it.\n\n#### Complexity\nTime complexity is `O(n)`, space is `O(1)`.\n\n#### Code\n```python\nclass Solution:\n def reverseList(self, head):\n curr = None\n nxt = head\n while nxt:\n tmp = nxt.next\n nxt.next = curr\n curr = nxt\n nxt = tmp\n \n return curr\n```
24
3
['Linked List', 'Two Pointers']
0
reverse-linked-list
Python Recursion [Highly Commented] (>99%)
python-recursion-highly-commented-99-by-vcvzm
Standard recursive approach. Traverse to end of linked list with recursive calls. Now orig_head is end node, and head is the node before that. Then swap nodes a
stephenlalor
NORMAL
2020-05-02T21:05:33.859186+00:00
2020-05-02T21:05:33.859235+00:00
3,032
false
Standard recursive approach. Traverse to end of linked list with recursive calls. Now ```orig_head``` is end node, and head is the node before that. Then swap nodes at each step and finally return the ```orig_head``` as the ```head``` of the reversed linked list.\n``` \nclass Solution:\n def reverseList(self, head: ListNode) -> ListNode:\n if not head: return head #Empty.\n if not head.next: return head #We reached end.\n orig_head = self.reverseList(head.next) #Traverse to end, orig_head is now end node.\n head.next.next = head #Swap head with right node.\n head.next = None #So we don\'t wind up in infinite loop.\n return orig_head #Very last thing returned. End node!\n```\n
24
2
['Recursion', 'Python']
1
reverse-linked-list
My 0ms 10 line java solution
my-0ms-10-line-java-solution-by-peter73-i6hv
public ListNode reverseList(ListNode head) {\n ListNode curr = null;\n ListNode temp = head;\n ListNode prev = null;\n while(temp !=
peter73
NORMAL
2016-01-04T21:07:08+00:00
2016-01-04T21:07:08+00:00
4,204
false
public ListNode reverseList(ListNode head) {\n ListNode curr = null;\n ListNode temp = head;\n ListNode prev = null;\n while(temp != null){\n prev = curr;\n curr = temp;\n temp = curr.next;\n curr.next = prev;\n }\n return curr; \n }
24
0
['Java']
1
reverse-linked-list
✅ 🔥 0 ms Runtime Beats 100% User confirm 🔥|| Step By Steps Solution ✅ || Beginner Friendly ✅ |
0-ms-runtime-beats-100-user-confirm-step-xjaa
\u2705 IF YOU LIKE THIS SOLUTION, PLEASE UPVOTE AT THE END \u2705 :\n\n### Problem Intuition :\nReversing a singly linked list means rearranging the next point
Letssoumen
NORMAL
2024-11-19T02:42:57.880177+00:00
2024-11-19T02:42:57.880199+00:00
2,856
false
\u2705 IF YOU LIKE THIS SOLUTION, PLEASE UPVOTE AT THE END \u2705 :\n\n### Problem Intuition :\nReversing a singly linked list means rearranging the `next` pointers of each node to point to the previous node instead of the next. This operation should be done **in-place** to optimize space usage.\n\n---\n\n### Optimal Approach :\n1. Traverse the list with three pointers:\n - **`prev`** to store the previous node (initially `null`).\n - **`current`** to process the current node.\n - **`next`** to temporarily hold the next node before reversing the link.\n2. Reverse the `next` pointer of each node as you traverse.\n3. Update `prev` to `current` and `current` to `next`.\n4. When `current` becomes `null`, `prev` will be the new head of the reversed list.\n\n---\n\n### Complexity :\n- **Time Complexity**: \\(O(n)\\), where \\(n\\) is the number of nodes in the list. Each node is visited once.\n- **Space Complexity**: \\(O(1)\\), as no additional data structures are used.\n\n---\n\n### Implementation in C++ :\n```cpp\nclass Solution {\npublic:\n ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr;\n ListNode* current = head;\n while (current != nullptr) {\n ListNode* next = current->next;\n current->next = prev;\n prev = current;\n current = next;\n }\n return prev;\n }\n};\n```\n\n---\n\n### Implementation in Java :\n```java\nclass Solution {\n public ListNode reverseList(ListNode head) {\n ListNode prev = null;\n ListNode current = head;\n while (current != null) {\n ListNode next = current.next;\n current.next = prev;\n prev = current;\n current = next;\n }\n return prev;\n }\n}\n```\n\n---\n\n### Implementation in Python :\n```python\nclass Solution:\n def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:\n prev = None\n current = head\n while current:\n next_node = current.next\n current.next = prev\n prev = current\n current = next_node\n return prev\n```\n\n---\n\n### Solving Steps :\n1. **Initialize**:\n - `prev = None` and `current = head`.\n2. **Iterate**:\n - Save the next node (`next = current.next`).\n - Reverse the pointer (`current.next = prev`).\n - Move forward (`prev = current`, `current = next`).\n3. **Return**:\n - The `prev` pointer will point to the new head of the reversed list.\n\n---\n\n### Example Walkthrough For You :\n#### Input: `head = [1, 2, 3, 4, 5]`\n1. Initial:\n ```\n prev = None, current = 1 -> 2 -> 3 -> 4 -> 5\n ```\n2. After processing `1`:\n ```\n prev = 1 -> None, current = 2 -> 3 -> 4 -> 5\n ```\n3. After processing `2`:\n ```\n prev = 2 -> 1 -> None, current = 3 -> 4 -> 5\n ```\n4. After processing `3`:\n ```\n prev = 3 -> 2 -> 1 -> None, current = 4 -> 5\n ```\n5. After processing `4`:\n ```\n prev = 4 -> 3 -> 2 -> 1 -> None, current = 5\n ```\n6. After processing `5`:\n ```\n prev = 5 -> 4 -> 3 -> 2 -> 1 -> None, current = None\n ```\n7. Return `prev`.\n\n#### Output: `[5, 4, 3, 2, 1]`\n\n![image.png](https://assets.leetcode.com/users/images/c7c9b83f-d22d-4318-9a35-d388b0a292d7_1731984149.5017643.png)\n
23
0
['Linked List', 'Recursion', 'C++', 'Java', 'Python3']
2
reverse-linked-list
✅Simple recursive C# solution | O(n) time | O(n) space✅
simple-recursive-c-solution-on-time-on-s-ejtc
This solution uses a recursive function to reverse a singly linked list. It starts at the head of the list and follows the next links until it reaches the end o
shukhratutaboev
NORMAL
2022-12-28T07:05:46.166726+00:00
2023-02-04T11:36:09.375097+00:00
3,355
false
This solution uses a recursive function to reverse a singly linked list. It starts at the head of the list and follows the next links until it reaches the end of the list. Then it reverses the next links back to the head of the list, building the reversed list as it goes. When it reaches the head of the original list again, it returns the head of the reversed list as the result.\n\n# Approach\nRecursion\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, e.g. $$O(n)$$ -->\n\n# Code\n```\npublic class Solution\n{\n private ListNode _reversedHead;\n\n public ListNode ReverseList(ListNode head)\n {\n if (head == null) return head;\n var last = RecursionReverse(head);\n last.next = null;\n\n return _reversedHead;\n }\n\n public ListNode RecursionReverse(ListNode node)\n {\n if (node.next == null)\n {\n _reversedHead = node;\n return node;\n }\n var next = RecursionReverse(node.next);\n next.next = node;\n return node;\n\n }\n}\n```\n\nIf you found my solution helpful, please consider upvoting it to let others know!
23
0
['Linked List', 'Recursion', 'C#']
2
reverse-linked-list
javascript
javascript-by-yinchuhui88-lguy
\nvar reverseList = function(head) {\n let pre = null\n while(head){\n const next = head.next\n head.next = pre\n pre = head\n
yinchuhui88
NORMAL
2018-12-29T07:14:56.408393+00:00
2018-12-29T07:14:56.408490+00:00
5,485
false
```\nvar reverseList = function(head) {\n let pre = null\n while(head){\n const next = head.next\n head.next = pre\n pre = head\n head = next\n }\n return pre\n};\n```
22
0
[]
6
reverse-linked-list
Simplest solution | C# | +98.8% efficient
simplest-solution-c-988-efficient-by-bay-6tr0
Intuition & Approach\n Describe your first thoughts on how to solve this problem. \nUsing 3 pointers - current, previous and next, we\'ll simply re-link the nod
Baymax_
NORMAL
2023-06-06T07:09:10.302296+00:00
2023-06-06T07:09:10.302337+00:00
2,168
false
# Intuition & Approach\n<!-- Describe your first thoughts on how to solve this problem. -->\nUsing 3 pointers - current, previous and next, we\'ll simply re-link the nodes to reverse the linked list.\n\n![Screenshot 2023-06-06 123439.png](https://assets.leetcode.com/users/images/db1a361b-aaab-415d-86ca-ca8867101592_1686035183.343104.png)\n\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(N) - as we loop over the linked list once\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1) - as we use constant memory\n\n## Please upvote if you like the approach\n---\n# Code\n```\n/**\n * Definition for singly-linked list.\n * public class ListNode {\n * public int val;\n * public ListNode next;\n * public ListNode(int val=0, ListNode next=null) {\n * this.val = val;\n * this.next = next;\n * }\n * }\n */\npublic class Solution {\n public ListNode ReverseList(ListNode head) {\n ListNode cur = head;\n ListNode prev = null;\n ListNode nxt = null;\n while (cur != null)\n {\n nxt = cur.next;\n cur.next = prev;\n prev = cur;\n cur = nxt;\n }\n\n return prev;\n }\n}\n```\n\n## Please upvote if you like the approach\n![Upvote please - do this.jpg](https://assets.leetcode.com/users/images/57266132-a386-48fe-822c-723578e29db1_1686035344.5539904.jpeg)\n\n
21
0
['Linked List', 'C#']
0
reverse-linked-list
Θ(n),Θ(1) Recursive & Iterative Solutions Explained
thnth1-recursive-iterative-solutions-exp-c9st
There are multiple possible approaches to solving this problem. In this post, I have outlined 4 approaches that are either the most performant or most mathemati
mxweaver
NORMAL
2023-04-30T10:55:45.253521+00:00
2023-05-12T20:04:17.126960+00:00
2,472
false
There are multiple possible approaches to solving this problem. In this post, I have outlined 4 approaches that are either the most performant or most mathematically interesting.\n\n# Impure Recursive\n\nTo reverse the list with recursion:\n\n- Add an optional parameter to keep track of the parent node\n- If the current node is empty, bail\n- Keep a reference to the next node\n- Flip the direction of the current node\'s edge\n- If there is a next node, recurse\n- Otherwise, return the current node\n\nThis will effectively iterate through the list and flip the direction of each node\'s edge, then return the tail of the original list. To use as little memory as possible, we can make our changes directly to the input instead of creating a new list.\n\nThis algorithm\'s time complexity is $$\u0398(n)$$ (where n is the size of the original list) because it calls itself exactly once per node in the original list. The space complexity is $$\u0398(n)$$ because a new scope is created for each level of recursion.\n\n```ts\nfunction reverseList(\n head: ListNode | null,\n parent: ListNode | null = null,\n): ListNode | null {\n if (!head) return parent;\n\n const next = head.next;\n head.next = parent;\n\n return reverseList(next, head);\n};\n```\n\n# Pure Recursive\n\nWith a slight change to the impure recursive algorithm, we can produce the same result while leaving the original list in-tact.\n\nThis algorithm\'s time complexity is $$\u0398(n)$$ (where n is the size of the original list) because it calls itself exactly once per node in the original list. The space complexity is $$\u0398(n)$$ because the caller scope will always persist while the function recurses and the algorithm creates exactly one new node for each node in the original list.\n\n```ts\nfunction reverseList(head: ListNode | null): ListNode | null {\n if (!head) return head;\n\n function reverse(curr: ListNode, parent: ListNode | null): ListNode {\n const next = curr.next;\n\n curr = new ListNode(curr.val, parent);\n\n if (!next) return curr;\n return reverse(next, curr);\n }\n\n return reverse(head, null);\n};\n```\n\n# Impure Iterative\n\nTo reverse the list with iteration:\n\n- If the current node is empty, bail\n- Keep a reference to the previous node\n- Do the following until the current node is empty:\n - Keep a reference to the next node\n - Flip the direction of the current node\'s edge\n - Move to the next node (prev <= current, current <= next)\n\nTo use as little memory as possible, we can make our changes directly to the input instead of creating a new list.\n\nThis algorithm\'s time complexity is $$\u0398(n)$$ (where n is the size of the original list) because it iterates exactly once per node in the original list. The space complexity is $$\u0398(1)$$ because it does not create any new objects and does not call and functions.\n\n```ts\nfunction reverseList(head: ListNode | null): ListNode | null {\n let prev = null;\n\n while (head) {\n let next = head.next;\n head.next = prev;\n prev = head;\n head = next;\n }\n\n return prev;\n}\n```\n\n# Pure Iterative\n\nWith a small change to the impure iterative algorithm, we can keep the original list in-tact at the cost of a linear space complexity. \n\nThis algorithm\'s time complexity is $$\u0398(n)$$ (where n is the size of the original list) because it iterates exactly once per node in the original list. The space complexity is $$\u0398(n)$$ because it creates a new node for each node found in the original list.\n\n```ts\nfunction reverseList(head: ListNode | null): ListNode | null {\n let prev: ListNode | null = null;\n\n while (head) {\n prev = new ListNode(head.val, prev);\n head = head.next;\n }\n\n return prev;\n}\n```\n\n# Conclusion\n\nIn most cases, the pure iterative algorithm is preferred as it provides the best real-world performance (no bloated call stacks) while keeping the function pure. Pure functions are preferred in many cases, especially when there may be multiple algorithms running in parallel on the same list.\n\nIn cases where parameter ownership is known, the impure iterative algorithm is prefferred as it provides the best time and space complexity in the tight case. Keep in mind that the TypeScript compiler cannot determine parameter ownership at compile time, so new code may break this constraint. Short of rewriting your solution in Rust, documentation is the best remedy for this.
21
0
['TypeScript']
4
reverse-linked-list
JS iterative solution with comments
js-iterative-solution-with-comments-by-m-ld3f
\n// Time Complexity: O(n), Linear - traverse linked list only once\n// Space Complexity: O(1), Constant - we will only have 2 pointers regardless of size of in
mrbanh
NORMAL
2019-08-30T20:35:00.966679+00:00
2019-08-30T20:35:00.966717+00:00
2,757
false
```\n// Time Complexity: O(n), Linear - traverse linked list only once\n// Space Complexity: O(1), Constant - we will only have 2 pointers regardless of size of input; prev and temp\n\nvar reverseList = function(head) {\n // End of the reversed linked list set to null\n let prev = null;\n \n // Traverse through the given linked list\n while (head) {\n const temp = head.next; // References the next Node of given linked list\n head.next = prev; // head.next point to previous Node, instead of the next Node of the given linked list\n prev = head; // Move the prev Node pointer up to head\n head = temp; // Move the head up to next Node of the given linked list\n }\n \n // Prev is the reversed linked list\n return prev;\n};\n```
19
0
['JavaScript']
0
reverse-linked-list
C++ | 2 Short O(n) Code | Iterative + Recursive | Easy Code
c-2-short-on-code-iterative-recursive-ea-c5bi
Approach 1: Iterative\n\nclass Solution {\npublic:\n ListNode* reverseList(ListNode* head) {\n ListNode *pre = NULL, *cur = head, *nex;\n \n
blazeyp
NORMAL
2021-10-03T12:18:53.628473+00:00
2021-10-03T12:18:53.628504+00:00
2,202
false
**Approach 1: Iterative**\n```\nclass Solution {\npublic:\n ListNode* reverseList(ListNode* head) {\n ListNode *pre = NULL, *cur = head, *nex;\n \n while(cur != NULL){\n nex = cur->next;\n cur->next = pre;\n pre = cur;\n cur = nex;\n }\n \n return pre;\n }\n};\n```\n**Approach 2: Recursive**\n```\nclass Solution { \n public:\n \n ListNode* helper(ListNode *pre, ListNode *root){\n if(root == NULL)\n return pre;\n ListNode *t = root->next;\n root->next = pre;\n return helper(root,t); \n }\n \n ListNode* reverseList(ListNode* root) {\n return helper(NULL, root);\n }\n};
18
0
['Recursion', 'C', 'Iterator', 'C++']
1
reverse-linked-list
✅ Animated Solution - 3 Approach - Recursion , Two Pointer
animated-solution-3-approach-recursion-t-pp59
Interview []\nIf you get this question in your interview and you haven\'t solve this\nit\'s less possible to comeup with 3rd approach and to be honest questions
cs_iitian
NORMAL
2024-03-21T03:36:51.377895+00:00
2024-03-24T17:16:48.862756+00:00
1,634
false
```Interview []\nIf you get this question in your interview and you haven\'t solve this\nit\'s less possible to comeup with 3rd approach and to be honest questions\non Binary Tree and Linked List are mostly asked that you have already\nseen, I mean there is very less variety available until and unless\ninterview himself made the questions but logic would be same.\n```\n\nAnimation is at the end.\n\n\n# Approach#1 ( Recursion )\n<!-- Describe your approach to solving the problem. -->\nMove to the next node till we reach the last node, now return this node to prev node, now change the returned node\'s next to prev node. and now return prev node and do this recursively.\nRemeber to change the curr node\'s next to null, else you will end up in creating cycle.\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```Java []\nclass Solution {\n ListNode newHead;\n public ListNode reverseList(ListNode head) {\n if(head == null) return null;\n reverseListHelper(head);\n return newHead;\n }\n\n public ListNode reverseListHelper(ListNode head) {\n if(head.next == null) return newHead = head;\n ListNode nextNode = reverseListHelper(head.next);\n nextNode.next = head;\n head.next = null;\n return head;\n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n ListNode* newHead = nullptr;\n\n ListNode* reverseList(ListNode* head) {\n if (head == nullptr) return nullptr;\n reverseListHelper(head);\n return newHead;\n }\n\n ListNode* reverseListHelper(ListNode* head) {\n if (head->next == nullptr) {\n newHead = head;\n return head;\n }\n ListNode* nextNode = reverseListHelper(head->next);\n nextNode->next = head;\n head->next = nullptr;\n return head;\n }\n};\n```\n```Python3 []\nclass Solution:\n def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:\n if head is None:\n return None\n self.reverseListHelper(head)\n return self.newHead\n \n def reverseListHelper(self, head: ListNode) -> ListNode:\n if head.next is None:\n self.newHead = head\n return head\n nextNode = self.reverseListHelper(head.next)\n nextNode.next = head\n head.next = None\n return head\n```\n\n# Approach#1 Optimisation\nSince every time we will change the node\'s next pointer to previous, so we don\'t need to mark it as null except the first node, which has no previous node. So once we are done with recursion we will change first node\'s next to null.\n\n# Code\n```Java []\nclass Solution {\n ListNode newHead;\n public ListNode reverseList(ListNode head) {\n if(head == null) return null;\n reverseListHelper(head);\n head.next = null;\n return newHead;\n }\n\n public ListNode reverseListHelper(ListNode head) {\n if(head.next == null) return newHead = head;\n ListNode nextNode = reverseListHelper(head.next);\n nextNode.next = head;\n return head;\n }\n}\n```\n\n# Approach#2 ( Recursion , Early Poitner Change )\nHere we will track prev and current node in our recursion stack and will change the current\'s next to prev and then move to next node. now for next node, prev would be the current node.\n\n# Code\n```\n/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n ListNode newHead;\n public ListNode reverseList(ListNode head) {\n if(head == null) return null;\n reverseListHelper(null, head);\n return newHead;\n }\n\n public void reverseListHelper(ListNode prev, ListNode head) {\n if(head == null) return;\n if(head.next == null) {\n newHead = head;\n }\n ListNode next = head.next;\n head.next = prev;\n reverseListHelper(head, next);\n }\n}\n```\n\n# Approach#3 ( Two Pointer )\nSee this video animation, you will understand it.\nhttps://youtube.com/shorts/Du4elALktj8\n\nThe idea is always make sure, you store previous node and change current node\'s next to previous node. and move to next node now since we are changing current node\'s next so first we will store current node\'s next node so that we don\'t lose the node and that\'s it.\n\nNow at the end your previous node would be the head of the linked list.\n\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```Java []\nclass Solution {\n public ListNode reverseList(ListNode head) {\n ListNode prev = null;\n ListNode curr = head;\n while(curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n ListNode* reverseList(ListNode* head) {\n ListNode *prev = nullptr;\n ListNode *curr = head;\n while (curr != nullptr) {\n ListNode *nextTemp = curr->next;\n curr->next = prev;\n prev = curr;\n curr = nextTemp;\n }\n return prev;\n }\n};\n```\n```Python3 []\nclass Solution:\n def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:\n prev, curr = None, head\n while curr:\n next = curr.next\n curr.next = prev\n prev, curr = curr, next\n return prev\n```\n```JavaScript []\nvar reverseList = function(head) {\n let prev = null;\n let curr = head;\n while (curr !== null) {\n let nextTemp = curr.next;\n curr.next = prev;\n prev = curr;\n curr = nextTemp;\n }\n return prev;\n};\n```\n```Kotlin []\nclass Solution {\n fun reverseList(head: ListNode?): ListNode? {\n var prev: ListNode? = null\n var curr = head\n while (curr != null) {\n val nextTemp = curr.next\n curr.next = prev\n prev = curr\n curr = nextTemp\n }\n return prev\n }\n}\n```\n\nAnimation Video for Approach - 3 ( Open in new Tab for better experience )\nor visit this link for slowed version\nhttps://youtube.com/shorts/Du4elALktj8\n![Reverse Linked List - Animation.gif](https://assets.leetcode.com/users/images/fc58d7b7-caba-4f22-ab25-389274e331a3_1710993442.234485.gif)\n\nIf you like the blog, please upvote it.\n\n---\n### Connect via\n#### [1. Instagram](https://www.instagram.com/cs_iitian/) ( Follow )\n#### [2. Facebook Page](https://www.facebook.com/cs.iitian)\n#### [3. Twitter](https://twitter.com/cs_iitian)\n#### [4. Blog](https://csiitian.blog/) ( Subscribe to news letter )\n#### [5. Medium](https://medium.com/@csiitian)\n#### [6. Youtube](https://www.youtube.com/channel/UCuxmikkhqbmBOUVxf-61hxw) ( Like, Share & Subscribe )\n#### [7. Leetcode](https://leetcode.com/cs_iitian/)\n
17
0
['C++', 'Java', 'Python3', 'JavaScript']
2
reverse-linked-list
beats 100%||Easy reverse Linked List||Explain with figure
beats-100easy-reverse-linked-listexplain-c9j0
Intuition\n Describe your first thoughts on how to solve this problem. \nExercise for reverse Linked List.\n# Approach\n Describe your approach to solving the p
anwendeng
NORMAL
2024-03-21T01:57:11.019838+00:00
2024-03-21T06:19:51.460123+00:00
5,350
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nExercise for reverse Linked List.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nTransverse the ListNode with pointer cur.\nUse 2 extra pointers prev & Next to reverse the Linked List.\n![reverseLN.png](https://assets.leetcode.com/users/images/63b66dd9-1064-4587-a706-9d16e7870212_1710993501.6268916.png)\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(1)$$\n# Code||0ms beats 100%\n```\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode() : val(0), next(nullptr) {}\n * ListNode(int x) : val(x), next(nullptr) {}\n * ListNode(int x, ListNode *next) : val(x), next(next) {}\n * };\n */\nclass Solution {\npublic:\n ListNode* reverseList(ListNode* head) {\n if (head==NULL || head->next==NULL) return head;\n ListNode* cur=head, *Next, *prev=NULL;\n while(cur!=NULL){\n Next=cur->next;\n cur->next=prev;\n prev=cur;\n cur=Next;\n }\n return prev;\n }\n};\n```\nOther linked list question [Leetcdoe 86. Partition List](https://leetcode.com/problems/partition-list/solutions/3910854/c-c-linked-lists-with-explanation/)\n[Please turn on English subtitles if necessary]\n[https://youtu.be/LZ6oARGKnZA?si=v5WQXtuCA6DYuqct](https://youtu.be/LZ6oARGKnZA?si=v5WQXtuCA6DYuqct)
17
1
['Linked List', 'C++']
3
reverse-linked-list
✅Java Simple Solution || ✅Runtime 0ms || ✅ Beats100%
java-simple-solution-runtime-0ms-beats10-6xlx
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
ahmedna126
NORMAL
2023-08-12T14:21:03.468177+00:00
2023-11-07T11:43:55.098329+00:00
1,549
false
# 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)$$ -->\n------\n\n1. We use three pointers to perform the reversing: prev, next, head.\n2. Point the current node to head and assign its next value to the prev node.\n3. Iteratively repeat the step 2 for all the nodes in the list.\n4. Assign head to the prev node.\n\n![image.png](https://assets.leetcode.com/users/images/315ddef6-bde6-487c-91b5-819452fd0868_1691849968.8248606.png)\n\n\n\n# Code\n```\n/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n public ListNode reverseList(ListNode head) {\n ListNode prev = null;\n ListNode cur = head;\n ListNode temp = null;\n\n while(cur != null)\n { \n temp = cur.next;\n cur.next = prev;\n prev = cur;\n cur = temp;\n }\n head = prev;\n \n return head;\n \n }\n}\n```\n\n## For additional problem-solving solutions, you can explore my repository on GitHub: [GitHub Repository](https://github.com/ahmedna126/java_leetcode_challenges)\n\n\n\n![e78315ef-8a9d-492b-9908-e3917f23eb31_1674946036.087042.jpeg](https://assets.leetcode.com/users/images/38c23ad1-23e9-4425-86ec-a7538326cc78_1691849749.8522763.jpeg)\n
17
0
['Java']
1
reverse-linked-list
206: Space Beats 99.79%, Solution with step by step explanation
206-space-beats-9979-solution-with-step-e7m03
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\nTo reverse a singly linked list, we need to change the pointers of each n
Marlen09
NORMAL
2023-02-23T20:17:41.484332+00:00
2023-02-23T20:17:41.484362+00:00
4,680
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nTo reverse a singly linked list, we need to change the pointers of each node to point to the previous node instead of the next node.\n\nWe can start by initializing three pointers:\n\n- prev: a pointer to the previous node, initially None.\n- curr: a pointer to the current node, initially the head of the linked list.\n- nxt: a pointer to the next node, initially None.\n- We can then iterate over the linked list while updating the pointers as follows:\n\nFirst, we set nxt to the next node of curr.\n- We then update curr\'s next pointer to point to prev (i.e., reverse the next pointer).\n- We then set prev to curr, and curr to nxt, effectively moving the pointers one node ahead.\n- We repeat this process until curr becomes None, at which point we return prev as the new head of the reversed linked list.\n\n# Complexity\n- Time complexity:\nBeats\n40.90%\n\n- Space complexity:\nBeats\n99.79%\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 reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:\n prev = None\n curr = head\n \n while curr:\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n \n return prev\n\n```
17
0
['Linked List', 'Recursion', 'Python', 'Python3']
1
reverse-linked-list
Super Ez Python Solution ➕ graph Explanation!!! | two pointers | Faster than 93%✅
super-ez-python-solution-graph-explanati-mff6
\u628Acur.next\u5B58\u5230nextnode\u4E2D\uFF0C\u9632\u6B62\u65AD\u5F00\u540E\u627E\u4E0D\u5230\nStore cur.next in nextnode, because we will disconnect the cur->
sophiel625
NORMAL
2022-06-21T21:51:11.521025+00:00
2022-08-09T23:01:12.961887+00:00
1,280
false
1. \u628Acur.next\u5B58\u5230nextnode\u4E2D\uFF0C\u9632\u6B62\u65AD\u5F00\u540E\u627E\u4E0D\u5230\nStore cur.next in nextnode, because we will disconnect the cur->nextnode for the reverse\n\n2. \u8BA9cur\u6307\u5411prev, \u5373 cur.next = prev\nLet cur -> prev for reversing, which is cur.next = prev\n\n3. prev\u548Ccur\u90FD\u5F80\u524D\u79FB\u4E00\u4F4D\uFF0Cnextnode\u4F1A\u81EA\u52A8\u5728\u4E0B\u4E00\u6B21\u5FAA\u73AF\u4E2D\u5F80\u524D\u79FB\u4E00\u4F4D\nMove prev and cur to the next number, which is prev = cur, cur = nextnode\n\n4. \u5F53cur\u4E3A\u7A7A\u7684\u65F6\u5019\u8BF4\u660E\u53CD\u8F6C\u5DF2\u7ECF\u7ED3\u675F\u4E86\uFF0C\u6211\u4EEC\u8981\u8FD4\u56DEcur\u524D\u4E00\u4E2A\u8282\u70B9\uFF0C\u6240\u4EE5return prev\nFinish list reversing when cur is Null and the loop end, we need to return the point before cur, so is return prev\n\n\u542C\u61C2\u638C\u58F0\uFF01\npls upvote me if u understand! :)\n![image](https://assets.leetcode.com/users/images/39a9a7bf-a4a9-45a6-a8d6-56ff176fcdde_1655848048.2144887.png)\n``` \ndef reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:\n if head is None or head.next is None:\n return head\n prev = None\n cur = head\n while cur:\n nextnode = cur.next\n cur.next = prev\n prev = cur\n cur = nextnode\n return prev\n
17
0
['Two Pointers', 'Python', 'Python3']
1
reverse-linked-list
CPP Recursive Solution explained
cpp-recursive-solution-explained-by-ujjw-a4wn
The base case for recursion is if list is empty i.e. head points to null or head-> next is null i.e. single element in the list, then the reverse of single elem
ujjw4l
NORMAL
2021-07-25T15:00:47.136095+00:00
2021-07-25T15:00:47.136136+00:00
1,257
false
The base case for recursion is if list is empty i.e. head points to null or head-> next is null i.e. single element in the list, then the reverse of single element is that element itself so we return head itself.\n\nGenerally, in recursion we break the problem into 1 and (n-1) parts where we handle 1 part and let recursion handle (n-1) parts, so we pass head->next (i.e. from the second node to the end of the list) to the recursive call.\n\nSo, after the recursive function is called, our list is almost reversed except the first node. Say, our original list was 1->2->3->4->5, then we have 5->4->3->2 after recursion. Now, we just have to add the first element of orginal list to the end. \n\nTo clearly explain the last 2 lines lets take an example:\n\nSay 1 is stored at 100, 2 at 200 and so on... head->next->next = head means head->next i.e. 200\'s next i.e. 300 is now changed to head i.e. 100. So now the node with val 2 points to the head i.e 2->1 which is exactly what we wanted. The last line head->next = NULL means that the head node will point to null thus, marking the end of our list. So, finally our list becomes 5->4->3->2->1->NULL\n\nBelow is my code if you want to refer to it:\n```\nclass Solution {\npublic:\n ListNode* reverseList(ListNode* head) {\n // base case for recursion is if head is null:\n if (head == NULL || head -> next == NULL) {\n return head;\n }\n // recursive call so passing all elements except first because in recursion we break nodes as 1 and (n-1) and we handle 1 and recursion handles (n-1) part:\n ListNode* node = reverseList(head -> next);\n head -> next -> next = head;\n head -> next = NULL;\n return node;\n }\n};\n```
17
0
['Recursion', 'C', 'C++']
4
reverse-linked-list
Java 2 solutons : In place operation(beats 100%) and Create a new linked list(beats 100%)
java-2-solutons-in-place-operationbeats-2ktvp
Please upvote if it helps,it\'s important for me\uD83D\uDE0A.\n\nHere are two methods :\n1\u3001In place operations(We should master it)\n\n\npublic ListNode re
Sarah_Lene
NORMAL
2022-03-20T06:00:51.502751+00:00
2022-03-20T07:36:42.787914+00:00
776
false
***Please upvote if it helps,it\'s important for me\uD83D\uDE0A.***\n\nHere are two methods :\n**1\u3001In place operations(We should master it)**\n![image](https://assets.leetcode.com/users/images/86ed2e34-f975-4310-b4b8-f9924416081e_1647755954.9587948.jpeg)\n```\npublic ListNode reverseList(ListNode head) {\n if(head == null || head.next == null) return head;\n ListNode curr = head;\n ListNode prev = null;\n ListNode next;\n while(curr != null){\n next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n }\n```\n**2\u3001Create a new linked list.**\n```\npublic ListNode reverseList(ListNode head) {\n ListNode result = null;\n while(head != null){\n result = new ListNode(head.val,result);\n head = head.next;\n }\n return result;\n }\n```
16
0
['Java']
2
reverse-linked-list
Easiest way to reverse Linked List explained with Images
easiest-way-to-reverse-linked-list-expla-tz7j
// Hi Devs if you like my post and it helps you please do vote so that it reaches more Devs\n\n\n// In this approach we uses a three pointers \n// p --> previou
Code_Y
NORMAL
2022-08-31T16:48:40.362788+00:00
2022-08-31T16:48:40.362834+00:00
2,574
false
// **Hi Devs if you like my post and it helps you please do vote so that it reaches more Devs**\n\n\n// In this approach we uses a three pointers \n// p --> previous , c --> current , n --> next\n// in every itration we reverse link between p and c , Then move pointers .\n\n![image](https://assets.leetcode.com/users/images/8a170425-7f78-496a-8c48-0e219f1b2b74_1661964315.967118.png)\n\n\n\n```\nvar reverseList = function(head) {\n let p =null;\n let c = head ;\n \n \n while(c){\n let n = c.next //next\n c.next =p; //reverse link and break link between c and n\n p=c; // move p\n c=n; // move c\n \n }\n return p;\n};\n```
15
0
['Linked List', 'C', 'Iterator', 'Java', 'JavaScript']
0
reverse-linked-list
Python iterative and recursive solutions
python-iterative-and-recursive-solutions-oqeq
\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
huayra
NORMAL
2019-03-09T02:28:57.862551+00:00
2019-03-09T02:28:57.862592+00:00
2,405
false
```\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\tdef reverseList_i(self, head: ListNode) -> ListNode: # iterative\n\t# O(n) Time / O(1) Space\n\t\tprev = None\n\t\tcur = head\n\t\twhile cur:\n\t\t\ttmp_next = cur.next\n\t\t\tcur.next = prev\n\t\t\tprev = cur\n\t\t\tcur = tmp_next\n\t\treturn prev\n \n def reverseList_r(self, head: ListNode) -> ListNode: # recursive\n\t# O(n) Time / O(n) Space\n if not head or not head.next: return head\n p = self.reverseList(head.next)\n head.next.next = head\n head.next = None\n return p\n```
15
0
['Recursion', 'Iterator', 'Python']
1
reverse-linked-list
Java solution -- recursion and iteration methods
java-solution-recursion-and-iteration-me-58xw
// Recursion: \n\n public ListNode reverseList(ListNode head) {\n return helper(null, head);\n }\n \n ListNode helper(ListNode reversed, List
peng4
NORMAL
2015-09-11T21:02:00+00:00
2018-09-08T21:01:57.497294+00:00
3,225
false
// Recursion: \n\n public ListNode reverseList(ListNode head) {\n return helper(null, head);\n }\n \n ListNode helper(ListNode reversed, ListNode remaining) {\n if(remaining==null) return reversed;\n ListNode tmp = remaining.next;\n remaining.next = reversed;\n \n return helper(remaining, tmp);\n }\n\n// Iteration:\n\n public ListNode reverseList(ListNode head) {\n if(head==null) return head;\n \n ListNode newhead = new ListNode(0);\n newhead.next = head;\n \n while(head.next!=null) {\n ListNode tmp = head.next;\n head.next = head.next.next;\n \n tmp.next = newhead.next;\n newhead.next = tmp;\n }\n return newhead.next;\n }
15
1
[]
2
reverse-linked-list
0ms Simple Java Solution
0ms-simple-java-solution-by-jguo11-yy39
public ListNode reverseList(ListNode head) {\n ListNode prev = null;\n while(head != null){\n ListNode next = head.next;\n h
jguo11
NORMAL
2016-03-20T17:20:50+00:00
2016-03-20T17:20:50+00:00
2,277
false
public ListNode reverseList(ListNode head) {\n ListNode prev = null;\n while(head != null){\n ListNode next = head.next;\n head.next = prev;\n prev = head;\n head = next;\n }\n return prev;\n }
15
0
['Java']
2
reverse-linked-list
Python Recursion Implemention
python-recursion-implemention-by-francis-m5ne
Python Recursion Implemention\n\npython\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n#
francisgee
NORMAL
2017-11-14T03:46:58.990000+00:00
2017-11-14T03:46:58.990000+00:00
4,371
false
Python Recursion Implemention\n\n```python\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 reverseList(self, head):\n """\n :type head: ListNode\n :rtype: ListNode\n """\n if not head or not head.next:\n return head\n second = head.next\n reverse = self.reverseList(second)\n second.next = head\n head.next = None\n \n return reverse\n\n\n```
15
1
[]
0
reverse-linked-list
[Python Explained Recursive Iterative]
python-explained-recursive-iterative-by-hrik6
\n\n\nRecursive:\n\nclass Solution:\n def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:\n if not head or not head.next:
Coss_True
NORMAL
2022-09-15T08:24:06.550725+00:00
2022-09-15T10:18:55.571010+00:00
1,219
false
![image](https://assets.leetcode.com/users/images/1caa5168-a9c7-4716-8a7f-0202926c8dff_1663236706.4428494.png)\n\n\nRecursive:\n```\nclass Solution:\n def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:\n if not head or not head.next: # nothing to reverse\n return head\n\t\tnewHead = self.reverseList(head.next) # see what\'s happening on the diagram above\n\t\thead.next.next = head\n\t\thead.next = None # see "head off" column\n\t\treturn newHead\n```\nIterative:\n```\nclass Solution:\n def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:\n newHead = None # "newHead" is to be returned. By now it\'s tail.\n while head:\n previous = newHead\n newHead = head # Now any doing with "newHead" makes the same doing with "head".\n head = head.next # !!! That\'s why this line can\'t be placed after the next. \n newHead.next = previous # Since "head" is freed, "newHead.next = previous" will not cause "head.next = previous".\n return newHead\n```
14
0
['Linked List', 'Recursion', 'Python']
2
reverse-linked-list
One line of code to remember the approach
one-line-of-code-to-remember-the-approac-kqu7
This problem can be a part of a bigger problem. One can get confused even after solving it previously. \nYou have to remember that we have to manage three upda
jenishah
NORMAL
2020-03-22T13:46:47.366509+00:00
2020-03-22T13:46:47.366540+00:00
2,977
false
This problem can be a part of a bigger problem. One can get confused even after solving it previously. \nYou have to remember that we have to manage three updates , and all updates can be done in one line.\n```\nclass Solution:\n def reverseList(self, head: ListNode) -> ListNode:\n first = head\n if (not first) or (not first.next): return first\n\n first.next, curr, prev = None, first.next, first\n \n #1. Reverse (curr.next = prev)\n #2. Update Current\n #3. Update previous\n \n while curr.next:\n curr.next, curr, prev = prev, curr.next, curr\n\n curr.next = prev\n return curr\n```
14
2
['Python', 'Python3']
3
reverse-linked-list
Java iterative and recursive solutions, both 0ms and 100% faster
java-iterative-and-recursive-solutions-b-sqd8
Iteratively:\n\npublic ListNode reverseList(ListNode head) {\n ListNode prev = null;\n ListNode node = head;\n\n while (node != null) {\n ListNo
falmp
NORMAL
2020-02-11T22:00:54.387948+00:00
2020-02-11T22:03:19.379745+00:00
1,907
false
**Iteratively:**\n```\npublic ListNode reverseList(ListNode head) {\n ListNode prev = null;\n ListNode node = head;\n\n while (node != null) {\n ListNode aux = node.next;\n node.next = prev;\n \n prev = node;\n node = aux;\n }\n \n return prev;\n}\n```\n\n**Recursively:**\n```\npublic ListNode reverseList(ListNode head) {\n return reverseList(null, head);\n}\n\npublic ListNode reverseList(ListNode prev, ListNode node) {\n if (node == null) {\n return prev;\n }\n \n ListNode aux = node.next;\n node.next = prev;\n \n return reverseList(node, aux);\n}\n```
14
0
['Recursion', 'Iterator', 'Java']
2
reverse-linked-list
C++ solution .. very easy..
c-solution-very-easy-by-homerhickam-60k8
/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode(int x) : val(x),
homerhickam
NORMAL
2015-06-13T20:38:37+00:00
2015-06-13T20:38:37+00:00
3,705
false
/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode(int x) : val(x), next(NULL) {}\n * };\n */\n class Solution {\n public:\n ListNode* reverseList(ListNode* head) {\n ListNode *temp = NULL , *nextNode = NULL;\n while(head){\n nextNode = head->next;\n head->next = temp;\n temp = head;\n head = nextNode;\n }\n return temp;\n }\n };
14
0
[]
2
reverse-linked-list
Python | Iterative | Really, really, REALLY simple solution!
python-iterative-really-really-really-si-96ne
The approach is the following: we need to point current node\'s next to the last node we saw, update the last node to be this current node, and move to the next
hemersontacon
NORMAL
2021-11-11T11:06:32.602631+00:00
2021-11-11T11:06:32.602813+00:00
812
false
The approach is the following: we need to point current node\'s next to the last node we saw, update the last node to be this current node, and move to the next node (which is the current node\'s next before any changes). In Python we can do these 3 operations at the same time with the help of tuple (un)packing sintax without the need of temporary swap variables.\n\n```\nclass Solution:\n def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:\n \n last = None\n while head:\n last, head.next, head = head, last, head.next\n \n return last\n```
13
0
['Linked List', 'Iterator', 'Python']
2
reverse-linked-list
Javascript - recursion
javascript-recursion-by-achandel-6guk
\n// time complexity - O (n)\n// space complexity - O (n)\nvar reverseList = function(head) {\n const helper = (current, prev) => {\n if(current === n
achandel
NORMAL
2020-03-22T21:02:47.041101+00:00
2020-03-22T21:02:56.003348+00:00
1,910
false
```\n// time complexity - O (n)\n// space complexity - O (n)\nvar reverseList = function(head) {\n const helper = (current, prev) => {\n if(current === null) return prev;\n\t\t// next node\n let next = current.next;\n\t\t// append previous nodes in current\n current.next = prev;\n return helper(next, current)\n }\n return helper(head, null);\n};\n```
13
0
['Recursion', 'JavaScript']
0
reverse-linked-list
golang
golang-by-zz12345-nzac
\nfunc reverseList(head *ListNode) *ListNode {\n\tvar prev *ListNode\n\tcur := head\n\tfor cur != nil {\n\t\tprev, cur, cur.Next = cur, cur.Next, prev\n\t}\n\n\
zz12345
NORMAL
2019-12-25T07:58:23.021191+00:00
2019-12-25T07:58:23.021229+00:00
688
false
```\nfunc reverseList(head *ListNode) *ListNode {\n\tvar prev *ListNode\n\tcur := head\n\tfor cur != nil {\n\t\tprev, cur, cur.Next = cur, cur.Next, prev\n\t}\n\n\treturn prev\n}\n```
13
0
[]
5
reverse-linked-list
Python solutions
python-solutions-by-amchoukir-p1kz
Iterative\n\npython\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n
amchoukir
NORMAL
2019-09-14T14:40:23.770867+00:00
2019-09-14T14:57:38.645665+00:00
2,582
false
# Iterative\n\n```python\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 reverseList(self, head: ListNode) -> ListNode:\n prev = None\n node = head\n while node:\n next = node.next\n node.next = prev\n prev = node\n node = next\n return prev\n```\n\n# Recursive\nThis first solution reverse the current node right away and continues with reversing the rest of the list.\n\n```python\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 \n def reverseListRec(self, node, prev):\n if node is None:\n return prev\n tmp = node.next\n node.next = prev\n return self.reverseListRec(tmp, node)\n \n def reverseList(self, head: ListNode) -> ListNode:\n return self.reverseListRec(head, None)\n```\n\nThis solution defer reversing the current node until the remainder of the list is reversed\n\n```python\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 reverseList(self, head: ListNode) -> ListNode:\n if not head or not head.next:\n return head\n p = self.reverseList(head.next)\n head.next.next = head\n head.next = None\n return p\n```
13
0
['Python', 'Python3']
0
reverse-linked-list
66ms Python recursive 5 lines
66ms-python-recursive-5-lines-by-nappfly-upgb
\n def reverseList(self, head, last = None):\n if not head:\n return last\n next = head.next\n head.next = last\n retu
nappflying
NORMAL
2015-05-08T15:58:30+00:00
2015-05-08T15:58:30+00:00
2,209
false
\n def reverseList(self, head, last = None):\n if not head:\n return last\n next = head.next\n head.next = last\n return self.reverseList(next, head)
13
0
[]
1
reverse-linked-list
Clear iterative Python solution
clear-iterative-python-solution-by-edoua-tn1k
class Solution(object):\n def reverseList(self, head):\n \n if not head: return head\n \n p, q = head, head.n
edouardfouche
NORMAL
2016-02-05T18:12:16+00:00
2016-02-05T18:12:16+00:00
3,664
false
class Solution(object):\n def reverseList(self, head):\n \n if not head: return head\n \n p, q = head, head.next\n p.next = None\n \n while q:\n tmp, q.next = q.next, p\n p, q = q, tmp\n \n return p
13
2
['Iterator', 'Python']
0
reverse-linked-list
ITERATIVE + RECURSIVE 🔥🔥 APPROACH || Explanation with images || Easy to understand || Beats 100%
iterative-recursive-approach-explanation-bef4
Intuition\nReverse Linked List Problem can be solved both iteratively and recursively.\n\nIdea is to reverse all the connections and return the last node as new
dcodeDV
NORMAL
2024-03-21T18:46:41.109625+00:00
2024-03-21T18:54:52.501499+00:00
278
false
# Intuition\nReverse Linked List Problem can be solved both iteratively and recursively.\n\nIdea is to reverse all the connections and return the last node as new head.\n\n- **Iterative Intuition**\n1. For each node `N` we want `N` points to `N-1` and `N+1` points to `N`.\n2. So it is clear from above point that we will need 3 pointers to point 3 consecutive nodes.\n\n- **Recursive Intuition**\n1. For node `N` reverse the list starting from `N+1` recursively.\n2. In this new reversed list add `N` as last node and `N` now points to `NULL`.\n\n---\n\n\n\n# **Iterative Approach**\n1. Initialize two pointers : `prev = NULL` $$&$$ `curr = head`.\n2. Start a while loop till `curr != NULL` :-\n3. Make another pointer `next = curr->next` to move to next node after manipulating it\'s connection.\n4. Make `curr->next = prev` to implement the intuition.\n5. Move `prev = curr` $$&$$ `curr = next`.\n6. After while loop completes return `prev` as head of reversed list.\n\n![iterative_approach.gif](https://assets.leetcode.com/users/images/c4f27e17-0f7a-49d2-ad0b-3da7742793a0_1711034129.3294234.gif)\n\n# **Recursive Approach**\n1. Base case for recursion\n```\nif(head == NULL || head->next == NULL)\n return head;\n```\n2. Call `reverseList()` recursively for `head->next` and get the newhead for reversed list.\n```\nListNode* newhead = reverseList(head->next);\n```\n3. Now `head` points to the last node of new reversed list which points to `NULL`. So, to make correct connections perform following :-\n```\nhead->next->next = head;\nhead->next = NULL;\n```\n4. Return `newhead` as head of reversed list.\n![recursive_approach.gif](https://assets.leetcode.com/users/images/0ec6ff93-d575-4aae-b8ce-abc84f45b9be_1711035226.2436209.gif)\n\n\n---\n\n\n# Complexity\n- Time complexity: $$O(N)$$ for both approaches\n\n- Space complexity: \n1. $$O(1)$$ for iterative approach\n2. $$O(N)$$ for recursive approach (To maintain function call stack)\n\n---\n\n\n# Iteration Code\n```\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode() : val(0), next(nullptr) {}\n * ListNode(int x) : val(x), next(nullptr) {}\n * ListNode(int x, ListNode *next) : val(x), next(next) {}\n * };\n */\nclass Solution {\npublic:\n ListNode* reverseList(ListNode* head) {\n ListNode *prev = NULL, *curr = head;\n while(curr!=NULL) {\n ListNode *next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n return prev;\n }\n};\n```\n# Recursion Code\n```\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode() : val(0), next(nullptr) {}\n * ListNode(int x) : val(x), next(nullptr) {}\n * ListNode(int x, ListNode *next) : val(x), next(next) {}\n * };\n */\nclass Solution {\npublic:\n ListNode* reverseList(ListNode* head) {\n if(head == NULL || head->next == NULL)\n return head;\n ListNode* newhead = reverseList(head->next);\n head->next->next = head;\n head->next = NULL;\n return newhead;\n }\n};\n```\n\n# PLEASE UPVOTE\n![upvote_req.gif](https://assets.leetcode.com/users/images/0e7c897a-25e4-4475-aa37-e5e40bb4ce6a_1711047280.7046223.gif)\n
12
0
['Linked List', 'Recursion', 'C++']
4
reverse-linked-list
💯🔥 C++ | Java || Python || JavaScript 💯🔥
c-java-python-javascript-by-ganya9970-bkcr
\uD83D\uDCAF\uD83D\uDD25 C++ | Java || Python || JavaScript \uD83D\uDCAF\uD83D\uDD25\n\nRead Whole article : https://www.nileshblog.tech/reverse-linked-list/\n\
ganya9970
NORMAL
2023-09-11T06:16:13.555422+00:00
2023-09-11T06:16:13.555441+00:00
2,787
false
\uD83D\uDCAF\uD83D\uDD25 C++ | Java || Python || JavaScript \uD83D\uDCAF\uD83D\uDD25\n\nRead Whole article : https://www.nileshblog.tech/reverse-linked-list/\n\nExplanation with Human Hand Eg.\n\nPython :\nJava:\nc++:\nJavaScript:\n\nTime Complexity :\nO(n)\n\nRead Whole article : https://www.nileshblog.tech/reverse-linked-list/\n![image](https://assets.leetcode.com/users/images/3c802501-f4d5-473b-b3b0-89d5fea1b7db_1694412968.676702.png)\n\n
12
0
['C', 'Python', 'Java', 'JavaScript']
1
reverse-linked-list
SIMPLE JAVASCRIPT 98% BEATS || EASY EXPLANATION
simple-javascript-98-beats-easy-explanat-ph89
\n\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n1. The reverseList function takes a head parameter representing the head of the
ikboljonme
NORMAL
2023-03-28T23:52:13.159277+00:00
2023-03-28T23:52:13.159306+00:00
3,237
false
\n![Screenshot 2023-03-29 at 01.46.25.png](https://assets.leetcode.com/users/images/b170e5a6-c2fd-4bca-ab07-6d4cc9fb3b46_1680047222.5570757.png)\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. The reverseList function takes a head parameter representing the head of the linked list.\n2. The first thing the function does is check if the linked list is empty or has only one node. If it does, the function simply returns the head node, since a list with only one node is already reversed.\n3. If the linked list has more than one node, the function calls itself recursively with the next node as the new head. This recursively reverses the rest of the list.\n4. The reversedList variable now contains the reversed list from the next node to the end of the list.\n5. The function now sets the next node\'s next pointer to the current node, effectively reversing the current node\'s next pointer.\n6. Finally, the function sets the current node\'s next pointer to null to break the link with the next node and return the new head node, which is the last node of the original linked list.\n\n# Complexity\nThe time complexity of the reverseList function is O(n), where n is the number of nodes in the linked list. This is because the function iterates through each node in the list exactly once, performing a constant amount of work on each node.\n\n- Space complexity:\nThe space complexity of the function is O(1), because it only uses a constant amount of additional space to keep track of the current, previous, and next nodes as it iterates through the list. This means that the space used by the function does not depend on the size of the input, and is therefore constant.\n\n# Code\n```\n/**\n * Definition for singly-linked list.\n * function ListNode(val, next) {\n * this.val = (val===undefined ? 0 : val)\n * this.next = (next===undefined ? null : next)\n * }\n */\n/**\n * @param {ListNode} head\n * @return {ListNode}\n */\nvar reverseList = function(head) {\n let prev = null;\n let current = head;\n let next = null;\n \n while (current) {\n next = current.next;\n current.next = prev;\n prev = current;\n current = next;\n }\n \n return prev;\n};\n\n```
12
0
['JavaScript']
3
reverse-linked-list
Golang Simple Recursive with Explanation
golang-simple-recursive-with-explanation-4s5k
Solution\n Describe your approach to solving the problem. \nThis is the explanation for this recursive solution. For simplicity, we will use an input head that
jaydenteoh
NORMAL
2022-11-25T15:41:49.274211+00:00
2022-11-25T15:47:48.393641+00:00
1,372
false
# Solution\n<!-- Describe your approach to solving the problem. -->\nThis is the explanation for this recursive solution. For simplicity, we will use an input head that points to 1 -> 2 -> 3.\n\nI\'ll run through the recursive solution in chronological layers.\n\n### Outer Layer:\nInput 1 (current) = 1 -> 2 -> 3 -> nil\nInput 2 (prev) = nil\n\nnext = 2 -> 3 -> nil `next := current.Next`\ncurrent = 1 -> nil `current.Next = prev`\n\n### Layer 2:\nInput 1 (current) = 2 -> 3 -> nil\nInput 2 (prev) = 1 -> nil\n\nnext = 3 -> nil `next := current.Next`\ncurrent = 2 -> 1 -> nil `current.Next = prev`\n\n### Layer 3:\nInput 1 (current) = 3 -> nil\nInput 2 (prev) = 2 -> 1 -> nil\n\nnext = nil `next := current.Next`\ncurrent = 3 -> 2 -> 1 -> nil `current.Next = prev`\n\n### Layer 4:\nInput 1 (current) = nil\nInput 2 (prev) = 3 -> 2 -> 1 -> nil\n\nSince current == nil, return prev which is the reverse linked list 3 -> 2 -> 1 -> nil<br />`if current == nil{return prev}`\n\n# Code\n```\n/**\n * Definition for singly-linked list.\n * type ListNode struct {\n * Val int\n * Next *ListNode\n * }\n */\nfunc helper(current *ListNode, prev *ListNode) *ListNode {\n if current == nil{\n return prev\n }\n next := current.Next\n current.Next = prev\n return helper(next, current)\n}\n\nfunc reverseList(head *ListNode) *ListNode {\n return helper(head, nil)\n}\n```
12
0
['Recursion', 'Go']
0
reverse-linked-list
C# accepted, recursive, with simple explanations
c-accepted-recursive-with-simple-explana-2nmu
Given: \n1->2->3->4\n\nReverse the list after first node: \n1->(2->3->4)\n\nBecame: \n4->3->2, \n1->2\n\nNow we need to let: \n2->1, 1->null\n\nand get result:
rain4
NORMAL
2015-10-01T21:14:02+00:00
2015-10-01T21:14:02+00:00
1,058
false
Given: \n1->2->3->4\n\nReverse the list after first node: \n1->(2->3->4)\n\nBecame: \n4->3->2, \n1->2\n\nNow we need to let: \n2->1, 1->null\n\nand get result: \n4->3->2->1->null\n\n public ListNode ReverseList(ListNode head)\n {\n if (head == null || head.next == null)\n {\n return head;\n }\n \n ListNode newHead = ReverseList(head.next);\n head.next.next = head;\n head.next = null;\n \n return newHead;\n }
12
1
['Recursion']
2
reverse-linked-list
TWO APPROACH || ITERATIVE & RECURSIVE || EASY JAVA SOLUTION || BEATS 100%
two-approach-iterative-recursive-easy-ja-2o1f
Complexity\n- Time complexity: O(N)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O(1)\n Add your space complexity here, e.g. O(n) \n\n# Co
202151174
NORMAL
2023-07-15T11:10:18.155797+00:00
2023-07-15T11:10:18.155814+00:00
1,030
false
# Complexity\n- Time complexity: O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\n\n//################ RECURSIVE APPROACH ##################\n\nclass Solution {\n public ListNode reverseList(ListNode head) {\n \n if(head == null || head.next == null) {\n return head;\n }\n\n ListNode revHead = reverseList(head.next);\n \n ListNode temp = head.next;\n temp.next = head;\n head.next = null;\n\n return revHead;\n }\n}\n\n\n//################ ITERATIVE APPROACH ##################\n\nclass Solution {\n public ListNode reverseList(ListNode head) {\n ListNode prev = null;\n ListNode curr = head;\n ListNode forw = null;\n\n while (curr != null)\n {\n\n forw = curr.next;\n curr.next = prev;\n prev = curr;\n curr = forw;\n\n }\n\n return prev;\n }\n}\n\n```\n\n![cat.jpeg](https://assets.leetcode.com/users/images/e074d223-5cba-49f1-83d7-fb09a8c3cc5b_1689419354.7035532.jpeg)\n
11
0
['Linked List', 'Recursion', 'Java']
0
reverse-linked-list
Easy Explained Solution - Beats 100%
easy-explained-solution-beats-100-by-dee-ta0x
Please Upvote my solution, if you find it helpful ;)\n\n# Intuition\nThink of a linked list as a chain of nodes where each node points to the next node in the c
deepankyadav
NORMAL
2023-06-30T17:34:38.412258+00:00
2023-06-30T17:34:38.412281+00:00
1,988
false
## ***Please Upvote my solution, if you find it helpful ;)***\n\n# Intuition\nThink of a linked list as a chain of nodes where each node points to the next node in the chain. Reversing a linked list means changing the direction of the chain, making the last node the new head, and the previous head the new tail.\n# Approach\n1. We\'ll use two pointers, temp and head2, to help us manipulate the linked list during the reversal process. Both pointers are initially set to **null**.\n1. Starting from the original head of the linked list, we\'ll traverse the list one node at a time using a loop.\n1. At each step, we\'ll save the reference to the current node in temp. This is like "grasping" the current link in the chain.\n1. We\'ll then move the head pointer to the next node to proceed further in the original list. It\'s like "breaking" the link we just grasped and preparing to move on to the next link.\n1. Now, the temp node has been removed from the original chain. To reverse the direction, we\'ll make its next pointer point to head2.\n1. Finally, we\'ll move the head2 pointer to the current node (temp), effectively extending the reversed chain backward. The current node becomes the new head of the reversed list.\n1. We\'ll repeat steps 3 to 6 until we have traversed the entire original linked list.\n1. After the loop completes, the head2 pointer will be pointing to the new head of the reversed linked list.\n# Complexity\n- Time complexity:\nThe time complexity of the solution is $$O(n)$$, where n is the number of nodes in the linked list. We need to visit each node once to reverse the list.\n\n- Space complexity:\nThe space complexity of the solution is $$O(1)$$. We only use a constant amount of extra space, regardless of the size of the input linked list. The algorithm modifies the pointers in place and does not use any additional data structures.\n\n# Code\n\n```java []\n/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n public ListNode reverseList(ListNode head) {\n // Initialize temp and head2 as null, to be used for manipulation\n ListNode temp = null;\n ListNode head2 = null;\n\n // Traverse the linked list while head is not null\n while (head != null) {\n // Save the reference to the current node in the temp variable\n temp = head;\n\n // Move the head pointer to the next node\n head = head.next;\n\n // Point the next pointer of the current node to the head2,\n // effectively reversing the pointer direction\n temp.next = head2;\n\n // Move the head2 pointer to the current node,\n // so that it becomes the new head of the reversed linked list\n head2 = temp;\n }\n\n // Once the loop finishes, head2 will be pointing to the new head\n // of the reversed linked list\n return head2;\n }\n}\n```\n```python []\n# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution(object):\n def reverseList(self, head):\n """\n Reverse a singly linked list.\n\n :type head: ListNode\n :rtype: ListNode\n """\n # Initialize temp and head2 as None, to be used for manipulation\n temp = None\n head2 = None\n\n # Traverse the linked list while head is not None\n while head is not None:\n # Save the reference to the current node in the temp variable\n temp = head\n\n # Move the head pointer to the next node\n head = head.next\n\n # Point the next pointer of the current node to head2,\n # effectively reversing the pointer direction\n temp.next = head2\n\n # Move the head2 pointer to the current node,\n # so that it becomes the new head of the reversed linked list\n head2 = temp\n\n # Once the loop finishes, head2 will be pointing to the new head\n # of the reversed linked list\n return head2\n```\n```C++ []\nclass Solution {\npublic:\n ListNode* reverseList(ListNode* head) {\n // Initialize two pointers: temp to store the current node and head2 for the new head\n ListNode* temp = nullptr;\n ListNode* head2 = nullptr;\n\n // Traverse the linked list while head is not nullptr\n while (head != nullptr) {\n // Save the reference to the current node in the temp pointer\n temp = head;\n\n // Move the head pointer to the next node\n head = head->next;\n\n // Point the next pointer of the current node to head2,\n // effectively reversing the pointer direction\n temp->next = head2;\n\n // Move the head2 pointer to the current node,\n // so that it becomes the new head of the reversed linked list\n head2 = temp;\n }\n\n // Once the loop finishes, head2 will be pointing to the new head\n // of the reversed linked list\n return head2;\n }\n};\n```\n## ***Please Upvote my solution, if you find it helpful ;)***\n![6a87bc25-d70b-424f-9e60-7da6f345b82a_1673875931.8933976.jpeg](https://assets.leetcode.com/users/images/c47627af-be86-437f-8053-08e9229d6750_1688146390.8061645.jpeg)\n\n
11
0
['Linked List', 'Two Pointers', 'Python', 'C++', 'Java']
1
reverse-linked-list
C++/Java/Python/JavaScript|| ✅🚀Space: O(1) Simple Solution || ✔️🔥Easy To Understand
cjavapythonjavascript-space-o1-simple-so-1xzs
Intuition\nTake the head of a singly-linked list as input and reverses the list.\n\n# Approach\n\n1. Check if the head is NULL. If it is, it means the list is e
devanshupatel
NORMAL
2023-05-20T18:40:22.832053+00:00
2023-05-20T18:40:22.832083+00:00
5,775
false
# Intuition\nTake the head of a singly-linked list as input and reverses the list.\n\n# Approach\n\n1. Check if the head is NULL. If it is, it means the list is empty, so we return the head as it is.\n\n2. Create two pointers, "current" and "previous," and initialize "current" with the head of the list and "previous" with NULL.\n\n3. Enter a loop that continues until "current" becomes NULL.\n\n4. Inside the loop, create a temporary pointer, "temp," and store the next node of the current node.\n\n5. Set the "next" pointer of the current node to the previous node, effectively reversing the pointer direction.\n\n6. Update the "previous" pointer to the current node.\n\n7. Update the "current" pointer to the next node (stored in "temp") for the next iteration.\n\n8. Once the loop finishes, all the pointers have been reversed, and the "previous" pointer will be pointing to the new head of the reversed list.\n\n9. Return the "previous" pointer as the new head of the reversed list.\n\n# Complexity\n- Time complexity: O(n), where n is the number of nodes in the linked list, as we need to traverse the entire list once.\n\n- Space complexity: O(1) as we are using a constant amount of extra space to store the pointers.\n\n# C++\n```cpp\nclass Solution {\npublic:\n ListNode* reverseList(ListNode* head) {\n if(head==NULL){\n return head;\n }\n ListNode* current=head;\n ListNode* previous=NULL;\n while(current!=NULL){\n ListNode* temp = current->next;\n current->next=previous;\n previous=current;\n current=temp;\n }\n return previous;\n }\n};\n```\n# JAVA\n```java\nclass Solution {\n public ListNode reverseList(ListNode head) {\n if (head == null) {\n return head;\n }\n \n ListNode current = head;\n ListNode previous = null;\n \n while (current != null) {\n ListNode temp = current.next;\n current.next = previous;\n previous = current;\n current = temp;\n }\n \n return previous;\n }\n}\n```\n# JavaScript\n```js\nvar reverseList = function(head) {\n if (head === null) {\n return head;\n }\n \n let current = head;\n let previous = null;\n \n while (current !== null) {\n let temp = current.next;\n current.next = previous;\n previous = current;\n current = temp;\n }\n \n return previous;\n};\n```\n# Python\n```py\nclass Solution(object):\n def reverseList(self, head):\n if head is None:\n return head\n \n current = head\n previous = None\n \n while current is not None:\n temp = current.next\n current.next = previous\n previous = current\n current = temp\n \n return previous\n```
11
0
['Linked List', 'Python', 'C++', 'Java', 'JavaScript']
1
reverse-linked-list
[Python] EASY-understanding, Clear and Intuitive with illustration☝️🖼🖍 for beginners
python-easy-understanding-clear-and-intu-dj53
Given a linked list: \n\n\t 0\uFE0F\u20E3 \u279D 1\uFE0F\u20E3 \u279D 2\uFE0F\u20E3 \u279D 3\uFE0F\u20E3 \u279D 4\uFE0F\u20E3\n\t \u261D\uFE0E\n\thead\n\n\nFrom
ziaiz-zythoniz
NORMAL
2022-05-13T09:27:31.540748+00:00
2022-05-14T03:48:19.933404+00:00
547
false
Given a linked list: \n```\n\t 0\uFE0F\u20E3 \u279D 1\uFE0F\u20E3 \u279D 2\uFE0F\u20E3 \u279D 3\uFE0F\u20E3 \u279D 4\uFE0F\u20E3\n\t \u261D\uFE0E\n\thead\n```\n\nFrom a beginner\'s point of view, what we need to do is:\n\n_________________________________________________________\n\n**Step 0. Initialize the new linked list with an empty head, `reversed_head`**\n\n```\nreversed_head = None\n```\n\n_________________________________________________________\n **Step 1. Break the original link between the current `head` and `head.next`**\n\n0\uFE0F\u20E3 \u21CF 1\uFE0F\u20E3 \u279D 2\uFE0F\u20E3 \u279D 3\uFE0F\u20E3 \u279D 4\uFE0F\u20E3\n\n***by cutting the original list into two seperate linked lists***\n\u21E4 0\uFE0F\u20E3 ..../.... 1\uFE0F\u20E3 \u219B 2\uFE0F\u20E3 \u279D 3\uFE0F\u20E3 \u279D 4\uFE0F\u20E3\n... \u261D\uFE0E ......... \u270C\uFE0F ~~(head.next)~~`next_head` \u279D remaining of original list\n....~~(head)~~`reversed_head` \u279D new reversed list building up\n\n\n_________________________________________________________\n\n* ***1.1 set current `head.next` as the new head for the linked list on the right, using the second pointer \u270C\uFE0F, name it `nexthead`*** \n\u21E4 0\uFE0F\u20E3 ..../.... 1\uFE0F\u20E3 \u279D 2\uFE0F\u20E3 \u279D 3\uFE0F\u20E3 \u279D 4\uFE0F\u20E3\n... \u261D\uFE0E ......... \u270C\uFE0F ~~(head.next)~~`next_head`\n(head)\n\n\n\n\n* ***1.2 update `head.next`, to `reversedhead`, break the original link, prepare for next new head of the new reversed list***\n\u2205\n\uD83E\uDD0C\n(head.next)\n__\n\u2205 \u290E 0\uFE0F\u20E3 ..../.... 1\uFE0F\u20E3 \u219B 2\uFE0F\u20E3 \u279D 3\uFE0F\u20E3 \u279D 4\uFE0F\u20E3 \n...... \u261D\uFE0E ......... \u270C\uFE0F ~~(head.next)~~`next_head` \n....(head)\n\n\n\n\n\n* ***1.3 set `reversedhead`, the head of the new linked list, to the first pointer\u261D\uFE0E\'s, `head`\'s value***\n\u21E4 0\uFE0F\u20E3 ..../.... 1\uFE0F\u20E3 \u219B 2\uFE0F\u20E3 \u279D 3\uFE0F\u20E3 \u279D 4\uFE0F\u20E3\n... \u261D\uFE0E ..........\u270C\uFE0F ~~(head.next)~~`next_head`\n~~(head)~~ `reversed_head` \n\n\n\n\n\n* ***1.4 push the first pointer \u261D\uFE0E onward, to the its origianl `next`, prepare for next iteration***\n\u21E4 0\uFE0F\u20E3 ..../.... 1\uFE0F\u20E3 \u279D 2\uFE0F\u20E3 \u279D 3\uFE0F\u20E3 \u279D 4\uFE0F\u20E3\n................. \u261D\uFE0E \n.............. (head)\n\n\n\n\n_________________________________________________________\n### **Step 2. Keep repeating above steps until traversed**\n#### ***keep detaching the head from the original list, and attaching it as new head to the new reversed list , until there is now more `head` in the original list***\n\n#### ***Detailed illustration of next iteration:***\n\u21E4 0\uFE0F\u20E3 ..../.... 1\uFE0F\u20E3 \u279D 2\uFE0F\u20E3 \u279D 3\uFE0F\u20E3 \u279D 4\uFE0F\u20E3\n................. \u261D\uFE0E \n.............. (head)\n\n\u21E9\n\n\u21E4 0\uFE0F\u20E3 ..../.... 1\uFE0F\u20E3 \u219B 2\uFE0F\u20E3 \u279D 3\uFE0F\u20E3 \u279D 4\uFE0F\u20E3\n.................. \u261D\uFE0E ... \u270C\uFE0F ~~(head.next)~~`next_head`\n.............. (head)\n\n\u21E9\n\n 0\uFE0F\u20E3 \n\uD83E\uDD0C\n(head.next)\n\n\u21E4 0\uFE0F\u20E3 \u290E 1\uFE0F\u20E3 .../... 2\uFE0F\u20E3 \u219B 3\uFE0F\u20E3 \u279D 4\uFE0F\u20E3\n........... \u261D\uFE0E ....... \u270C\uFE0F ~~(head.next)~~`next_head`\n........ (head)\n\n\u21E9\n\n\u21E4 0\uFE0F\u20E3 \u290E 1\uFE0F\u20E3 ......... 2\uFE0F\u20E3 \u219B 3\uFE0F\u20E3 \u279D 4\uFE0F\u20E3\n............\u261D\uFE0E........... \u270C\uFE0F ~~(head.next)~~`next_head`\n........ ~~(head)~~ `reversed_head` \n\n\u21E9\n\n\u21E4 0\uFE0F\u20E3 \u290E 1\uFE0F\u20E3 ......... 2\uFE0F\u20E3 \u279D 3\uFE0F\u20E3 \u279D 4\uFE0F\u20E3\n........................... \u261D\uFE0E \n........................ (head)\n\n\n_________________________________________________________\n### ***Further iterations***:\n\u267B\uFE0F\u2674\n\u21E4 0\uFE0F\u20E3 \u290E 1\uFE0F\u20E3 \u290E 2\uFE0F\u20E3 ........ \u279D 3\uFE0F\u20E3 \u279D 4\uFE0F\u20E3\n....................\u261D\uFE0E........... \u270C\uFE0F ~~(head.next)~~`next_head`\n........ ~~(head)~~ `reversed_head` \n\u267B\uFE0F\u2675\n\u21E4 0\uFE0F\u20E3 \u290E 1\uFE0F\u20E3 \u290E 2\uFE0F\u20E3 \u290E 3\uFE0F\u20E3 ........ 4\uFE0F\u20E3\n........................... \u261D\uFE0E ........ \u270C\uFE0F ~~(head.next)~~`next_head`\n....................... ~~(head)~~ `reversed_head` \n\u267B\uFE0F\u2676\n\u21E4 0\uFE0F\u20E3 \u290E 1\uFE0F\u20E3 \u290E 2\uFE0F\u20E3 \u290E 3\uFE0F\u20E3 \u290E 4\uFE0F\u20E3\n................................... \u261D\uFE0E.... \u270C\uFE0F ~~(head.next)~~`next_head`\n............................... ~~(head)~~ `reversed_head` \n\uD83D\uDED1\n\n_________________________________________________________\n### **Step by step solution:**\n```\nclass Solution:\n def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:\n reversed_head = None\n \n while head:\n next_head = head.next\n head.next = reversed_head\n reversed_head = head \n head = next_head\n \n return reversed_head \n```\n\n_________________________________________________________\n## **4-line solution:**\nAs observed in while loops, the 4 linked assignment statements can be simplified using Python swap:\n```\nclass Solution:\n def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:\n reversed_head, next_head = None, head\n while head:\n head.next, reversed_head, head = reversed_head, head, head.next\n return reversed_head\n```\n\n\n_________________________________________________________\nI am also a beginner, writing these all out to help myself, and hopefully also help anyone out there who is like me at the same time. \n\nPlease upvote\u2B06\uFE0F if you find this helpful or worth-reading in anyway. Your upvote is more than just supportive to me. \uD83D\uDE33\uD83E\uDD13\uD83E\uDD70\n\nIf you find this is not helpful, needs improvement, or questionable, would you please leave a quick comment below to point out the problem before you decide to downvote? It will be very very helpful for me to learn as a beginner. \n\nThank you very much either way \uD83E\uDD13.
11
0
['Linked List', 'Two Pointers', 'Iterator', 'Python']
3
reverse-linked-list
Rust move-only solution
rust-move-only-solution-by-brainplot-uc26
rust\nimpl Solution {\n pub fn reverse_list(head: Option<Box<ListNode>>) -> Option<Box<ListNode>> {\n let mut prev: Option<Box<ListNode>> = None;\n
brainplot
NORMAL
2020-06-06T04:34:59.660027+00:00
2020-06-06T04:35:37.309496+00:00
867
false
```rust\nimpl Solution {\n pub fn reverse_list(head: Option<Box<ListNode>>) -> Option<Box<ListNode>> {\n let mut prev: Option<Box<ListNode>> = None;\n let mut curr = head;\n \n while let Some(mut boxed_node) = curr {\n let mut next = boxed_node.next.take();\n boxed_node.next = prev.take();\n prev = Some(boxed_node);\n curr = next.take();\n }\n \n prev\n }\n}\n```
11
0
['Rust']
2
reverse-linked-list
Python 3-liner to memorize for interviews (with mnemonic)
python-3-liner-to-memorize-for-interview-r2dk
I had an interview where I solved a LeetCode-medium problem in 15 minutes, but took 10-15 minutes to reverse a linked list in another problem because I kept stu
zemer
NORMAL
2018-10-23T21:20:16.883214+00:00
2018-10-25T21:55:30.328134+00:00
1,209
false
I had an interview where I solved a LeetCode-medium problem in 15 minutes, but took 10-15 minutes to reverse a linked list in another problem because I kept stumbling over stupid trivial things under pressure. I didn\'t get the job because the interviewer assumed I\'d seen the hard problem before but "couldn\'t even do simple things like reverse a linked list", which was completely unfair to me. But people suck and there\'s nothing that can be done about it. To be fair, I also sucked because I really should know how to reverse a linked list under pressure.\n\n---\n\nI got home and came up with these solutions in 2 minutes (they\'re very similar, just pick one):\n```python\ndef reverseList(head):\n prev = None\n while head: head.next, head, prev = prev, head.next, head\n return prev\n\ndef reverseList(head):\n prev = None\n while head: head.next, prev, head = prev, head, head.next\n return prev\n```\nIt sucks to suck. Don\'t be like me. If you\'re like me and struggle to write perfect code for simple things under pressure, I hope this helps you.\n\n---\n\nHere\'s an easy mnemonic for the body of the `while` loop. Imagine the linked list going from left to right, then you can think of the 3 relevant nodes as `0`, `1`, and `2`:\n```abc\n[prev] -> [head] -> [head.next]\n 0 1 2\n```\nThe assignment in the `while` loop can be thought of as a cycle `2 <- 0 <- 1 <- 2` (where `a <- b` means "assign `b` to `a`"):\n```abc\n2, 1, 0 = 0, 2, 1\n\nor\n\n2, 0, 1 = 0, 1, 2\n```\nThe important thing is that `head.next = prev` _must_ be the first assignment. The other 2 assignments can be done in any order.
11
0
[]
2
reverse-linked-list
Beats 100% || Best Solution Recursion🔥|| HandWritten Notes++ || Java, C++, Python
beats-100-best-solution-recursion-handwr-cq6r
Intuition & Approach ComplexityCode
VIBHU_DIXIT
NORMAL
2025-03-13T03:28:14.959874+00:00
2025-03-13T03:28:14.959874+00:00
603
false
# Intuition & Approach ![1.jpg](https://assets.leetcode.com/users/images/3c6727e2-9e1b-4a93-ba0c-539ceb78650c_1741836357.0098286.jpeg) ![2.jpg](https://assets.leetcode.com/users/images/47933783-8a04-4eb6-b618-e977f6d732db_1741836369.6006374.jpeg) # Complexity ![image.png](https://assets.leetcode.com/users/images/8d7c1e01-cd5c-4c80-8556-2e4c57f54c15_1741836330.221157.png) # Code ```java [] class Solution { public ListNode reverseList(ListNode head) { if(head==null || head.next==null) return head; ListNode last = reverseList(head.next); head.next.next = head; head.next = null; return last; } } ``` ```c++ [] class Solution { public: ListNode* reverseList(ListNode* head) { // Base case: if the list is empty or has only one node, return head if (head == nullptr || head->next == nullptr) { return head; } // Recursive call to reverse the rest of the list ListNode* last = reverseList(head->next); // Reverse the current node head->next->next = head; // Make the next node point to the current node head->next = nullptr; // Break the original link to avoid cycles // Return the new head of the reversed list return last; } }; ``` ```python [] # Definition for singly-linked list node class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def reverseList(self, head: ListNode) -> ListNode: # Base case: if the list is empty or has only one node, return head if not head or not head.next: return head # Recursive call to reverse the rest of the list last = self.reverseList(head.next) # Reverse the current node head.next.next = head # Make the next node point back to the current node head.next = None # Break the original link to avoid cycles # Return the new head of the reversed list return last ``` ![ok.png](https://lh6.googleusercontent.com/proxy/c1LeLv7686Z3O0EwMYz1lmGtbXDKOiBX-BuRnwKeGTNuZe0BvX8zRUkiGoFz8uYyPzx4HakbmPxP_Vtd0EUIAPOoej-NiUQub0ONve7eniMitSoN-mHyAeT499TCJF8KA1cTRUiEqyg4MoHYvmeuJGxj-ssy)
10
1
['Linked List', 'Recursion', 'Python', 'C++', 'Java']
0
reverse-linked-list
Beats 100% 🚀➡️Full Solution Explained with Dry Run ➡️[Java/C++/Python/Rust/JavaScript/Go]
beats-100-full-solution-explained-with-d-q81p
Approach Iterative\nStep 1: Initialize Pointers\n- Initialize a pointer prev to null. This will eventually point to the new head of the reversed list.\n\nStep 2
Shivansu_7
NORMAL
2024-03-21T04:12:33.854516+00:00
2024-03-21T04:12:33.854547+00:00
1,555
false
# Approach Iterative\n**Step 1: Initialize Pointers**\n- Initialize a pointer `prev` to `null`. This will eventually point to the new head of the reversed list.\n\n**Step 2: Iterate Through the List**\n- Begin iterating through the original list starting from the `head` node.\n\n**Step 3: Reverse Pointers**\n- Inside the loop:\n - Store the next node of the current `head` in a temporary variable `next`.\n - Reverse the link of the current `head` node to point to the `prev` node.\n - Move `prev` to the current `head`.\n - Move `head` to the next node stored in the `next` variable.\n\n**Step 4: Repeat Until End of List**\n- Repeat Step 3 until `head` becomes `null`, indicating the end of the original list.\n\n**Step 5: Return Reversed List**\n- Return `prev` as the new head of the reversed list.\n\n![RGIF2.gif](https://assets.leetcode.com/users/images/15648b28-6b8f-457e-8cbf-5e65e48c99e9_1710993935.3556094.gif)\n\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(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```Java []\nclass Solution {\n public ListNode reverseList(ListNode head) {\n ListNode dummy = null;\n while(head!=null) {\n ListNode next = head.next;\n head.next = dummy;\n dummy = head;\n head = next;\n }\n return dummy;\n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n ListNode* reverseList(ListNode* head) {\n ListNode* dummy = nullptr;\n while (head != nullptr) {\n ListNode* next = head->next;\n head->next = dummy;\n dummy = head;\n head = next;\n }\n return dummy;\n }\n};\n```\n```Go []\nfunc reverseList(head *ListNode) *ListNode {\n var dummy *ListNode\n for head != nil {\n next := head.Next\n head.Next = dummy\n dummy = head\n head = next\n }\n return dummy\n}\n```\n```Rust []\nimpl Solution {\n pub fn reverse_list(head: Option<Box<ListNode>>) -> Option<Box<ListNode>> {\n let mut dummy = None;\n let mut current = head;\n while let Some(mut node) = current {\n let next = node.next.take();\n node.next = dummy.take();\n dummy = Some(node);\n current = next;\n }\n dummy\n }\n}\n```\n```C# []\npublic class Solution {\n public ListNode ReverseList(ListNode head) {\n ListNode dummy = null;\n while (head != null) {\n ListNode next = head.next;\n head.next = dummy;\n dummy = head;\n head = next;\n }\n return dummy;\n }\n}\n```\n```Python3 []\nclass Solution:\n def reverseList(self, head: ListNode) -> ListNode:\n dummy = None\n while head:\n next_node = head.next\n head.next = dummy\n dummy = head\n head = next_node\n return dummy\n```\n```JavaScript []\n * @param {ListNode} head\n * @return {ListNode}\n */\nvar reverseList = function(head) {\n let dummy = null;\n while (head !== null) {\n let next = head.next;\n head.next = dummy;\n dummy = head;\n head = next;\n }\n return dummy;\n};\n```\n\n---\n\n## ***FEEL FREE TO POST RECURSIVE SOLUTION IN COMMENTS***\n\n---\n\n
10
0
['C', 'Python', 'C++', 'Java', 'Go', 'Python3', 'Rust', 'JavaScript', 'C#']
4
reverse-linked-list
Idiomatic Rust with Recursion ✅ analysis
idiomatic-rust-with-recursion-analysis-b-kzuf
Intuition\n1. encounter a node \n2. If node is None, return prev.\n3. save its next node as tmp\n4. swap its next and prev\n5. move to tmp and do 1\n\n# Approac
LSTM-VinDiesel
NORMAL
2023-02-09T00:31:17.249688+00:00
2024-09-06T07:38:29.208555+00:00
992
false
# Intuition\n1. encounter a node \n2. If node is None, return prev.\n3. save its next node as tmp\n4. swap its next and prev\n5. move to tmp and do 1\n\n# Approach\nRecursion: using the call-stack\nThe std::mem::replace in Rust nicely combines 3/4\nThe `match` syntax bit does 2/3\nCould also use `if let` and `else` instead of `match`\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n\nEdit: Sep-2024\nI didn\'t know why I put Space O(1) there. It\'s O(n) because of recursion itself.\n\nRecursive calls are thrown into a stack, innit. Every call increases it by 1 before they all get cleared when conditions are met\n\nAnyways, I stopped using Rust, gave up serious programming and became a JavaScript web dev. Peace\n\n\n# Code\n```\ntype T = Option<Box<ListNode>>;\nimpl Solution {\n pub fn reverse_list(head: T) -> T {\n cur_prev(head, None)\n }\n}\n\nfn cur_prev(cur: T, prev: T) -> T{\n match cur{\n Some(mut node) => cur_prev(std::mem::replace(&mut node.next, prev), Some(node)),\n None => prev\n }\n}\n```
10
0
['Recursion', 'Rust']
2
reverse-linked-list
Python || 93.68% Faster || Iterative || O(n) Solution
python-9368-faster-iterative-on-solution-xvh0
\nclass Solution:\n def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:\n if head==None or head.next==None: return head\n pr
pulkit_uppal
NORMAL
2022-11-26T14:35:55.342343+00:00
2022-11-26T14:35:55.342366+00:00
1,769
false
```\nclass Solution:\n def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:\n if head==None or head.next==None: return head\n prev,curr,temp=head,head.next,head.next.next\n prev.next=None\n while temp:\n curr.next=prev\n prev=curr\n curr=temp\n temp=temp.next\n curr.next=prev\n return curr\n```\n\n**An upvote will be encouraging**
10
0
['Linked List', 'Iterator', 'Python', 'Python3']
0
reverse-linked-list
Java 0ms 100% Faster | Recursion | Easy | Intution Explained
java-0ms-100-faster-recursion-easy-intut-zz7g
Intution : We have to manipulate (reverse) the pointer of the linked list, in order to reverse the entire linked list.\nRecursive Intution : We\'ll reverse one
iamharshpathak
NORMAL
2022-05-11T05:12:07.870756+00:00
2022-05-11T05:12:44.511675+00:00
763
false
***Intution : We have to manipulate (reverse) the pointer of the linked list, in order to reverse the entire linked list.\nRecursive Intution : We\'ll reverse one pointer, others will be done by the function itself (recursive leap of faith ) !***\n\n```\nclass Solution {\n public ListNode reverseList(ListNode head) {\n ListNode prev=null; //previous pointer\n ListNode cPtr = head; //current pointer\n ListNode nxt = null; //head pointer\n \n return reverse (cPtr, prev, nxt);\n }\n \n public ListNode reverse(ListNode cPtr, ListNode prev, ListNode nxt){\n if(cPtr == null){ //base condition\n return prev;\n }\n nxt = cPtr.next;\n cPtr.next = prev;\n prev = cPtr; \n cPtr = nxt;\n \n return reverse(cPtr, prev, nxt);\n }\n}\n```\n\n**Perform a dry run for better understanding !\nHappy Coding !\nDo Upvote if it helped !**
10
0
['Recursion', 'Java']
0
reverse-linked-list
C++ Simplest Iterative Approach
c-simplest-iterative-approach-by-ayushma-0xgq
\nclass Solution {\npublic:\n ListNode reverseList(ListNode head) {\n \n ListNode previous = NULL;\n ListNode current = head;\n L
AyushMaheshwari
NORMAL
2022-01-05T15:57:47.842751+00:00
2022-01-05T15:57:47.842793+00:00
556
false
\nclass Solution {\npublic:\n ListNode* reverseList(ListNode* head) {\n \n ListNode* previous = NULL;\n ListNode* current = head;\n ListNode* next;\n while(current != NULL)\n {\n next = current -> next;\n current -> next = previous;\n \n previous = current;\n current = next;\n }\n return previous;\n }\n};
10
0
['Linked List', 'C', 'Iterator']
0
reverse-linked-list
C#
c-by-rajeevarakkal-jlbe
Runtime: 92 ms, faster than 72.27% of C# online submissions for Reverse Linked List.\nMemory Usage: 25.2 MB, less than 40.36% of C# online submissions for Rever
rajeevarakkal
NORMAL
2021-06-29T15:16:27.111916+00:00
2021-06-29T15:16:27.111966+00:00
4,450
false
Runtime: 92 ms, faster than 72.27% of C# online submissions for Reverse Linked List.\nMemory Usage: 25.2 MB, less than 40.36% of C# online submissions for Reverse Linked List.\n\n```\n/**\n * Definition for singly-linked list.\n * public class ListNode {\n * public int val;\n * public ListNode next;\n * public ListNode(int val=0, ListNode next=null) {\n * this.val = val;\n * this.next = next;\n * }\n * }\n */\npublic class Solution {\n public ListNode ReverseList(ListNode head) {\n \n if(head == null) return head;\n \n //Auctually we will have to reverse the link direction only\n //1 -> 2 -> 3 -> null(tail) To (null)<-1 <- 2 <-3\n \n \n ListNode prev_node = null;\n \n //iterate through list till the end, change link direction (next) of each item \n //point to just before node (previos)\n while(head != null){\n ListNode next_node = head.next; // 2 , kept a track of next item\n head.next = prev_node; //direction changed right to left\n //This also means head is now broke link to its earlier next ie 2\n //(null) <- 1 2\n // prev_node, head, next_node all one step right\n prev_node = head; //1\n head = next_node; //2 \n //first line #26 will take care of sliding of next_node \n }\n \n //finally now retrun the prev_node, which is reversed ie head is at 3\n return prev_node;\n \n \n \n }\n}\n```\n\n
10
0
[]
1
reverse-linked-list
PYTHON CODE WITH FULL DETAILED EXPLANATIONS
python-code-with-full-detailed-explanati-584e
The comments are already added regarding the logic although its pretty staright forward and simple\n\n # SO bacially we will take 3 pointers one is \n
shubhamverma2604
NORMAL
2021-03-25T15:58:38.202189+00:00
2021-03-25T15:58:38.202231+00:00
1,020
false
The comments are already added regarding the logic although its pretty staright forward and simple\n\n # SO bacially we will take 3 pointers one is \n #curr = head\n #prev\n #next i.e. curr.next coz if we will directly point our curr.next to prev then we loose connection with curr.next\n \n \n curr = head\n next = None\n prev = None\n \n while curr!=None:\n #firstly initalize next\n next = curr.next\n \n #now prev\n curr.next = prev\n \n \n #Also keep updating the prev so that we know what is the prev element to curr\n \n prev = curr\n \n \n #Now update curr as next --> which current.next\n curr = next\n \n # returning prev beacuse when curr = None and next is None then we are left with prev \n return prev\n\t\t\n**UPVOTE IF YOU FIND IT HELPFUL**
10
2
['Linked List', 'Python', 'Python3']
0
reverse-linked-list
Go
go-by-dynasty919-fwk3
\nfunc reverseList(head *ListNode) *ListNode {\n var front *ListNode\n mid, end := head, head\n for mid != nil {\n end = mid.Next\n mid.N
dynasty919
NORMAL
2020-03-12T06:39:20.079773+00:00
2020-03-12T06:39:20.079821+00:00
1,034
false
```\nfunc reverseList(head *ListNode) *ListNode {\n var front *ListNode\n mid, end := head, head\n for mid != nil {\n end = mid.Next\n mid.Next = front\n front, mid = mid, end\n }\n return front\n}\n```
10
0
[]
2
reverse-linked-list
JavaScript - Iterative & Recursive
javascript-iterative-recursive-by-grs-p47k
Iterative\n\n/**\n * @param {ListNode} head\n * @return {ListNode}\n */\nvar reverseList = function(head) {\n let prev = null;\n while (head) {\n c
grs
NORMAL
2019-07-20T09:50:43.458359+00:00
2019-07-20T09:50:43.458396+00:00
1,110
false
**Iterative**\n```\n/**\n * @param {ListNode} head\n * @return {ListNode}\n */\nvar reverseList = function(head) {\n let prev = null;\n while (head) {\n const next = head.next;\n const curr = head;\n curr.next = prev;\n head = next;\n prev = curr;\n }\n \n return prev;\n};\n```\n\n**Recursive**\n```\n/**\n * @param {ListNode} head\n * @return {ListNode}\n */\nvar reverseList = function(head, prev = null) {\n if (head === null) {\n return null;\n }\n const next = reverseList(head.next, head);\n head.next = prev;\n return next || head;\n \n};\n```
10
0
[]
0
reverse-linked-list
Share my Accepted Java solution - iteratively and recursively:
share-my-accepted-java-solution-iterativ-w879
Iteratively:\n\n public ListNode reverseList(ListNode head) {\n if(head == null || head.next == null)\n return head;\n L
sammy89
NORMAL
2015-07-25T21:39:09+00:00
2015-07-25T21:39:09+00:00
1,648
false
**Iteratively:**\n\n public ListNode reverseList(ListNode head) {\n if(head == null || head.next == null)\n return head;\n ListNode pre = null;\n ListNode curr = head;\n while(curr != null){\n ListNode next = curr.next;\n curr.next = pre;\n pre = curr;\n curr = next;\n }\n return pre;\n }\n\n**Recursively:**\n\n public class Solution { \n public ListNode reverseList(ListNode head) { \n if(head == null || head.next == null) \n return head; \n ListNode second = head.next; \n head.next = null; \n ListNode newHead = reverseList(second); \n second.next = head; \n return newHead; \n } \n }\n\nAny suggestions for improvements are welcome.
10
0
['Java']
3
reverse-linked-list
Ac solution code
ac-solution-code-by-cheng_zhang-lx9n
Solution1. Iterative Solution\n\n public ListNode reverseList(ListNode head) {\n \tListNode prev = null, curr = head;\n \twhile (curr != null) { \n
cheng_zhang
NORMAL
2016-01-11T05:28:21+00:00
2016-01-11T05:28:21+00:00
877
false
**Solution1. Iterative Solution**\n\n public ListNode reverseList(ListNode head) {\n \tListNode prev = null, curr = head;\n \twhile (curr != null) { \n \t ListNode next = curr.next;// Save current's next \n \t\tcurr.next = prev;// Point current.next to prev\n \t\tprev = curr;// Set the current node as prev\n \t\tcurr = next;// Forward current node to next \n \t}\n \treturn prev;\n }\n\n**Solution2. Recursive Solution**\n \n public ListNode reverseList(ListNode head) {\n \treturn reverseList(head, null);\n }\t \n public ListNode reverseList(ListNode curr, ListNode prev) {\n \tif (curr == null) return prev;\n \tListNode next = curr.next;// Save current's next \n \tcurr.next = prev;// Point current.next to prev\n \treturn reverseList(next, curr);// // Forward current node to next; Set the current node as prev\n }
10
0
[]
1
reverse-linked-list
Easy✅JAVA&C++&JAVASCRIPT|| 🗓️ Daily LeetCoding Challenge Day 4✅🔥
easyjavacjavascript-daily-leetcoding-cha-b19x
I hope a nice day for u!!\njava []\nclass Solution {\n public ListNode reverseList(ListNode head) {\n return reverse(head);\n }\n private ListNo
DoaaOsamaK
NORMAL
2024-03-21T07:16:32.702205+00:00
2024-03-21T07:19:22.928600+00:00
895
false
I hope a nice day for u!!\n```java []\nclass Solution {\n public ListNode reverseList(ListNode head) {\n return reverse(head);\n }\n private ListNode reverse(ListNode head){\n ListNode curr = head, prev = null;\n while(curr != null){\n ListNode nextNode = curr.next;\n curr.next = prev;\n prev = curr;\n curr = nextNode;\n }\n return prev;\n }\n}\n```\n```javascript []\nvar reverseList = function(head) {\n let prev = null;\n let curr = head;\n while (curr !== null) {\n let nextTemp = curr.next;\n curr.next = prev;\n prev = curr;\n curr = nextTemp;\n }\n return prev;\n};\n```\n```cpp []\nclass Solution {\npublic:\n ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr;\n ListNode* curr = head;\n while (curr != nullptr) {\n ListNode* nextTemp = curr->next;\n curr->next = prev;\n prev = curr;\n curr = nextTemp;\n }\n return prev;\n }\n};\n```\n
9
0
['C++', 'Java', 'JavaScript']
1
reverse-linked-list
🔥Simple C++ Solution || using 3 pointer || iterative 🔥
simple-c-solution-using-3-pointer-iterat-xkr9
\n Describe your approach to solving the problem. \n\n\n Add your time complexity here, e.g. O(n) \n\n\n Add your space complexity here, e.g. O(n) \n\n# Code\n\
rishav_raj_16
NORMAL
2023-02-12T14:26:42.658375+00:00
2024-06-10T11:29:41.053462+00:00
932
false
\n<!-- Describe your approach to solving the problem. -->\n\n\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode() : val(0), next(nullptr) {}\n * ListNode(int x) : val(x), next(nullptr) {}\n * ListNode(int x, ListNode *next) : val(x), next(next) {}\n * };\n */\n\n// if it helps plzz upvote it \uD83D\uDE09\nclass Solution {\npublic:\n ListNode* reverseList(ListNode* head) {\n ListNode* prev = NULL;\n ListNode* curr=head;\n while(curr){\n ListNode* next=curr->next;\n curr->next=prev;\n prev=curr;\n curr=next;\n }\n return prev;\n }\n};\n// if it helps plzz upvote it \uD83D\uDE09\n```
9
0
['Linked List', 'C']
0
reverse-linked-list
Python [Iterative: Beats 99% || Recursive: Beats 87%] with full working explanation
python-iterative-beats-99-recursive-beat-0kfs
Iterative\n\nclass Solution:\n def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]: # Time: O(n) and Space: O(1)\n prev, cur = None
DanishKhanbx
NORMAL
2022-08-12T11:12:46.514285+00:00
2022-08-12T11:12:46.514379+00:00
1,321
false
# Iterative\n```\nclass Solution:\n def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]: # Time: O(n) and Space: O(1)\n prev, cur = None, head\n while cur: # let cur 3 \n temp = cur.next # nxt = 4\n cur.next = prev # 3 -> 2\n prev = cur # prev = 3\n cur = temp # 5 <- cur(4) <- 3(prev) -> 2 -> 1 -> Null\n return prev\n```\nFor example,\nLet **head = [1, 2, 3, 4, 5]**\n1. prev = None\n1. cur = head[0]=1\n1. while cur=1,2,3,4,5 = True:\n* cur=1: temp = 1.nxt=2 --> 1.next = None --> prev = 1 --> cur = 2 i.e. 1(prev) -> Null then 2(cur)\n* cur=2: temp = 2.nxt=3 --> 2.next = 1 --> prev = 2 --> cur = 3 i.e. 2(prev) -> 1 -> Null then 3(cur)\n* cur=3: temp = 3.nxt=4 --> 3.next = 2 --> prev = 3 --> cur = 4 i.e. 3(prev) -> 2 -> 1 -> Null then 4(cur)\n* cur=4: temp = 4.nxt=5 --> 4.next = 3 --> prev = 4 --> cur = 5 i.e. 4(prev) -> 3 -> 2 -> 1 -> Null then 5(cur)\n* cur=5: temp = 5.nxt=Null --> 5.next = 4 --> prev = 5 --> cur = Null i.e. 5(prev) -> 4 -> 3 -> 2 -> 1 -> Null then Null(cur)\n4. Return the first node i.e. **prev = 5.**\n# Recursive\n```\nclass Solution:\n def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]: # Time: O(n) and Space: O(n)\n if head == None or head.next == None: # head = 2 & 2 -> 3\n return head\n\n newHead = self.reverseList(head.next) # newHead = Func(head=3) returns head = 3\n head.next.next = head # head.next = 3 & 3.next = 2\n head.next = None # 2.next = None\n return newHead # returns newHead = 3 to when head = 1, and so on\n```\nFor example,\nLet **head = [1, 2, 3]**\n* reverse(1):\n * if head == None or head.next == None = False\n * newHead = self.reverseList(2)\n* reverse(2):\n * if head == None or head.next == None = False\n * newHead = self.reverseList(3) = { if head == None or head.next == None = True: return 3 }\n * head.next.next i.e 3.next = 2 --> 2.next = None --> return newHead=3\n* --> reverse(1) \n * newHead = 3 --> 2.next = 1 --> 1.next = None --> return newHead=3
9
0
['Recursion', 'Python', 'Python3']
1
reverse-linked-list
Python3 3 Solutions iterative, recursive, and stack.
python3-3-solutions-iterative-recursive-l8vob
The three solutions contains stack, recursive, iterative solution\nyou can clearly see the best runtime, I\'ve got is come with stack, but we can do better, wit
arshergon
NORMAL
2022-05-21T14:35:44.846981+00:00
2022-05-21T14:35:44.847011+00:00
778
false
The three solutions contains stack, recursive, iterative solution\nyou can clearly see the best runtime, I\'ve got is come with stack, but we can do better, with O(1) memory, leetcode servers result comes different everytime you hit submit.\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 reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:\n return self.reverseWithStack(head) \n # return self.iterativeReverse(head)\n # return self.recursiveReverse(head)\n \n # O(N) || O(1)\n # Runtime: 45ms 61.29%\n def iterativeReverse(self, head):\n if not head:\n return head\n \n prev = None\n while head is not None:\n next = head.next\n head.next = prev\n prev = head\n head = next\n \n return prev\n \n # O(N) || O(N)\n # Runtime: 50ms 47.81%\n def recursiveReverse(self, head):\n if not head:\n return head\n if not head.next:\n return head\n \n newHead = self.recursiveReverse(head.next)\n head.next.next = head\n head.next = None\n \n return newHead\n \n # O(N) || O(N)\n # Runtime: 33ms 94.92% \n def reverseWithStack(self, head):\n if not head:\n return head\n \n stack = []\n newHead = head\n while newHead is not None:\n stack.append(newHead.val)\n newHead = newHead.next\n \n newHead = head\n \n for i in range(len(stack)):\n newHead.val = stack.pop()\n newHead = newHead.next\n return head\n```
9
0
['Stack', 'Python', 'Python3']
0
minimum-number-of-taps-to-open-to-water-a-garden
[Java] A general greedy solution to process similar problems
java-a-general-greedy-solution-to-proces-39dp
This problem is similiar to Jump game II and Video Stiching. Just summary a general idea to process this kind of problems for the conveninece of review in the f
bluecamel
NORMAL
2020-02-12T08:57:13.607399+00:00
2020-02-21T07:13:02.895381+00:00
29,528
false
This problem is similiar to **Jump game II** and **Video Stiching**. Just summary a general idea to process this kind of problems for the conveninece of review in the future. (Welcome supplement other similar ones, thanks in advance).\n\nFirst we need ensure that the array has been sorted by start time. Then say in each step, we have a range [left, right], which means we can only visit the elements within the range in this step. We keep checking the elements until we are at the rightmost postion in [left, right] to update "farCanReach" , which means the farthest we can reach in next step. \n\n\n[1024]. **Video Stitching** (https://leetcode.com/problems/video-stitching/)\n```\nclass Solution {\n public int videoStitching(int[][] clips, int T) {\n int end = 0, farCanReach = 0, cnt = 0;\n Arrays.sort(clips, (a, b) -> (a[0] - b[0])); // sort by start time\n if(clips[clips.length - 1][1] < T) return -1;\n for(int i = 0; end < T; end = farCanReach) { // at the beginning of each step, we need update the "end" \n cnt++; \n while(i < clips.length && clips[i][0] <= end) { // check all elements within the range\n farCanReach = Math.max(farCanReach, clips[i++][1]); // update the "farCanReach" for next step\n }\n if(end == farCanReach) return -1; \n\t\t\t// if "farCanReach" isn\'t updated after we checked all elements within the range, we will fail in next step. \n\t\t\t// say the first element in next step is [curS, curE], "curS" must be larger than "end" = "farCanReach".\n }\t\t\n return cnt;\n }\n}\n```\n\n[45]. **Jump Game II** (https://leetcode.com/problems/jump-game-ii/)\nIn this problem, the "left" in range [left, right] becomes the index of element. And the "right" becomes index + nums[index].\n```\nclass Solution {\n public int jump(int[] nums) {\n int cnt = 0, farCanReach = 0, end = 0;\n for(int i = 0; end < nums.length - 1; end = farCanReach) {\n cnt++;\n while(i < nums.length && i <= end) {\n farCanReach = Math.max(farCanReach, i + nums[i++]);\n } \n if(end == farCanReach) return -1;\n }\n return cnt;\n }\n}\n```\n\n[1326]. **Minimum Number of Taps to Open to Water a Garden** (https://leetcode.com/problems/minimum-number-of-taps-to-open-to-water-a-garden/)\nFor this problem, we just need construct a new array to move the value into the leftmost point we can water, so the problem becomes **Jump Game II**. For example, at index i we could water (i - arr[i]) ~ (i + arr[i]). So we store the farthest point we can water at "i - arr[i]". Then "left" in range [left, right] is index and "right" is the value in arr[index].\n```\nclass Solution {\n public int minTaps(int n, int[] ranges) {\n // construct the arr\n int[] arr = new int[n + 1];\n for(int i = 0; i < ranges.length; i++) {\n if(ranges[i] == 0) continue;\n int left = Math.max(0, i - ranges[i]);\n arr[left] = Math.max(arr[left], i + ranges[i]);\n }\n\t\t\n\t\t// same part like previous problem\n int end = 0, farCanReach = 0, cnt = 0; \n for(int i = 0; i < arr.length && end < n; end = farCanReach) {\n cnt++;\n while(i < arr.length && i <= end) {\n farCanReach = Math.max(farCanReach, arr[i++]); \n }\n if(end == farCanReach) return -1; \n }\n return cnt;\n }\n}\n```\n\n\n
499
4
[]
47
minimum-number-of-taps-to-open-to-water-a-garden
[Java/C++/Python] Similar to LC1024
javacpython-similar-to-lc1024-by-lee215-b59a
Intuition\nExample 2 did confuse me.\nWe actually need to water the whole segment, instead of n + 1 point.\nThe taps with value 0 can water nothing.\n\n\n# Solu
lee215
NORMAL
2020-01-19T04:01:06.771901+00:00
2020-01-23T12:30:11.300138+00:00
42,224
false
# Intuition\nExample 2 did confuse me.\nWe actually need to water the whole segment, instead of `n + 1` point.\nThe taps with value `0` can water nothing.\n<br>\n\n# Solution 1: Brute Force DP\n`dp[i]` is the minimum number of taps to water `[0, i]`.\nInitialize `dp[i]` with max = `n + 2`\n`dp[0] = [0]` as we need no tap to water nothing.\n\nFind the leftmost point of garden to water with tap `i`.\nFind the rightmost point of garden to water with tap `i`.\nWe can water `[left, right]` with onr tap,\nand water `[0, left - 1]` with `dp[left - 1]` taps.\n<br>\n\n# Complexity\nTime `O(NR)`, where `R = ranges[i] <= 100`\nSpace `O(N)`\n<br>\n\n**Java:**\n```java\n public int minTaps(int n, int[] A) {\n int[] dp = new int[n + 1];\n Arrays.fill(dp, n + 2);\n dp[0] = 0;\n for (int i = 0; i <= n; ++i)\n for (int j = Math.max(i - A[i] + 1, 0); j <= Math.min(i + A[i], n); ++j)\n dp[j] = Math.min(dp[j], dp[Math.max(0, i - A[i])] + 1);\n return dp[n] < n + 2 ? dp[n] : -1;\n }\n```\n\n**C++:**\n```cpp\n int minTaps(int n, vector<int>& A) {\n vector<int> dp(n + 1, n + 2);\n dp[0] = 0;\n for (int i = 0; i <= n; ++i)\n for (int j = max(i - A[i] + 1, 0); j <= min(i + A[i], n); ++j)\n dp[j] = min(dp[j], dp[max(0, i - A[i])] + 1);\n return dp[n] < n + 2 ? dp[n] : -1;\n }\n```\n\n**Python:**\n```python\n def minTaps(self, n, A):\n dp = [0] + [n + 2] * n\n for i, x in enumerate(A):\n for j in xrange(max(i - x + 1, 0), min(i + x, n) + 1):\n dp[j] = min(dp[j], dp[max(0, i - x)] + 1)\n return dp[n] if dp[n] < n + 2 else -1\n```\n<br>\n\n# Solution 2+: 1024. Video Stitching\nActually it\'s just a duplicate problem with a confusing description.\nSee this [1024. Video Stitching](https://leetcode.com/problems/video-stitching/discuss/270036/JavaC%2B%2BPython-Greedy-Solution-O(1)-Space)\nand its 3 different solutions.
262
17
[]
39
minimum-number-of-taps-to-open-to-water-a-garden
[Python] Jump Game II
python-jump-game-ii-by-kytabyte-pd5t
\nWe build a list max_range to store the max range it can be watered from each index. \n\nThen it becomes Jump Game II, where we want to find the minimum steps
kytabyte
NORMAL
2020-01-19T04:10:25.145866+00:00
2020-01-23T03:21:51.722791+00:00
13,122
false
\nWe build a list `max_range` to store the max range it can be watered from each index. \n\nThen it becomes [Jump Game II](https://leetcode.com/problems/jump-game-ii/), where we want to find the minimum steps to jump from `0` to `n`.\n\nThe only difference is Jump Game II guarantees we can jump to the last index but this one not. We need to additionally identify the unreachable cases.\n\n```python\nclass Solution:\n def minTaps(self, n: int, ranges: List[int]) -> int:\n max_range = [0] * (n + 1)\n \n for i, r in enumerate(ranges):\n left, right = max(0, i - r), min(n, i + r)\n max_range[left] = max(max_range[left], right - left)\n \n\t\t# it\'s a jump game now\n start = end = step = 0\n \n while end < n:\n step += 1\n start, end = end, max(i + max_range[i] for i in range(start, end + 1))\n if start == end:\n return -1\n \n return step\n```
203
0
[]
23
minimum-number-of-taps-to-open-to-water-a-garden
DP pattern to solve 3 similar problems
dp-pattern-to-solve-3-similar-problems-b-dh88
We can use the same DP pattern to solve the following 3 problems.\n\n 1326. Minimum Number of Taps to Open to Water a Garden\n\n public int minTaps(int[] range
chenzuojing
NORMAL
2020-06-30T06:38:59.514292+00:00
2021-08-03T21:15:09.958101+00:00
10,488
false
We can use the same DP pattern to solve the following 3 problems.\n\n* 1326. Minimum Number of Taps to Open to Water a Garden\n```\n public int minTaps(int[] ranges) {\n\t\tint len = ranges.length;\n\t\tint[] dp = new int[len]; \n\t\tArrays.fill(dp, len + 1); \n\t\tdp[0] = 0;\n\n\t\tfor (int i = 0; i < len; i++) {\n\t\t\tint start = Math.max(i - ranges[i], 0);\n\t\t\tint end = Math.min(i + ranges[i], len - 1);\n\t\t\tfor (int j = start; j <= end; j++) {\n\t\t\t\tdp[j] = Math.min(dp[j], dp[start] + 1);\n\t\t\t}\n\t\t}\n\n\t\treturn dp[len - 1] == len + 1 ? -1 : dp[len - 1];\n\t}\n```\n\n* 45. Jump Game II\n```\n\tpublic int jump(int[] nums) {\n\t\tint len = nums.length;\n\t\tint[] dp = new int[len];\n\t\tArrays.fill(dp, len + 1);\n\t\tdp[0] = 0;\n\n\t\tfor (int i = 0; i < len; i++) {\n\t\t\tint start = i;\n\t\t\tint end = Math.min(i + nums[i], len - 1);\n\t\t\tfor (int j = start; j <= end; j++) {\n\t\t\t\tdp[j] = Math.min(dp[j], dp[start] + 1);\n\t\t\t}\n\t\t}\n\n\t\treturn dp[len - 1] == len + 1 ? -1 : dp[len - 1];\n\t}\n\t\n```\n\n\n* 1024. Video Stitching\n```\n\tpublic int videoStitching(int[][] clips, int T) {\n\t\tint[] dp = new int[T + 1];\n\t\tArrays.fill(dp, T + 2);\n\t\tdp[0] = 0;\n\n\t\tfor (int i = 0; i <= T; i++) {\n\t\t\tfor (int[] clip : clips) {\n\t\t\t\tint start = clip[0];\n\t\t\t\tint end = clip[1];\n\t\t\t\tif (i >= start && i <= end)\n\t\t\t\t\tdp[i] = Math.min(dp[i], dp[start] + 1);\n\t\t\t}\n\t\t}\n\n\t\treturn dp[T] == T + 2 ? -1 : dp[T];\n\t}\n```\n
145
3
[]
9
minimum-number-of-taps-to-open-to-water-a-garden
✅ 99.5% Greedy with Dynamic + DP
995-greedy-with-dynamic-dp-by-vanamsen-mygc
Interview Guide - Minimum Number of Taps to Open to Water a Garden\n\n## Problem Understanding\n\n### Description\nAt its core, this problem is a fascinating bl
vanAmsen
NORMAL
2023-08-31T00:14:11.946782+00:00
2023-08-31T01:45:04.612085+00:00
15,370
false
# Interview Guide - Minimum Number of Taps to Open to Water a Garden\n\n## Problem Understanding\n\n### Description\nAt its core, this problem is a fascinating blend of interval merging and greedy optimization. You are provided with a one-dimensional garden and the ability to water certain intervals of it by opening taps located at different points. The goal is to water the entire garden with the minimum number of taps opened.\n\n---\n\n## Key Points to Consider\n\n### 1. Understand the Constraints\n- Garden Length: $$ 1 \\leq n \\leq 10^4 $$\n- Number of Taps: $$ n + 1 $$\n- Watering Range: $$ 0 \\leq \\text{ranges}[i] \\leq 100 $$\n\n### 2. Unveil the Significance of Intervals\nThe problem can be visualized as merging intervals. The operation to open a tap can be thought of as covering an interval within the garden. The challenge is to cover the entire garden with the least number of intervals. This applies to both the greedy and dynamic programming approaches.\n\n### 3. Algorithmic Approaches\nThis problem can be tackled using two different approaches: the Greedy Approach and the Dynamic Programming (DP) Approach.\n\n#### Greedy Approach in Context\nIn the greedy approach, the algorithm makes the best local choice at each decision point with the aim of finding a global optimum. In this problem, each tap you decide to open becomes a commitment to water a specific range in the garden. The greedy strategy here involves always picking the tap that extends your reach as far as possible. This approach is optimized for speed, aiming to solve the problem in the least amount of time.\n\n#### Dynamic Programming in Context\nDynamic Programming, on the other hand, builds the solution step by step. It uses an array to keep track of the minimum number of taps needed to water the garden up to each point. The DP approach is generally more flexible and can handle more complicated scenarios at the cost of potentially slower runtime for larger problem sizes.\n\n### 4. Key Concepts in Each Approach\n\n#### The Magic of "Farthest Reach" (Greedy)\nIn the greedy approach, the concept of "farthest reach" is crucial. As you move from the first to the last tap, this variable adapts dynamically, reflecting the furthest point that can be watered by any tap that intersects with the currently watered range. This dynamic updating is vital for deciding whether or not a new tap needs to be opened.\n\n#### The Power of Incremental Build-up (DP)\nIn the DP approach, the array essentially serves as a memoization table. Each element in the DP array signifies the minimum number of taps required to water the garden up to that point. This array gets updated iteratively as we consider each tap, forming the basis for the final solution.\n\n### 5. Importance of Ordered Intervals (Greedy)\nFor the greedy algorithm, it\'s beneficial to consider the taps in an ordered sequence, sorted by their starting points. This ordering helps make the local choices more straightforward and effective, thereby aiding in the search for a global optimum.\n\n### 6. Explain Your Thought Process\nRegardless of the approach, clear thinking and explanation are crucial. For the greedy approach, maintaining and updating the variable `far_can_reach` is key. In the DP approach, the DP array holds the minimum number of taps needed to water each point, and it\'s updated as we go through each tap.\n\n---\n\n# Live Coding & More\nhttps://youtu.be/UQ__VyptWPQ?si=NrC2tEc2X24SSCpZ\n\n---\n\n# Approach: Greedy Algorithm with Dynamic "Farthest Reach" Adjustment\n\n## Intuition and Logic Behind the Solution\nThe problem challenges us to water an entire one-dimensional garden using the fewest number of taps. Each tap has a range that it can water. The crux of our solution is to always choose the tap that allows us to water the farthest point in the garden that hasn\'t been watered yet.\n\n## Why Greedy?\nThe greedy approach works well in this situation because it aims to make the best local choices in the hope of reaching an optimal global solution. In this context, each local choice is to open a tap that extends our watering range as far as possible. By doing so, we minimize the total number of taps that need to be opened.\n\n## Step-by-step Explanation\n- **Initialization**: We initialize `end = 0`, `far_can_reach = 0`, and `cnt = 0`. Here, `end` represents the last point that can be watered by the previously considered taps, `far_can_reach` is the farthest point that can be watered by any tap considered so far, and `cnt` keeps track of the number of taps opened.\n \n- **Prepare the Ranges**: We prepare an array `arr` where the index represents the starting point, and the value at that index represents the farthest point that can be watered from that starting point.\n \n- **Main Algorithm**: We iterate through the array `arr`. If the current index `i` is greater than `end`, we update `end` to `far_can_reach` and increment `cnt` by 1. This is because we need to open a new tap to extend our reach.\n \n- **Check for Gaps**: If at any point we find that we can\'t extend our reach (`far_can_reach <= end`), we return -1.\n \n- **Count Taps**: `cnt` keeps track of the minimum number of taps we need to open.\n\n## Wrap-up\nThe function returns the minimum number of taps needed to water the entire garden. If it\'s not possible to water the whole garden, the function returns -1.\n\n## Complexity Analysis\n- **Time Complexity**: The algorithm runs in $$O(n)$$ time because it only needs to traverse the array `arr` once.\n \n- **Space Complexity**: The space complexity is $$O(n)$$ due to the additional array `arr`.\n\n---\n\n# Approach: Dynamic Programming with Local Optimization\n\n## Intuition and Logic Behind the Solution\nThe problem asks us to water the entire garden by opening the minimum number of taps. Unlike the greedy approach, which focuses on extending the range to be watered as far as possible, the dynamic programming approach calculates the minimum number of taps needed to water each point in the garden.\n\n## Why Dynamic Programming?\nDynamic programming (DP) is effective here because it allows us to build up a solution incrementally, using previously calculated results to inform future calculations. Each element in the DP array represents the minimum number of taps needed to water up to that point, which we update as we consider each tap in the garden. The DP approach is particularly useful when we need to make decisions that depend on previous choices, as is the case here.\n\n## Step-by-step Explanation\n- **Initialization**: Initialize an array `dp` of size `n+1` with `float(\'inf\')`, except for `dp[0]`, which is set to 0. This array will store the minimum number of taps needed to water up to each point.\n- **Iterate through Ranges**: Loop through the array `ranges`, which contains the range each tap can cover.\n - **Calculate Start and End**: For each tap at index `i`, calculate the start and end of the interval it can water.\n - **Update DP Array**: For each point `j` in the interval, update `dp[j]` to be the minimum of its current value and $$dp[\\text{start}] + 1$$.\n \n- **Check Feasibility**: If `dp[-1]` remains `float(\'inf\')`, then the garden can\'t be fully watered, and the function returns -1.\n\n## Wrap-up\nThe function returns `dp[-1]`, which holds the minimum number of taps needed to water the entire garden, or -1 if it\'s not possible to water the whole garden.\n\n## Complexity Analysis\n- **Time Complexity**: $$O(n^2)$$ due to the nested loop structure. For each tap, we potentially update $$O(n)$$ elements in the DP array.\n- **Space Complexity**: $$O(n)$$ for storing the DP array.\n\nThis DP approach provides an exact solution but may be slower than the greedy approach for large problem sizes. However, it is conceptually straightforward and builds a solid foundation for understanding more complex DP problems.\n\n---\n\n# Performance\n\n| Language | Approach | Runtime (ms) | Memory (MB) |\n|------------|----------|--------------|-------------|\n| Rust | Greedy | 2 | 2.2 |\n| Java | Greedy | 4 | 43.9 |\n| Go | Greedy | 7 | 5.5 |\n| C++ | Greedy | 10 | 14.6 |\n| PHP | Greedy | 32 | 20.8 |\n| JavaScript | Greedy | 71 | 43.8 |\n| C# | Greedy | 97 | 42.2 |\n| Python3 | Greedy | 112 | 16.8 |\n| Python3 | DP | 416 | 16.6 |\n\n![30j.png](https://assets.leetcode.com/users/images/ce1cae9d-6ec3-42cd-94f8-905a34f41514_1693442661.641292.png)\n\n# Code Greedy\n``` Python []\nclass Solution:\n def minTaps(self, n: int, ranges: List[int]) -> int:\n arr = [0] * (n + 1)\n for i, r in enumerate(ranges):\n if r == 0:\n continue\n left = max(0, i - r)\n arr[left] = max(arr[left], i + r)\n\n end, far_can_reach, cnt = 0, 0, 0\n \n for i, reach in enumerate(arr):\n if i > end:\n if far_can_reach <= end:\n return -1\n end, cnt = far_can_reach, cnt + 1\n far_can_reach = max(far_can_reach, reach)\n\n return cnt + (end < n)\n\n```\n``` C++ []\nclass Solution {\npublic:\n int minTaps(int n, vector<int>& ranges) {\n vector<int> arr(n + 1, 0);\n for(int i = 0; i < ranges.size(); ++i) {\n if(ranges[i] == 0) continue;\n int left = max(0, i - ranges[i]);\n arr[left] = max(arr[left], i + ranges[i]);\n }\n \n int end = 0, far_can_reach = 0, cnt = 0;\n for(int i = 0; i <= n; ++i) {\n if(i > end) {\n if(far_can_reach <= end) return -1;\n end = far_can_reach;\n ++cnt;\n }\n far_can_reach = max(far_can_reach, arr[i]);\n }\n \n return cnt + (end < n);\n }\n};\n```\n``` Rust []\nimpl Solution {\n pub fn min_taps(n: i32, ranges: Vec<i32>) -> i32 {\n let mut arr = vec![0; (n + 1) as usize];\n \n for i in 0..ranges.len() {\n if ranges[i] == 0 { continue; }\n let left = std::cmp::max(0, i as i32 - ranges[i]) as usize;\n arr[left] = std::cmp::max(arr[left], (i as i32 + ranges[i]) as usize);\n }\n \n let (mut end, mut far_can_reach, mut cnt) = (0, 0, 0);\n for i in 0..=n as usize {\n if i > end {\n if far_can_reach <= end { return -1; }\n end = far_can_reach;\n cnt += 1;\n }\n far_can_reach = std::cmp::max(far_can_reach, arr[i]);\n }\n \n cnt + if end < n as usize { 1 } else { 0 }\n }\n}\n```\n``` Go []\nfunc minTaps(n int, ranges []int) int {\n arr := make([]int, n+1)\n \n for i, r := range ranges {\n if r == 0 {\n continue\n }\n left := max(0, i - r)\n arr[left] = max(arr[left], i + r)\n }\n \n end, far_can_reach, cnt := 0, 0, 0\n for i := 0; i <= n; i++ {\n if i > end {\n if far_can_reach <= end {\n return -1\n }\n end = far_can_reach\n cnt++\n }\n far_can_reach = max(far_can_reach, arr[i])\n }\n \n if end < n {\n cnt++\n }\n return cnt\n}\n\nfunc max(a, b int) int {\n if a > b {\n return a\n }\n return b\n}\n```\n``` Java []\npublic class Solution {\n public int minTaps(int n, int[] ranges) {\n int[] arr = new int[n + 1];\n Arrays.fill(arr, 0);\n \n for(int i = 0; i < ranges.length; i++) {\n if(ranges[i] == 0) continue;\n int left = Math.max(0, i - ranges[i]);\n arr[left] = Math.max(arr[left], i + ranges[i]);\n }\n \n int end = 0, far_can_reach = 0, cnt = 0;\n for(int i = 0; i <= n; i++) {\n if(i > end) {\n if(far_can_reach <= end) return -1;\n end = far_can_reach;\n cnt++;\n }\n far_can_reach = Math.max(far_can_reach, arr[i]);\n }\n \n return cnt + (end < n ? 1 : 0);\n }\n}\n```\n``` C# []\npublic class Solution {\n public int MinTaps(int n, int[] ranges) {\n int[] arr = new int[n + 1];\n Array.Fill(arr, 0);\n \n for(int i = 0; i < ranges.Length; i++) {\n if(ranges[i] == 0) continue;\n int left = Math.Max(0, i - ranges[i]);\n arr[left] = Math.Max(arr[left], i + ranges[i]);\n }\n \n int end = 0, far_can_reach = 0, cnt = 0;\n for(int i = 0; i <= n; i++) {\n if(i > end) {\n if(far_can_reach <= end) return -1;\n end = far_can_reach;\n cnt++;\n }\n far_can_reach = Math.Max(far_can_reach, arr[i]);\n }\n \n return cnt + (end < n ? 1 : 0);\n }\n}\n```\n``` JavaScript []\n/**\n * @param {number} n\n * @param {number[]} ranges\n * @return {number}\n */\nvar minTaps = function(n, ranges) {\n const arr = new Array(n + 1).fill(0);\n \n for(let i = 0; i < ranges.length; i++) {\n if(ranges[i] === 0) continue;\n const left = Math.max(0, i - ranges[i]);\n arr[left] = Math.max(arr[left], i + ranges[i]);\n }\n \n let end = 0, far_can_reach = 0, cnt = 0;\n for(let i = 0; i <= n; i++) {\n if(i > end) {\n if(far_can_reach <= end) return -1;\n end = far_can_reach;\n cnt++;\n }\n far_can_reach = Math.max(far_can_reach, arr[i]);\n }\n \n return cnt + (end < n ? 1 : 0);\n}\n```\n``` PHP []\nclass Solution {\n\n /**\n * @param Integer $n\n * @param Integer[] $ranges\n * @return Integer\n */\n function minTaps($n, $ranges) {\n $arr = array_fill(0, $n + 1, 0);\n \n foreach($ranges as $i => $r) {\n if($r === 0) continue;\n $left = max(0, $i - $r);\n $arr[$left] = max($arr[$left], $i + $r);\n }\n \n $end = 0; $far_can_reach = 0; $cnt = 0;\n for($i = 0; $i <= $n; $i++) {\n if($i > $end) {\n if($far_can_reach <= $end) return -1;\n $end = $far_can_reach;\n $cnt++;\n }\n $far_can_reach = max($far_can_reach, $arr[$i]);\n }\n \n return $cnt + ($end < $n ? 1 : 0);\n }\n}\n```\n\n# Code DP \n``` Python []\nclass Solution:\n def minTaps(self, n: int, ranges: List[int]) -> int:\n dp = [float(\'inf\')] * (n + 1)\n dp[0] = 0\n \n for i, r in enumerate(ranges):\n start, end = max(0, i - r), min(n, i + r)\n for j in range(start + 1, end + 1):\n dp[j] = min(dp[j], dp[start] + 1)\n \n return dp[-1] if dp[-1] != float(\'inf\') else -1\n```\n\nEvery problem presents a new challenge and an opportunity to learn. Whether you\'re a beginner or an expert, each problem has something new to offer. So dive in, explore, and share your insights. Happy Coding! \uD83D\uDE80\uD83D\uDCA1\uD83C\uDF1F
108
8
['Dynamic Programming', 'Greedy', 'PHP', 'C++', 'Java', 'Go', 'Python3', 'Rust', 'JavaScript', 'C#']
7
minimum-number-of-taps-to-open-to-water-a-garden
[C++] O(n) no sort, similar to Jump Game II
c-on-no-sort-similar-to-jump-game-ii-by-80hg3
The question can be converted into the form of Jump Game II.\n\n1. The range each tap covers is: max(0, i-ranges[i]) (say l) to min(n, i+ranges[i]) (say r). Thi
sarthaksehgal
NORMAL
2020-01-21T04:37:24.667459+00:00
2020-11-10T09:16:18.537805+00:00
9,754
false
The question can be converted into the form of [Jump Game II](https://leetcode.com/problems/jump-game-ii/).\n\n1. The range each tap covers is: `max(0, i-ranges[i])` (say `l`) to `min(n, i+ranges[i])` (say `r`). Think of this range as a jump starting from the index `max(0,i-ranges[i])` with maximum reach till `min(n, i+ranges[i]) - max(0, i-ranges[i])`.\n2. To do this, we define a new array `jumps` where `jumps[l] = max(jumps[l], r-l)`. Now our problem boils down to calculating the minimum number of jumps required to reach the end of array.\n3. The main idea is based on greedy. Let\'s say the range of the current jump is [curBegin, curEnd], curFarthest is the farthest point that all points in [curBegin, curEnd] can reach. Once the current point reaches curEnd, then trigger another jump, and set the new curEnd with curFarthest, then keep the above steps.\nPlease see [this solution](https://leetcode.com/problems/jump-game-ii/discuss/18014/Concise-O(n)-one-loop-JAVA-solution-based-on-Greedy) of Jump Game II by [@Cheng_Zhang](https://leetcode.com/cheng_zhang/) to understand further.\n```\nint minTaps(int n, vector<int>& ranges) {\n vector<int> jumps(n+1, 0);\n \n for (int i=0; i<ranges.size(); i++) {\n int l = max(0, i-ranges[i]);\n int r = min(n, i+ranges[i]);\n jumps[l] = max(jumps[l], r-l);\n }\n \n for (auto i : jumps)\n cout<<i<<" ";\n cout<<endl;\n \n // See Jump Game II\n int count = 0, curEnd = 0, curFarthest = 0;\n for (int i = 0; i<jumps.size()-1; i++) {\n if (i>curFarthest)\n return -1;\n \n curFarthest = max(curFarthest, i + jumps[i]);\n \n if (i == curEnd) {\n count++;\n curEnd = curFarthest;\n }\n }\n \n return curFarthest >= n ? count : -1;\n }\n```\n\nTime complexity: O(n)\nSpace complexity: O(n)
91
3
[]
9
minimum-number-of-taps-to-open-to-water-a-garden
✅ Simple 7 line solution w/ explanation ⬆️ BEST🧠
simple-7-line-solution-w-explanation-bes-6c8q
small request - please give an upvote if it helps \uD83D\uDC31\u267B\uFE0F\uD83D\uDC31\n\n# Code\nCPP []\nclass Solution {\nint minTaps(int n, vector<int>& rang
trishitchar
NORMAL
2023-08-31T08:09:06.719482+00:00
2023-08-31T08:48:59.913034+00:00
2,753
false
# small request - please give an upvote if it helps \uD83D\uDC31\u267B\uFE0F\uD83D\uDC31\n\n# Code\n```CPP []\nclass Solution {\nint minTaps(int n, vector<int>& ranges) {\n int min=0, max=0, count=0; // Initialize variables to keep track of the minimum and maximum reach, and the number of taps used.\n while (max < n) { // Continue looping until we cover the entire range from 0 to n.\n for (int i = 0; i < ranges.size(); i++) {\n // Check if tap i can cover the current minimum position (min) and reach the current maximum position (max).\n if (i - ranges[i] <= min && i + ranges[i] >= max)\n max = i + ranges[i]; // Update the maximum reach if this tap can cover the current range.\n }\n if (max == min) return -1; // If max is not updated in this loop, it means we can\'t extend the reach further. Return -1 as it\'s not possible.\n count++; // Increment the count of taps used.\n min = max; // Update the minimum reach to the newly reached maximum position.\n }\n return count; // Return the count of taps used to cover the entire range.\n }\n};\n```\n```JAVA []\nclass Solution {\n public int minTaps(int n, int[] ranges) {\n int min = 0, max = 0, count = 0; // Initialize variables to keep track of the minimum and maximum reach, and the number of taps used.\n while (max < n) { // Continue looping until we cover the entire range from 0 to n.\n for (int i = 0; i < ranges.length; i++) {\n // Check if tap i can cover the current minimum position (min) and reach the current maximum position (max).\n if (i - ranges[i] <= min && i + ranges[i] >= max) {\n max = i + ranges[i]; // Update the maximum reach if this tap can cover the current range.\n }\n }\n if (max == min) return -1; // If max is not updated in this loop, it means we can\'t extend the reach further. Return -1 as it\'s not possible.\n count++; // Increment the count of taps used.\n min = max; // Update the minimum reach to the newly reached maximum position.\n }\n return count; // Return the count of taps used to cover the entire range.\n }\n}\n```\n```Python []\nclass Solution:\n def minTaps(self, n: int, ranges: List[int]) -> int:\n min_pos = 0\n max_pos = 0\n count = 0 # Initialize variables to keep track of the minimum and maximum reach, and the number of taps used.\n \n while max_pos < n: # Continue looping until we cover the entire range from 0 to n.\n for i in range(len(ranges)):\n # Check if tap i can cover the current minimum position (min_pos) and reach the current maximum position (max_pos).\n if i - ranges[i] <= min_pos and i + ranges[i] >= max_pos:\n max_pos = i + ranges[i] # Update the maximum reach if this tap can cover the current range.\n \n if max_pos == min_pos:\n return -1 # If max_pos is not updated in this loop, it means we can\'t extend the reach further. Return -1 as it\'s not possible.\n \n count += 1 # Increment the count of taps used.\n min_pos = max_pos # Update the minimum reach to the newly reached maximum position.\n \n return count # Return the count of taps used to cover the entire range.\n```\n\n# Intuition && Approach\n\n1. Initialize variables: min to keep track of the minimum reach, max to keep track of the maximum reach, and count to count the number of taps used.\n\n2. Start a while loop that continues until the entire range from 0 to n is covered.\n\n3. Inside the loop, iterate through all the taps represented by the ranges vector.\n\n4. For each tap at position i, check if it can cover the current minimum position (min) and reach the current maximum position (max). This is done by comparing i - ranges[i] with min (to check if it covers the left side) and i + ranges[i] with max (to check if it covers the right side).\n\n5. If the tap can cover the current range, update max to be the maximum reach achieved by this tap.\n\n6. After iterating through all the taps, check if max is still equal to min. If they are equal, it means no tap can extend the reach further, so return -1 to indicate that it\'s not possible to cover the entire range.\n\n7. Increment the count to keep track of the number of taps used.\n\n8. Update min to be equal to the newly reached max because we have covered the range up to max.\n\n9. Repeat steps 3-8 until max is greater than or equal to n, which means the entire range is covered.\n\n10. Finally, return the count which represents the minimum number of taps needed to cover the entire range.\n\n\n# small request - please give an upvote if it helps \uD83D\uDC31\u267B\uFE0F\uD83D\uDC31\n\n
54
1
['Greedy', 'C', 'C++', 'Java', 'Python3']
7
minimum-number-of-taps-to-open-to-water-a-garden
C++ (3 explained/commented approaches)
c-3-explainedcommented-approaches-by-maz-ze32
\n//Approach-1 (Brute Force)\nclass Solution {\npublic: \n int minTaps(int n, vector<int>& ranges) {\n int min = 0;\n int max = 0;\n
mazhar_mik
NORMAL
2021-07-17T15:46:53.929227+00:00
2021-07-17T15:46:53.929257+00:00
3,215
false
```\n//Approach-1 (Brute Force)\nclass Solution {\npublic: \n int minTaps(int n, vector<int>& ranges) {\n int min = 0;\n int max = 0;\n int count = 0;\n while(max < n) {\n \n //Choose the tap with maximum range it can reach to right\n //For a given min value (to left)\n for(int i = 0; i < n + 1; i++) {\n if(i-ranges[i] <= min && i+ranges[i] > max)\n max = i+ranges[i];\n }\n \n //It means we couldn\'t expand our range to right\n if(max == min)\n return -1;\n \n //Now, we have reached till max, next we want to cover more than this max\n //starting from min\n min = max;\n count++;\n }\n \n return count;\n }\n};\n```\n\n```\n//Approach-2 (Converting to Jump Game-II)\nclass Solution {\npublic:\n int minTaps(int n, vector<int>& ranges) {\n vector<int> jumps(n+1, 0);\n \n for(int i = 0; i<n+1; i++) {\n int l = max(0, i-ranges[i]);\n int r = min(n, i+ranges[i]);\n \n jumps[l] = max(jumps[l], r-l); //from l, that\'s farthest I can jump to right\n }\n \n //Now this questions has turned to Jump Game II\n //Where you have maximum jump you can take form an index i and\n //you have to reach end\n \n //This is just Jump Game - II code\n int currEnd = 0;\n int maxReach = 0;\n int count = 0;\n for(int i = 0; i<n; i++) {\n maxReach = max(maxReach, jumps[i]+i);\n \n if(i == currEnd) {\n count++;\n currEnd = maxReach;\n }\n }\n \n if(currEnd >= n)\n return count;\n return -1;\n }\n};\n```\n\n```\n//Approach-3 (BOttom UP : DP)\nclass Solution {\npublic:\n int minTaps(int n, vector<int>& ranges) {\n vector<int> t(n+1, n+2);\n \n //t[i] = minimum taps needed to cover 0 to ith of Garden\n t[0] = 0; //I need 0 tap to cover 0 to 0\n \n //Why start from i = 0\n //Because value at ranges[0] also impacts the range {i-ranges[i], i+ranges[i]}\n //We will miss that impact if we skip i = 0\n for(int i = 0; i<n+1; i++) {\n \n int l = max(0, i-ranges[i]);\n int r = min(n, i+ranges[i]);\n \n /*\n 0 to l is watered\n We now need to find minimum taps to cover from (l+1) to r\n */\n for(int j = l+1; j<=r; j++)\n \n /*\n Check if this range from(left+1..right) can\n be watered using less number of taps than previous\n */\n \n t[j] = min(t[j], t[l]+1);\n \n }\n \n //if min taps needed to water ground is greater than (n+1) we return -1\n //Because we only had (n+1) taps\n return t[n] > n+1 ? -1 : t[n];\n }\n};\n```
42
0
[]
4
minimum-number-of-taps-to-open-to-water-a-garden
[Java/Python 3] Sort and greedy, similar to 1024 video stitching, w/ brief explanation and analysis.
javapython-3-sort-and-greedy-similar-to-ysxe7
The ranges can cover intervals: [i - ranges[i], i + ranges[i]]; Sort them by their low bounds;\n2. start starting from 0, if it is not less than the low bound o
rock
NORMAL
2020-01-19T04:02:13.760993+00:00
2020-01-20T04:20:55.961347+00:00
5,677
false
1. The `ranges` can cover intervals: `[i - ranges[i], i + ranges[i]]`; Sort them by their low bounds;\n2. `start` starting from `0`, if it is not less than the low bound of current interval, update `end` to the high bound; move to next interval; \n3. Repeat step 2 till low bound of current interval larger than `start`; If `end` is same as `start`, means impossible to cover the right of `end`, return -1; Otherwise, update `start` to `end`, increase `ans` by 1;\n4. Return `ans` if not return -1 in step 3.\n\n```java\n public int minTaps(int n, int[] ranges) {\n int[][] rg = new int[n + 1][2];\n for (int i = 0; i <= n; ++i)\n rg[i] = new int[]{i - ranges[i], i + ranges[i]};\n Arrays.sort(rg, Comparator.comparing(r -> r[0]));\n int ans = 0;\n for (int i = 0, start = 0, end = 0; start < n && i <= n; start = end, ++ans) {\n while (i <= n && rg[i][0] <= start)\n end = Math.max(end, rg[i++][1]);\n if (end <= start)\n return -1;\n }\n return ans;\n }\n```\n```python\n def minTaps(self, n: int, ranges: List[int]) -> int:\n rg = sorted([[i - r, i + r] for i, r in enumerate(ranges)])\n ans = start = end = i = 0\n while start < n:\n while i <= n and rg[i][0] <= start:\n end = max(end, rg[i][1])\n i += 1 \n if start == end:\n return -1\n start = end\n ans += 1\n return ans\n````\n\n**Analysis:**\n\nTime: O(nlogn), space: O(n).
41
0
[]
6
minimum-number-of-taps-to-open-to-water-a-garden
Wrong test?
wrong-test-by-nvda-v88p
For this test case, can someone please explain why the answer is 6 instead of 5?\n\n35\n[1,0,4,0,4,1,4,3,1,1,1,2,1,4,0,3,0,3,0,3,0,5,3,0,0,1,2,1,2,4,3,0,1,0,5,2
nvda
NORMAL
2020-01-19T04:05:13.873400+00:00
2020-01-21T13:48:32.007513+00:00
2,673
false
For this test case, can someone please explain why the answer is 6 instead of 5?\n\n35\n[1,0,4,0,4,1,4,3,1,1,1,2,1,4,0,3,0,3,0,3,0,5,3,0,0,1,2,1,2,4,3,0,1,0,5,2]\n\n\nyou can use the following configuration to get the answer 5\n[1,0,4,0,4,1,4,3,1|1,1,2,1,4,0,3,0,3|0,3,0,5,3,0,0,1,2|1,2,4,3,0,1,0|5,2]\n 1,1,1,1,1,1,1,1,1 |2,2,2,2,2,2,2,2,2|3,3,3,3,3,3,3,3,3|4,4,4,4,4,4,4|5,5\n\n\nEDIT: it was clarified that covering all the taps is not enough, you need to cover all the areas between the taps as well. \nThe difference between the solutions for the 2 cases is you just need to change the right range to be exclusive instead of inclusive if we are not covering the last tap.\n\n int minTaps(int n, vector<int>& ranges) {\n vector<int> v(ranges.size(), 0); // v[i] -> which tap covers tap i and covers the most taps to the right\n\n for (int i = 0; i <= n; i ++)\n { \n int r = ranges[i];\n if (r == 0)\n continue;\n\t\t\t// int right = min(n, i + r); // this works if you don\'t need to cover the area between the taps\n int right = min(n, i + r == n ? n : i + r - 1);\n for (int j = max(0, i - r); j <= right; j ++)\n v[j] = max(v[j], right);\n }\n \n int res = 0;\n for (int i = 0; i <= n; i ++)\n {\n if (v[i] == 0)\n return -1;\n \n i = v[i]; // last one covered\n res ++;\n }\n\n return res;\n }
40
0
[]
11
minimum-number-of-taps-to-open-to-water-a-garden
C++ || DP (recursion + memoization) || Day 31
c-dp-recursion-memoization-day-31-by-chi-vclp
Code\n\nclass Solution{\npublic:\n int N;\n long dp[10008];\n long help(int i, vector<pair<int, int>> &vp)\n {\n if (vp[i].second == N)\n
CHIIKUU
NORMAL
2023-08-31T04:52:22.272799+00:00
2023-08-31T04:52:22.272820+00:00
4,910
false
Code\n```\nclass Solution{\npublic:\n int N;\n long dp[10008];\n long help(int i, vector<pair<int, int>> &vp)\n {\n if (vp[i].second == N)\n return 1;\n if (i == vp.size())\n return INT_MAX;\n if (dp[i] != -1)\n return dp[i];\n long ans = INT_MAX;\n for (int j = i + 1; j < vp.size(); j++)\n {\n if (vp[j].first > vp[i].second)\n break;\n ans = min(ans, 1 + help(j, vp));\n }\n return dp[i] = ans;\n }\n int minTaps(int n, vector<int> &ranges)\n {\n N = n;\n memset(dp, -1, sizeof(dp));\n vector<pair<int, int>> vp;\n for (int i = 0; i < ranges.size(); i++)\n {\n int x = max(0, i - ranges[i]);\n int y = min(n, i + ranges[i]);\n vp.push_back({x, y});\n }\n sort(vp.begin(), vp.end());\n long ans = INT_MAX;\n for (int i = 0; i < n; i++)\n {\n if (vp[i].first == 0)\n {\n ans = min(ans, help(i, vp));\n }\n }\n if (ans == INT_MAX)\n ans = -1;\n return ans;\n }\n};\n```\n![upvote (2).jpg](https://assets.leetcode.com/users/images/9a23bb8c-dcd5-4f38-a004-1bc93c79ad9d_1693457531.908961.jpeg)\n\n
35
0
['Array', 'Dynamic Programming', 'Greedy', 'Recursion', 'Memoization', 'C++']
3
minimum-number-of-taps-to-open-to-water-a-garden
[Java] Jump game II. O(N) time and O(1) space
java-jump-game-ii-on-time-and-o1-space-b-n0ma
If you have not done Jump Game porblems, try resolving that first: https://leetcode.com/problems/jump-game-ii/\n\nAssuming you already understand the Jump Game
liang54
NORMAL
2020-09-01T15:48:08.834299+00:00
2020-09-01T15:48:08.834346+00:00
2,223
false
If you have not done Jump Game porblems, try resolving that first: https://leetcode.com/problems/jump-game-ii/\n\nAssuming you already understand the Jump Game II solution, now in this problem, you just need to convert the ranges array to the max point you can get from each index.\n\n```\n public int minTaps(int n, int[] ranges) {\n for (int i=0; i<ranges.length; i++) {\n int s = Math.max(0, i - ranges[i]);\n int e = i + ranges[i];\n if (s < i) {\n // update the maximum right bound from left bound s.\n ranges[s] = Math.max(e, ranges[s]);\n }\n }\n // Identical solution from Jump Game II.\n // The only difference is that in jump game problem, the element in the array is the maximum steps to jump with\n // but here, the element in the range array is already the maximum index that one can reach to.\n int curEnd = 0, steps = 0, curFurtherest = 0;\n for (int i=0; i<n; i++) {\n // update the max point we can reach.\n curFurtherest = Math.max(curFurtherest, ranges[i]);\n if (i == curEnd) {\n // Being greedy. \n // We only have a new jump when we are reaching the furtherest point from previous jump\n // Update the curEnd to the new max point\n steps++;\n curEnd = curFurtherest;\n }\n }\n return curEnd >= n ? steps : -1;\n }\n```\n
34
0
[]
4
minimum-number-of-taps-to-open-to-water-a-garden
【Video】Beat 95% solution with Python, JavaScript, Java and C++
video-beat-95-solution-with-python-javas-6kwp
Intuition\nThe most important idea to solve this question is to utilize the concept of dynamic programming by transforming the tap ranges into intervals. This a
niits
NORMAL
2023-08-31T03:42:02.157614+00:00
2023-08-31T08:57:03.021029+00:00
1,793
false
# Intuition\nThe most important idea to solve this question is to utilize the concept of dynamic programming by transforming the tap ranges into intervals. This allows you to efficiently determine the coverage of each tap and select the optimal intervals to minimize the number of taps required to water the entire garden. The key steps involve creating intervals, updating coverage and farthest reachable endpoints, and efficiently iterating through the intervals to find the solution.\n\n---\n\n# Solution Video\n\n### Please subscribe to my channel from here. I have 253 videos as of August 31th, 2023.\n\nhttps://youtu.be/s3o3XJHm3fU\n\n### In the video, the steps of approach below are visualized using diagrams and drawings. I\'m sure you understand the solution easily!\n\n### \u2B50\uFE0F Don\'t forget to subscribe to my channel!\n\n**\u25A0 Subscribe URL**\nhttp://www.youtube.com/channel/UC9RMNwYTL3SXCP6ShLWVFww?sub_confirmation=1\n\n---\n\n# Approach\nThis is based on Python. Other might be different a bit.\n\n1. **Initialization of Variables**\n - `max_range` array is initialized with zeros to keep track of the maximum right endpoint for each left endpoint.\n\n2. **Creating Intervals and Filling `max_range`**\n - Iterate through the `ranges` list.\n - Calculate the left and right endpoints of the interval based on the current index and the tap\'s range.\n - Update `max_range` at the `left` position with the maximum value between its current value and `right`.\n\n3. **Initialization of Pointers and Counters**\n - Initialize `end`, `farthest`, and `taps` to 0. `i` is initialized to 0.\n\n4. **Iterate Until the Garden is Covered**\n - While `end` (rightmost point reached so far) is less than `n` (the total length of the garden):\n - Start an inner loop that iterates while `i` is less than or equal to `end`.\n - Update `farthest` to be the maximum between its current value and `max_range[i]`.\n - Increment `i` to move through the intervals.\n\n5. **Check Coverage**\n - If `farthest` is less than or equal to `end`, it means we couldn\'t extend the coverage further, and we return -1 as it\'s not possible to cover the entire garden.\n\n6. **Extend Coverage and Increment Tap Count**\n - Update `end` to `farthest` to extend the coverage.\n - Increment `taps` to count the number of taps used.\n\n7. **Return the Minimum Taps Required**\n - Once the while loop completes (meaning the entire garden is covered), return the value of `taps` as the minimum number of taps required.\n\n# Complexity\n- Time complexity: O(n)\n\n\n- Space complexity: O(n)\n\n```python []\nclass Solution:\n def minTaps(self, n: int, ranges: List[int]) -> int:\n max_range = [0] * (n + 1)\n \n for i in range(len(ranges)):\n left = max(0, i - ranges[i])\n right = min(n, i + ranges[i])\n max_range[left] = max(max_range[left], right)\n \n end = farthest = taps = 0\n i = 0\n \n while end < n:\n while i <= end:\n farthest = max(farthest, max_range[i])\n i += 1\n \n if farthest <= end:\n return -1 # Unable to cover the entire garden\n \n end = farthest\n taps += 1\n \n return taps \n```\n```javascript []\n/**\n * @param {number} n\n * @param {number[]} ranges\n * @return {number}\n */\nvar minTaps = function(n, ranges) {\n const maxRange = new Array(n + 1).fill(0);\n \n for (let i = 0; i < ranges.length; i++) {\n const left = Math.max(0, i - ranges[i]);\n const right = Math.min(n, i + ranges[i]);\n maxRange[left] = Math.max(maxRange[left], right);\n }\n \n let end = 0;\n let farthest = 0;\n let taps = 0;\n let i = 0;\n \n while (end < n) {\n while (i <= end) {\n farthest = Math.max(farthest, maxRange[i]);\n i++;\n }\n \n if (farthest <= end) {\n return -1; // Unable to cover the entire garden\n }\n \n end = farthest;\n taps++;\n }\n \n return taps; \n};\n```\n```java []\nclass Solution {\n public int minTaps(int n, int[] ranges) {\n int[] maxRange = new int[n + 1];\n \n for (int i = 0; i < ranges.length; i++) {\n int left = Math.max(0, i - ranges[i]);\n int right = Math.min(n, i + ranges[i]);\n maxRange[left] = Math.max(maxRange[left], right);\n }\n \n int end = 0;\n int farthest = 0;\n int taps = 0;\n int i = 0;\n \n while (end < n) {\n while (i <= end) {\n farthest = Math.max(farthest, maxRange[i]);\n i++;\n }\n \n if (farthest <= end) {\n return -1; // Unable to cover the entire garden\n }\n \n end = farthest;\n taps++;\n }\n \n return taps; \n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n int minTaps(int n, vector<int>& ranges) {\n vector<int> maxRange(n + 1, 0);\n \n for (int i = 0; i < ranges.size(); i++) {\n int left = max(0, i - ranges[i]);\n int right = min(n, i + ranges[i]);\n maxRange[left] = max(maxRange[left], right);\n }\n \n int end = 0;\n int farthest = 0;\n int taps = 0;\n int i = 0;\n \n while (end < n) {\n while (i <= end) {\n farthest = max(farthest, maxRange[i]);\n i++;\n }\n \n if (farthest <= end) {\n return -1; // Unable to cover the entire garden\n }\n \n end = farthest;\n taps++;\n }\n \n return taps; \n }\n};\n```\n
33
0
['C++', 'Java', 'Python3', 'JavaScript']
1
minimum-number-of-taps-to-open-to-water-a-garden
[Java] O(n) solution | beat 100% | Greedy
java-on-solution-beat-100-greedy-by-adkm-18c9
Iterate through all the intervals and store the longest position value that can be reached\nEvery time choose to go to the farthest point it can reach\n\nclass
adkmr
NORMAL
2020-01-19T04:19:53.839827+00:00
2020-01-19T04:19:53.839876+00:00
5,131
false
Iterate through all the intervals and store the longest position value that can be reached\nEvery time choose to go to the farthest point it can reach\n```\nclass Solution {\n public int minTaps(int n, int[] ranges) {\n int[] intervals = new int[n];\n Arrays.fill(intervals, -1);\n for (int i = 0; i < ranges.length; i++) {\n if (ranges[i] == 0) continue;\n int left = i - ranges[i] >= 0 ? i - ranges[i] : 0;\n int right = i + ranges[i];\n intervals[left] = Math.max(intervals[left], right);\n }\n if (intervals[0] == -1) return -1;\n int longest = intervals[0];\n int count = 1;\n int i = 0;\n while (longest < n) {\n int temp = Integer.MIN_VALUE;\n for (; i <= longest; i++) {\n int val = intervals[i];\n if (val == -1) continue;\n temp = Math.max(temp, val);\n }\n if (temp <= longest) return -1;\n longest = temp;\n count++;\n }\n return count;\n }\n}\n```
32
0
['Greedy', 'Java']
6
minimum-number-of-taps-to-open-to-water-a-garden
【Video】Beat 95% solution with Python, JavaScript, Java and C++
video-beat-95-solution-with-python-javas-37tq
IntuitionThe most important idea to solve this question is to utilize the concept of dynamic programming by transforming the tap ranges into intervals. This all
niits
NORMAL
2025-01-14T16:40:45.263317+00:00
2025-01-14T17:57:28.449940+00:00
648
false
# Intuition The most important idea to solve this question is to utilize the concept of dynamic programming by transforming the tap ranges into intervals. This allows you to efficiently determine the coverage of each tap and select the optimal intervals to minimize the number of taps required to water the entire garden. The key steps involve creating intervals, updating coverage and farthest reachable endpoints, and efficiently iterating through the intervals to find the solution. --- # Solution Video ### Please subscribe to my channel from here. I have 253 videos as of August 31th, 2023. https://youtu.be/s3o3XJHm3fU ### In the video, the steps of approach below are visualized using diagrams and drawings. I'm sure you understand the solution easily! ### ⭐️ Don't forget to subscribe to my channel! **■ Subscribe URL** http://www.youtube.com/channel/UC9RMNwYTL3SXCP6ShLWVFww?sub_confirmation=1 --- # Approach This is based on Python. Other might be different a bit. 1. **Initialization of Variables** - `max_range` array is initialized with zeros to keep track of the maximum right endpoint for each left endpoint. 2. **Creating Intervals and Filling `max_range`** - Iterate through the `ranges` list. - Calculate the left and right endpoints of the interval based on the current index and the tap's range. - Update `max_range` at the `left` position with the maximum value between its current value and `right`. 3. **Initialization of Pointers and Counters** - Initialize `end`, `farthest`, and `taps` to 0. `i` is initialized to 0. 4. **Iterate Until the Garden is Covered** - While `end` (rightmost point reached so far) is less than `n` (the total length of the garden): - Start an inner loop that iterates while `i` is less than or equal to `end`. - Update `farthest` to be the maximum between its current value and `max_range[i]`. - Increment `i` to move through the intervals. 5. **Check Coverage** - If `farthest` is less than or equal to `end`, it means we couldn't extend the coverage further, and we return -1 as it's not possible to cover the entire garden. 6. **Extend Coverage and Increment Tap Count** - Update `end` to `farthest` to extend the coverage. - Increment `taps` to count the number of taps used. 7. **Return the Minimum Taps Required** - Once the while loop completes (meaning the entire garden is covered), return the value of `taps` as the minimum number of taps required. # Complexity - Time complexity: O(n) - Space complexity: O(n) ```python [] class Solution: def minTaps(self, n: int, ranges: List[int]) -> int: max_range = [0] * (n + 1) for i in range(len(ranges)): left = max(0, i - ranges[i]) right = min(n, i + ranges[i]) max_range[left] = max(max_range[left], right) end = farthest = taps = 0 i = 0 while end < n: while i <= end: farthest = max(farthest, max_range[i]) i += 1 if farthest <= end: return -1 # Unable to cover the entire garden end = farthest taps += 1 return taps ``` ```javascript [] /** * @param {number} n * @param {number[]} ranges * @return {number} */ var minTaps = function(n, ranges) { const maxRange = new Array(n + 1).fill(0); for (let i = 0; i < ranges.length; i++) { const left = Math.max(0, i - ranges[i]); const right = Math.min(n, i + ranges[i]); maxRange[left] = Math.max(maxRange[left], right); } let end = 0; let farthest = 0; let taps = 0; let i = 0; while (end < n) { while (i <= end) { farthest = Math.max(farthest, maxRange[i]); i++; } if (farthest <= end) { return -1; // Unable to cover the entire garden } end = farthest; taps++; } return taps; }; ``` ```java [] class Solution { public int minTaps(int n, int[] ranges) { int[] maxRange = new int[n + 1]; for (int i = 0; i < ranges.length; i++) { int left = Math.max(0, i - ranges[i]); int right = Math.min(n, i + ranges[i]); maxRange[left] = Math.max(maxRange[left], right); } int end = 0; int farthest = 0; int taps = 0; int i = 0; while (end < n) { while (i <= end) { farthest = Math.max(farthest, maxRange[i]); i++; } if (farthest <= end) { return -1; // Unable to cover the entire garden } end = farthest; taps++; } return taps; } } ``` ```C++ [] class Solution { public: int minTaps(int n, vector<int>& ranges) { vector<int> maxRange(n + 1, 0); for (int i = 0; i < ranges.size(); i++) { int left = max(0, i - ranges[i]); int right = min(n, i + ranges[i]); maxRange[left] = max(maxRange[left], right); } int end = 0; int farthest = 0; int taps = 0; int i = 0; while (end < n) { while (i <= end) { farthest = max(farthest, maxRange[i]); i++; } if (farthest <= end) { return -1; // Unable to cover the entire garden } end = farthest; taps++; } return taps; } }; ``` --- Thank you for reading my post. ⭐️ Please upvote it and don't forget to subscribe to my channel! ⭐️ Subscribe URL http://www.youtube.com/channel/UC9RMNwYTL3SXCP6ShLWVFww?sub_confirmation=1 https://youtu.be/pCc4kR-TdYs
28
0
['Array', 'Dynamic Programming', 'Greedy', 'C++', 'Java', 'Python3', 'JavaScript']
0
minimum-number-of-taps-to-open-to-water-a-garden
[Python] O(1) memory O(n) time Greedy With Explanation (132ms beats 100%)
python-o1-memory-on-time-greedy-with-exp-gp25
Constant Space! O(n) Greedy Approuch (AC: 132ms beats 100%)\nThis question is very similar to Jump Game II. \n1. Inplace modify ranges so that each element repr
yanrucheng
NORMAL
2020-01-19T04:02:20.117675+00:00
2020-01-19T06:08:01.585560+00:00
2,630
false
**Constant Space! O(n) Greedy Approuch (AC: 132ms beats 100%)**\nThis question is very similar to [Jump Game II](https://leetcode.com/problems/jump-game-ii/). \n1. Inplace modify `ranges` so that each element represents the furthest index you can reach by taking one jump.\n2. Find the minimal jump you need to reach the end.\n```\nclass Solution:\n def minTaps(self, n: int, ranges: List[int]) -> int:\n for i,r in enumerate(ranges):\n l = max(0,i-r)\n ranges[l] = max(i+r, ranges[l])\n \n res = lo = hi = 0 \n while hi < n:\n lo, hi = hi, max(ranges[lo:hi+1])\n if hi == lo: return -1\n res += 1\n return res \n```\n**O(nlogn) Greedy Approuch (AC: 175ms)**\n1. Convert `ranges` in the format of `[(l0,r0), (l1,r1)...]`, where `li,ri` represents the left boundary and right boundary of a tap. O(n)\n2. Sort the taps. O(nlogn)\n3. Select taps greedily. We select the one that can reach the furthest among those whose left boundary overlaps with the current furthest point.\n```\nclass Solution:\n def minTaps(self, n: int, ranges: List[int]) -> int:\n taps = sorted([(max(p-r,0), min(p+r,n)) for p, r in enumerate(ranges)])\n \n new_furthest = furthest = ind = 0\n for res in range(1,n+1):\n for i,(l,r) in enumerate(taps[ind:],ind):\n if l > furthest: break\n new_furthest = max(new_furthest, r)\n ind = i \n \n if new_furthest == furthest and new_furthest != n: return -1\n if new_furthest == n: return res\n furthest = new_furthest\n```\n
28
1
['Greedy', 'Python']
1
minimum-number-of-taps-to-open-to-water-a-garden
Python : O(N)
python-on-by-fallenranger-t9s7
Create jumps array which stores the maximum coverage from a point.\nThen problem is just reduced to reaching last index from 0th index in minimum jumps using ju
fallenranger
NORMAL
2020-01-19T04:04:19.724338+00:00
2020-01-19T05:33:28.127640+00:00
3,482
false
Create jumps array which stores the maximum coverage from a point.\nThen problem is just reduced to reaching last index from 0th index in minimum jumps using jumps array.\n[Jump Array 2](https://leetcode.com/problems/jump-game-ii/)\n\n```\nclass Solution:\n def minTaps(self, n: int, ranges: List[int]) -> int:\n jumps = [0]*(n+1)\n for i in range(n+1):\n l, r = max(0,i-ranges[i]), min(n,i+ranges[i])\n jumps[l] = max(jumps[l],r-l)\n step = start = end = 0\n while end < n:\n start, end = end+1, max(i+jumps[i] for i in range(start, end+1))\n if start > end:\n return -1\n step += 1\n return step\n```\nTime Complexity : O(N)\nSpace Complexity : O(N)
25
0
['Python', 'Python3']
10
minimum-number-of-taps-to-open-to-water-a-garden
Easy solution| Line By Line explanation 🔥| DP and Greedy Approach | Python | Beats 90+% | 🍾🔥
easy-solution-line-by-line-explanation-d-tad5
Intuition\nThe problem challenges us to water an entire one-dimensional garden using the fewest number of taps. Each tap has a range that it can water. The crux
Pratikk_Rathod
NORMAL
2023-08-31T04:07:04.382938+00:00
2023-08-31T18:52:02.837682+00:00
1,590
false
# Intuition\n**The problem challenges us to water an entire one-dimensional garden using the fewest number of taps. Each tap has a range that it can water. The crux of our solution is to always choose the tap that allows us to water the farthest point in the garden that hasn\'t been watered yet.**\n<!-- Describe your first thoughts on how to solve this problem. -->\n# Beats:\n![image.png](https://assets.leetcode.com/users/images/acea0346-2a97-4cfc-90b4-44f4ca1533b7_1693454711.7570882.png)\n\n\n# Approach\n1. We start by preparing an array max_reach where the index represents the starting point of a tap, and the value at that index represents the farthest point that can be watered from that tap.\n2. We iterate through the ranges array and populate the max_reach array based on the watering ranges of each tap.\n3. We initialize end, far_can_reach, and taps_used variables to keep track of the last point watered, the farthest point reachable by any tap considered so far, and the number of taps used, respectively.\n4. We iterate through the max_reach array, and for each index i, if i is greater than end, we update end to far_can_reach and increment taps_used by 1. This means we need to open a new tap to extend our watering reach.\n5. If at any point we find that far_can_reach is less than or equal to end, it means we cannot extend our watering reach, and we return -1.\n6. Finally, we return taps_used plus 1 if end is less than n, indicating that we need to open an additional tap to cover the remaining area.\nComplexity\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n- $$O(n)$$, where n is the length of the input array ranges. We iterate through the ranges array once to populate the max_reach array and then iterate through the max_reach array once.\n- Space complexity:\n- $$O(n)$$, as we use the max_reach array to store the farthest reachable points for each tap.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def minTaps(self, n: int, ranges: List[int]) -> int:\n # Create an array to store the maximum right boundary that each tap can reach\n max_reach = [0] * (n + 1)\n \n # Populate the max_reach array based on the ranges of each tap\n for i, r in enumerate(ranges):\n if r == 0:\n continue\n left_boundary = max(0, i - r)\n right_boundary = min(n, i + r)\n max_reach[left_boundary] = max(max_reach[left_boundary], right_boundary)\n \n # Initialize variables to keep track of the watering progress\n end, far_can_reach, taps_used = 0, 0, 0\n \n # Iterate through the garden points and water them using the taps\n for i, reach in enumerate(max_reach):\n if i > end:\n # If the current position can\'t be reached, return -1\n if far_can_reach <= end:\n return -1\n # Update the end to the farthest reachable point and increment taps_used\n end, taps_used = far_can_reach, taps_used + 1\n # Update the farthest point we can currently reach\n far_can_reach = max(far_can_reach, reach)\n \n # Return the total taps_used + 1 if end is less than n, indicating extra tap needed\n return taps_used + (end < n)\n\n\n```\n\n# Please upvote if u find helpful\n\n
23
0
['Python', 'Python3']
7
minimum-number-of-taps-to-open-to-water-a-garden
Simple Solution || Beginner Friendly || Easy to Understand 🔥
simple-solution-beginner-friendly-easy-t-eieb
Approach\n Describe your approach to solving the problem. \n- Create an array maxReach to store the farthest endpoints that can be reached from each starting po
Anirban_Pramanik10
NORMAL
2023-08-31T01:37:54.388204+00:00
2023-08-31T02:00:33.914631+00:00
3,372
false
# Approach\n<!-- Describe your approach to solving the problem. -->\n- Create an array `maxReach` to store the farthest endpoints that can be reached from each starting point.\n- Iterate through the `ranges` array:\n- Calculate starting and ending points for each tap\'s reach.\n- Update `maxReach` at the starting point with the corresponding ending point.\n- Initialize variables for tap count (`tap`), current endpoint (`currEnd`), and next endpoint (`nextEnd`).\n- Loop through indices `0` to `n`:\n- If `i` is beyond `nextEnd`, return `-1` as a gap cannot be covered.\n- If `i` is beyond `currEnd`, increment `tap` and update `currEnd` to `nextEnd`.\n- Update `nextEnd` with the maximum of its current value and `maxReach[i]`.\n- Return the value of `tap` as the minimum taps needed to cover the garden.\n\n# Complexity\n- Time complexity: `O(n)`\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n- Space complexity: `O(n)`\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n public int minTaps(int n, int[] ranges) {\n int[] maxReach = new int[n+1];\n \n for(int i=0;i<ranges.length;i++) {\n int s = Math.max(0, i - ranges[i]), e = i + ranges[i]; \n maxReach[s] = e;\n }\n \n int tap = 0, currEnd = 0, nextEnd = 0; \n for(int i=0;i<=n;i++) {\n if(i > nextEnd) return -1;\n if(i > currEnd) {\n tap++;\n currEnd = nextEnd;\n }\n nextEnd = Math.max(nextEnd, maxReach[i]);\n }\n return tap;\n }\n}\n```\n```python3 []\nclass Solution:\n def minTaps(self, n, ranges):\n maxReach = [0] * (n + 1)\n \n for i in range(len(ranges)):\n s = max(0, i - ranges[i])\n e = i + ranges[i]\n maxReach[s] = e\n \n tap = 0\n currEnd = 0\n nextEnd = 0\n \n for i in range(n + 1):\n if i > nextEnd:\n return -1\n if i > currEnd:\n tap += 1\n currEnd = nextEnd\n nextEnd = max(nextEnd, maxReach[i])\n \n return tap\n\n```\n```C++ []\nclass Solution {\npublic:\n int minTaps(int n, std::vector<int>& ranges) {\n std::vector<int> maxReach(n + 1, 0);\n \n for (int i = 0; i < ranges.size(); ++i) {\n int s = std::max(0, i - ranges[i]);\n int e = i + ranges[i];\n maxReach[s] = e;\n }\n \n int tap = 0;\n int currEnd = 0;\n int nextEnd = 0;\n \n for (int i = 0; i <= n; ++i) {\n if (i > nextEnd) {\n return -1;\n }\n if (i > currEnd) {\n tap++;\n currEnd = nextEnd;\n }\n nextEnd = std::max(nextEnd, maxReach[i]);\n }\n \n return tap;\n }\n};\n```\n```C []\nclass Solution {\npublic:\n int minTaps(int n, vector<int>& ranges) {\n \n for(int i=1;i<ranges.size();i++){\n if(ranges[i] == 0) ranges[i]=i;\n else{\n int range = max(0, i-ranges[i]);\n ranges[range] = max(i+ranges[i],ranges[range]);\n }\n }\n \n int maxIdx = 0;\n int pos = 0;\n int jump = 0;\n \n for(int i=0;i<n;i++){\n if(maxIdx<i) return -1;\n \n maxIdx = max(maxIdx, ranges[i]);\n \n if(i==pos){\n jump++;\n pos = maxIdx;\n }\n }\n \n return maxIdx>=n ? jump : -1;\n \n }\n};\n```\n# If you like the solution please Upvote.\n![5196fec2-1dd4-4b82-9700-36c5a0e72623_1692159956.9446952.jpeg](https://assets.leetcode.com/users/images/137cf315-3420-4cd0-a71e-6e9724eb642b_1693445807.4529147.jpeg)\n
21
3
['Array', 'Dynamic Programming', 'Greedy', 'C', 'C++', 'Java', 'Python3']
5
minimum-number-of-taps-to-open-to-water-a-garden
[Clean C++] Treat it as another interval problem (Like Video Stitching)
clean-c-treat-it-as-another-interval-pro-cknz
Same as : https://leetcode.com/problems/video-stitching/\n\n\nclass Solution {\npublic:\n int minTaps(int n, vector<int>& ranges) {\n vector <vector<i
abhisharma404
NORMAL
2020-07-09T06:46:12.197399+00:00
2020-07-09T06:47:30.320226+00:00
2,538
false
Same as : https://leetcode.com/problems/video-stitching/\n\n```\nclass Solution {\npublic:\n int minTaps(int n, vector<int>& ranges) {\n vector <vector<int>> intervals;\n for (int i = 0; i < ranges.size(); i++) {\n vector<int> inter{i - ranges[i], i + ranges[i]};\n intervals.push_back(inter);\n }\n sort(intervals.begin(), intervals.end(), [](auto &p, auto &q){\n return (p[0] < q[0]);\n });\n int count = 0, start_time = 0, end_time = 0, i = 0;\n \n while (end_time < n) {\n for (; i < intervals.size() && intervals[i][0] <= start_time; i++) {\n end_time = max(end_time, intervals[i][1]);\n }\n if (start_time == end_time) return -1;\n start_time = end_time;\n count++;\n }\n return count;\n }\n};\n```
20
3
['Greedy', 'Recursion', 'C', 'Sorting', 'C++']
0
minimum-number-of-taps-to-open-to-water-a-garden
Greedy python O(N log(N)) beats 97%
greedy-python-on-logn-beats-97-by-akshay-uf0c
Convert the ranges into intervals [start, end] and sort them by the start positions\n2. In each iteration find a pipe such that its start is <= the end of the p
akshayagg
NORMAL
2021-01-21T11:09:33.874250+00:00
2021-01-21T11:13:28.862309+00:00
1,614
false
1. Convert the ranges into intervals [start, end] and sort them by the start positions\n2. In each iteration find a pipe such that its start is <= the end of the prev pipe and has the largest end among all such pipes. \n3. Continue till we find a pipe whose end >= n\n\n`n = 7 ranges=[1,2,1,0,2,1,0,1]`\n`intervals = [(-1, 1), (-1, 3), (1, 3), (2, 6), (4, 6), (6, 8)]`\n\nIterations\n1. find all intervals with start positions <= 0, ie. `(-1, 1), (-1, 3)`, and select the pipe with max end, ie. `(-1, 3)`\n2. find all intervals with start positions <= 3, ie. `(2, 6)`, and select the pipe with max end, ie. `(2, 6)`\n3. find all intervals with start positions <= 6, ie. `(4, 6), (6, 8)`, and select the pipe with max end, ie. `(6, 8)`. Since 8 >= n, return count of selected pipes = 3\n```\n\nclass Solution:\n def minTaps(self, n: int, ranges: List[int]) -> int: \n \n # Convert the ranges for pipes into intervals\n # and filter out pipes with range 0\n intervals = [(i-ranges[i], i+ranges[i]) \n for i in range(n+1) \n if ranges[i] != 0]\n \n # Sort the intervals by their starting points\n intervals.sort()\n \n start = count = i = 0\n while True:\n \n # Find an interval starting at <= start, with the max end\n curr = None\n while i < len(intervals) and intervals[i][0] <= start:\n if not curr or intervals[i][1] > curr[1]: \n curr = intervals[i]\n i += 1\n \n # if we couldn\'t find such an interval\n if not curr:\n return -1\n \n count += 1\n \n # if we have reached the end of the garden\n if curr[1] >= n:\n return count \n \n # update the start to the end of the selected interval\n start = curr[1] \n```
17
0
['Greedy', 'Python']
1
minimum-number-of-taps-to-open-to-water-a-garden
✅Easy Solution✅Python/C#/C++/Java/C🔥Clean Code🔥
easy-solutionpythonccjavacclean-code-by-ruk88
Problem\n\nThis problem involves finding the minimum number of taps that need to be open to water the entire garden. The garden is represented as a one-dimensio
MrAke
NORMAL
2023-08-31T03:29:03.062100+00:00
2023-08-31T03:29:03.062121+00:00
1,100
false
# Problem\n***\nThis problem involves finding the minimum number of taps that need to be open to water the entire garden. The garden is represented as a one-dimensional axis from 0 to n, and each tap can water a specific range around its location. The goal is to determine the minimum number of taps you need to turn on to ensure that the entire garden is watered.\n***\n# Solution\n1. Initialize a list dp of size (n + 1) to store the minimum number of taps needed to water each position.\n\n2. Initialize dp[0] to 0, because no taps are needed to water the starting position.\n\n3. Iterate through each tap location using the enumerate function. For each tap:\n**a**. Calculate the leftmost and rightmost positions that can be watered by the current tap. These positions are given by max(0, i - tap_range) and min(n, i + tap_range) respectively, where i is the current tap\'s position.\n**b**. Iterate through the positions that can be watered by the current tap (from left to right). For each position j, update dp[j] to be the minimum of its current value and dp[left] + 1. This means that if you can reach the current position j from the left position of the current tap, you update the minimum number of taps required to reach position j.\n\n4. After iterating through all taps, the value of dp[n] will represent the minimum number of taps required to water the entire garden. If dp[n] is still the initial maximum value (indicating that the garden couldn\'t be watered), return -1. Otherwise, return the value of dp[n].\n\nThe dynamic programming approach ensures that each position in the garden is reached using the minimum number of taps. By updating the dp array as taps are considered, the algorithm efficiently calculates the minimum number of taps required to water the entire garden.\n\n**Overall, the provided solution is a well-implemented approach to solving the given problem efficiently.**\n\n![Screenshot 2023-08-20 065922.png](https://assets.leetcode.com/users/images/cc56207e-0bc5-4e51-90d0-dd76c3536315_1693452467.6303158.png)\n\n\n```Python3 []\nclass Solution:\n def minTaps(self, n: int, ranges: List[int]) -> int:\n dp = [sys.maxsize] * (n + 1)\n\n dp[0] = 0\n\n for i, tap_range in enumerate(ranges):\n left = max(0, i - tap_range)\n right = min(n, i + tap_range)\n\n for j in range(left, right + 1):\n dp[j] = min(dp[j], dp[left] + 1)\n\n return dp[n] if dp[n] < sys.maxsize else -1\n```\n```python []\nclass Solution:\n def minTaps(self, n: int, ranges: List[int]) -> int:\n dp = [sys.maxsize] * (n + 1)\n\n dp[0] = 0\n\n for i, tap_range in enumerate(ranges):\n left = max(0, i - tap_range)\n right = min(n, i + tap_range)\n\n for j in range(left, right + 1):\n dp[j] = min(dp[j], dp[left] + 1)\n\n return dp[n] if dp[n] < sys.maxsize else -1\n```\n```C# []\npublic class Solution {\n public int MinTaps(int n, int[] ranges) {\n int[] dp = new int[n + 1];\n for (int i = 1; i <= n; i++) {\n dp[i] = n + 2; // Set to a value larger than n + 1 to handle the all-zero ranges case\n }\n\n dp[0] = 0;\n\n for (int i = 0; i <= n; i++) {\n int tapRange = ranges[i];\n int left = Math.Max(0, i - tapRange);\n int right = Math.Min(n, i + tapRange);\n\n for (int j = left; j <= right; j++) {\n dp[j] = Math.Min(dp[j], dp[left] + 1);\n }\n }\n\n return dp[n] <= n + 1 ? dp[n] : -1;\n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n int minTaps(int n, std::vector<int>& ranges) {\n std::vector<int> dp(n + 1, n + 2); // Set to a value larger than n + 1 to handle the all-zero ranges case\n dp[0] = 0;\n\n for (int i = 0; i <= n; i++) {\n int tapRange = ranges[i];\n int left = std::max(0, i - tapRange);\n int right = std::min(n, i + tapRange);\n\n for (int j = left; j <= right; j++) {\n dp[j] = std::min(dp[j], dp[left] + 1);\n }\n }\n\n return dp[n] <= n + 1 ? dp[n] : -1;\n }\n};\n```\n```Java []\nimport java.util.Arrays;\n\nclass Solution {\n public int minTaps(int n, int[] ranges) {\n int[] dp = new int[n + 1];\n Arrays.fill(dp, n + 2); // Set to a value larger than n + 1 to handle the all-zero ranges case\n dp[0] = 0;\n\n for (int i = 0; i <= n; i++) {\n int tapRange = ranges[i];\n int left = Math.max(0, i - tapRange);\n int right = Math.min(n, i + tapRange);\n\n for (int j = left; j <= right; j++) {\n dp[j] = Math.min(dp[j], dp[left] + 1);\n }\n }\n\n return dp[n] <= n + 1 ? dp[n] : -1;\n }\n}\n```
16
2
['C', 'Python', 'C++', 'Java', 'Python3', 'C#']
1
minimum-number-of-taps-to-open-to-water-a-garden
O(n) time complexity greedy implementation in C++ with comments
on-time-complexity-greedy-implementation-l26r
\nclass Solution {\npublic:\n int minTaps(int n, vector<int>& nums) {\n vector<int> maxRight(n+1); //maxRight[Left]=the farest index Left can reach\n
djw612
NORMAL
2020-07-15T05:02:25.468267+00:00
2020-07-15T05:02:25.468306+00:00
1,461
false
```\nclass Solution {\npublic:\n int minTaps(int n, vector<int>& nums) {\n vector<int> maxRight(n+1); //maxRight[Left]=the farest index Left can reach\n \n // scan each tap, update the farest index each Left can reach.\n for (int i =0;i<=n;i++){\n int L = max(0,i-nums[i]);\n int R = min(n,i+nums[i]);\n maxRight[L] = max(maxRight[L],R);\n } \n\n int next_right_most = maxRight[0];// the rightmost index which is accessible by one more tap\n int cur_right_most = maxRight[0];// cur right most accessible index\n int taps = 1;\n\n for(int i=1;i<=n;i++){\n // i is the Left to scan.\n // for each i, we find the next right most index to cover.\n if(i>next_right_most){\n //still can\'t find the next connected range\n //this implies all indices in[0,next_right_most] cannot reach the rest part of the garden.\n //because if they can, the next_right_most should have been updated to larger.(contradicted)\n return -1;\n }\n if (i>cur_right_most){\n //this implies Left of current scan is disconnected from previous right_most index.\n //It\'s time to add an additional tap to cover previous indices\n taps++;\n cur_right_most = next_right_most;\n }\n \n //only update when i(which is the Left)<cur_right_most\n //because only in this case, the tap is overlapped with the previous tap\n next_right_most = max(next_right_most,maxRight[i]); //greedy. find the rightmost index\n }\n return taps; \n }\n};\n```
16
0
[]
4