title
stringlengths
3
77
title_slug
stringlengths
3
77
question_content
stringlengths
38
1.55k
tag
stringclasses
707 values
level
stringclasses
3 values
question_hints
stringlengths
19
3.98k
view_count
int64
8
630k
vote_count
int64
5
10.4k
content
stringlengths
0
43.9k
__index_level_0__
int64
0
109k
Merge k Sorted Lists
merge-k-sorted-lists
You are given an array of k linked-lists lists, each linked-list is sorted in ascending order. Merge all the linked-lists into one sorted linked-list and return it.
Linked List,Divide and Conquer,Heap (Priority Queue),Merge Sort
Hard
null
711
5
```\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 mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:\n \n if not lists or len(lists)==0:\n return None\n \n \n while(len(lists)>1):\n mergedlist =[]\n \n for i in range(0,len(lists),2):\n \n l1 = lists[i]\n l2 = lists[i+1] if i+1<len(lists) else None\n \n mergedlist.append(self.mergetwo(l1,l2))\n \n lists = mergedlist\n \n return lists[0]\n \n def mergetwo(self,l1,l2):\n \n dummy = ListNode()\n tail = dummy\n \n while l1 and l2:\n if l1.val<l2.val:\n tail.next = l1\n l1 = l1.next\n else:\n tail.next = l2\n l2 = l2.next\n \n tail = tail.next\n \n \n if l1:\n tail.next = l1\n \n if l2:\n tail.next = l2\n \n return dummy.next \n \n```
2,295
Merge k Sorted Lists
merge-k-sorted-lists
You are given an array of k linked-lists lists, each linked-list is sorted in ascending order. Merge all the linked-lists into one sorted linked-list and return it.
Linked List,Divide and Conquer,Heap (Priority Queue),Merge Sort
Hard
null
3,407
44
**UPVOTE if you like (\uD83C\uDF38\u25E0\u203F\u25E0), If you have any question, feel free to ask.**\n\nThe main challenge in the problem is the fact that the number of lists `k` can be huge and iterating over list heads every time attaching a new node to the result would be time-consuming. Essentially what is important to know on every merging step is what is the smallest node among all list heads. We can utilize the priority queue to fast access the current smallest node. \n\nFirst, we form the initial heap with tuples containing val and node itself. Notice that in Python implementation of the heap, the first element of the tuple is considered as a priority. In case the heap already has an element with the same priority, the Python compares the next element of the tuple. That is why we need index `i` in the second place.\n\nThen we run a cycle until the heap is empty. On every step, we pop out the smallest node and attach it to the result. Right away we push to the heap the next node.\n\nTime: **O(k * n * log(k))** - scan and manipulation with heap\nSpace: **O(k)** - for the heap\n\nRuntime: 96 ms, faster than **93.66%** of Python3 online submissions for Merge k Sorted Lists.\nMemory Usage: 17.9 MB, less than **61.96%** of Python3 online submissions for Merge k Sorted Lists.\n\n```\ndef mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:\n\theap, res = [], ListNode()\n\tfor i, list in enumerate(lists):\n\t\tif list: \n\t\t\theappush(heap, (list.val, i, list))\n\n\tcur = res\n\twhile heap:\n\t\t_, i, list = heappop(heap)\n\t\tif list.next:\n\t\t\theappush(heap, (list.next.val, i, list.next))\n\n\t\tcur.next, cur = list, list\n\n\treturn res.next\n```\n\n**UPVOTE if you like (\uD83C\uDF38\u25E0\u203F\u25E0), If you have any question, feel free to ask.**
2,298
Swap Nodes in Pairs
swap-nodes-in-pairs
Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)
Linked List,Recursion
Medium
null
56,094
921
As mentioned in the question we have to **exchange the nodes itself (and not just their values)**, and this solution follows this constraint.\n\nI will be placing a `dummy node` before the head node so that the code we write can also be applicable to the head node also, and we don\'t have to specifically write different conditions for the head node.\n\n#### Example:\n***Given Linked List***\n\n![image]()\n\n ***Final Linked List***\n\n![image]()\n\n\nLet\'s now understand the **approach**\n\n1. As mentioned earlier, we will place a `dummyNode` before the head node.\n\n![image]()\n\n\n2. Now, let the head be our `currNode`. That means the `node with value 1` is the currNode, and we have to swap it with the `node with value 2`. So for this, we will also have to keep track of the node previous to the currNode, let it be `prevNode`, as it\'s next pointer value will have to change after we swap the currNode and the node next to currNode.\n\n![image]()\n\n3. Now the very first thing to do is change the `next pointer of prevNode to point to currNode->next`. Why?? Because in the answer we want the `node with value 2` after the dummyNode. Right? So we will have to connect `dummyNode` (prevNode) to the `node with value 2` (currNode->next). This means\n```cpp\nprevNode->next = currNode->next\n```\n\n![image]()\n\n\n4. Now, in our finl answer `node with value 1` should be at the place of `node with value 2`. So the next pointer of `node with value 1` should point to whatever the `node with value 2` is pointing to originally. That means we will have to change `currNode->next` to the `next of next of prevNode`, as currently prevNode is dummyNode, prevNode->next is node with value 2 and prevNode->next->next = next of node with value 2. This means\n```cpp\ncurrNode->next = prevNode->next->next\n```\n\n![image]()\n\n\n5. Now, as in the answer the `node with value 2` should point to `node with value 1`. That means\n```cpp\nprevNode->next->next = currNode\n```\n\n![image]()\n\n\n6. After this iteration, nodes 1 and 2 will get swapped and our linked list will look like this.\n\n![image]()\n\n\n7. Now for the next iteration, we have to swap `nodes with values 3 and 4`. For that the `prevNode` should point to `node with value 1` and the `currNode` should point to `node with value 3`. This means\n```cpp\nprevNode = currNode\ncurrNode = currNode->next\n```\n\n![image]()\n\n\n\n\n8. We should stop this procedure when either there is no nodes left to swap or there is only one node left which cannot be swapped with any node.\n\n9. At the end, as we can see that our head of the list has been misplaced in the procedure of swapping, so we can return `dummyNode->next` to return the swapped linked list.\n\n\n#### Code\n```cpp\nListNode* swapPairs(ListNode* head) {\n if(!head || !head->next) return head; //If there are less than 2 nodes in the given nodes, then no need to do anything just return the list as it is.\n\t\t\n ListNode* dummyNode = new ListNode();\n \n ListNode* prevNode=dummyNode;\n ListNode* currNode=head;\n \n while(currNode && currNode->next){\n prevNode->next = currNode->next;\n currNode->next = prevNode->next->next;\n prevNode->next->next = currNode;\n \n prevNode = currNode;\n currNode = currNode->next;\n }\n \n return dummyNode->next;\n }\n\n```\n\n#### Complexity:\n***TC*** **= O(n)**\n***SC*** **= O(1)**\n\n***Plz upvote if you liked the post***\n\n\n
2,300
Swap Nodes in Pairs
swap-nodes-in-pairs
Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)
Linked List,Recursion
Medium
null
41,049
635
***Brief note about Question-***\n* We have to *swap every two adjacent nodes and return its head*.\n```\nLet\'s take an example not given in question -\nSuppose our head pointer given to us as [1,9,2,8,3,7]\n\nSo, we have to swap every two adjcant nodes,\nthe answer should be [9,1,8,2,7,3]\n```\n_______________\n***Solution - I (using recursion, Accepted)-***\n* The very basic thing that is given to us is, **it is given in form of linked list**.\n* We have a advantage by having linked list, How?\n* For swapping every two adjcant nodes, we will be able to just change the link of nodes.\n* See how we change links on the first example.\n![image]()\n\n\n* I have mention everything in image itself, and also add comment in code also, but if u have still doubt or suggestion,please put that in comment part.\n ____________\n**Code (C++)**\n```\nclass Solution {\npublic:\n ListNode* swapPairs(ListNode* head) {\n // if head is NULL OR just having a single node, then no need to change anything \n if(head == NULL || head -> next == NULL) \n {\n return head;\n }\n \n ListNode* temp; // temporary pointer to store head -> next\n temp = head->next; // give temp what he want\n \n head->next = swapPairs(head->next->next); // changing links\n temp->next = head; // put temp -> next to head\n \n return temp; // now after changing links, temp act as our head\n }\n};\n```\n***`If u find this useful , please consider to give a upvote!!`***\n
2,301
Swap Nodes in Pairs
swap-nodes-in-pairs
Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)
Linked List,Recursion
Medium
null
36,310
174
**UPVOTE if you like (\uD83C\uDF38-_-\'), If you have any question, feel free to ask.**\n\nJust a bunch of placeholders, edge cases, and strange errors about a cycle meanwhile :(\n\nprev cur cur porev next cur prev pasdfaslfjgnzdsf;ljgfsdaz;lkjkfgn\n\nTime: **O(n)** - iterate\nSpace: **O(1)**\n\n```\ndef swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:\n\tif not head: return head\n\n\tprev, cur, ans = None, head, head.next\n\twhile cur and cur.next:\n\t\tadj = cur.next\n\t\tif prev: prev.next = adj\n\n\t\tcur.next, adj.next = adj.next, cur\n\t\tprev, cur = cur, cur.next\n\n\treturn ans or head\n```\n\n**UPVOTE if you like (\uD83C\uDF38-_-\'), If you have any question, feel free to ask.**
2,302
Swap Nodes in Pairs
swap-nodes-in-pairs
Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)
Linked List,Recursion
Medium
null
1,659
13
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe will convert the list into the list with dummy head and dummy tail. It will help us to maintain pointer and will save us from writing edge cases for null pointers.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nEg. Given list is `1 -> 2 -> 3 -> 4`. We will convert it to `-1 -> 1 -> 2 -> 3 -> 4 -> -1`. Now our head will point to dummy head.\n\nWe will keep track of three pointer and will reverse every pair of elements,\n1. prev - which will link the reversed element (from a pair of elements), this pointer is immediate left of the current pair\n2. cur - first element of current pair\n3. next - second element of current pair\n\nIf we look at this example `-1 -> 1 -> 2 -> 3 -> 4 -> -1`, then in the first iteration prev would be -1, cur would be 1 and next would be 2.\n\nAfter swapping a pair list will look like this `-1 -> 2 -> 1 -> 3 -> 4 -> -1`. Now we will have our next pair which is `3 -> 4`. So prev would be 1, curr would be at 3 and next would be at 4. \n\nAfter second iteration list will look like `-1 -> 2 -> 1 -> 4 -> 3 -> -1`.\n\nNow, The list is swapped in pairs of two elements. We just have to remove dummy head and dummy tail.\n\nFinal answer: `2 -> 1 -> 4 -> 3`\n\n**NOTE 1:** ***Odd size list handled in the code. Just emit the last element from being swapped with dummy tail.***\n**NOTE 2:** ***Code is self explanatory.***\n\n### Iteration Steps Explanation\n![image.png]()\n\n# Complexity\n- Time complexity: $$O(n)$$\n - As we are traversing list only once (ignore adding and deleting dummy head and dummy tail)\n\n- Space complexity: $$O(1)$$\n - As we have not used any space (containers) except the pointers.\n\n# Code\n```\nclass Solution {\npublic:\n ListNode* swapPairs(ListNode* head) {\n // if list is null or contains one element then return the list itself (null => null & `1` => `1`)\n if (!head or !head->next)\n return head;\n\n // Adding dummy head\n ListNode *dummyHead = new ListNode(-1);\n dummyHead->next = head;\n head = dummyHead;\n\n // Adding dummy tail\n ListNode *dummyTail = new ListNode(-1);\n ListNode *ptr = head;\n while (ptr->next)\n ptr = ptr->next;\n ptr->next = dummyTail;\n\n // assigning prev, cur and next for first iteration\n ListNode *prev = head, *cur = head->next, *next = head->next->next;\n while (next and next->val != -1)\n {\n // Check above image\n ListNode *nextCur = next->next; // 1\n prev->next = next; // 2\n cur->next = next->next; // 3\n next->next = cur; // 4\n\n prev = cur; // 5\n cur = nextCur; // 6\n next = cur->next; // 7\n } \n\n // Remove dummy tail\n ListNode *remove = head;\n while(remove->next->val != -1)\n remove = remove->next;\n remove->next = NULL;\n\n // remove dummy head\n return head = head->next;\n }\n};\n```\n### Upvote if it helped you !!!\n![image.png]()\n
2,325
Swap Nodes in Pairs
swap-nodes-in-pairs
Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)
Linked List,Recursion
Medium
null
2,881
25
# 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* swapPairs(ListNode* head) {\n if(head==NULL || head->next==NULL)return head;\n ListNode* temp=swapPairs(head->next->next);\n ListNode* t=head;\n head=head->next;\n head->next=t;\n head->next->next=temp;\n return head;\n }\n};\n```\n![upvote (2).jpg]()\n
2,326
Swap Nodes in Pairs
swap-nodes-in-pairs
Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)
Linked List,Recursion
Medium
null
10,284
54
**!! BIG ANNOUNCEMENT !!**\nI am currently Giving away my premium content well-structured assignments and study materials to clear interviews at top companies related to computer science and data science to my current Subscribers. This is only for first 10,000 Subscribers. **DON\'T FORGET** to Subscribe\n\n# Search \uD83D\uDC49 `Tech Wired Leetcode` to Subscribe\n\n# Video Solution\n\n# Search \uD83D\uDC49 `Swap Nodes in Pairs by Tech Wired`\n\n# or\n\n# Click the Link in my Profile\n\n# Approach:\nThe approach used in the code is to traverse the linked list and swap adjacent pairs of nodes. This is done iteratively by maintaining a current pointer that points to the previous node before the pair to be swapped. The swapping is done by modifying the next pointers of the nodes.\n\n# Intuition:\nThe intuition behind the code is to break down the problem into smaller subproblems. By swapping two nodes at a time, we can gradually swap adjacent pairs throughout the linked list. This is achieved by manipulating the next pointers of the nodes.\n\nThe use of a dummy node helps in handling the edge case where the head of the list needs to be swapped. It serves as a placeholder for the new head of the modified list.\n\nThe while loop iterates as long as there are at least two nodes remaining in the list. In each iteration, the current pair of nodes is swapped by adjusting the next pointers accordingly.\n\n\n\n```Python []\nclass Solution:\n def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:\n\n if not head or not head.next: return head\n\n dummy = ListNode(0)\n dummy.next = head\n curr = dummy\n\n while curr.next and curr.next.next:\n first = curr.next\n second = curr.next.next\n curr.next = second\n first.next = second.next\n second.next = first\n curr = curr.next.next\n \n return dummy.next\n```\n```Java []\nclass Solution {\n public ListNode swapPairs(ListNode head) {\n if (head == null || head.next == null) {\n return head;\n }\n \n ListNode dummy = new ListNode(0);\n dummy.next = head;\n ListNode curr = dummy;\n \n while (curr.next != null && curr.next.next != null) {\n ListNode first = curr.next;\n ListNode second = curr.next.next;\n curr.next = second;\n first.next = second.next;\n second.next = first;\n curr = curr.next.next;\n }\n \n return dummy.next;\n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n ListNode* swapPairs(ListNode* head) {\n if (head == nullptr || head->next == nullptr) {\n return head;\n }\n \n ListNode* dummy = new ListNode(0);\n dummy->next = head;\n ListNode* curr = dummy;\n \n while (curr->next != nullptr && curr->next->next != nullptr) {\n ListNode* first = curr->next;\n ListNode* second = curr->next->next;\n curr->next = second;\n first->next = second->next;\n second->next = first;\n curr = curr->next->next;\n }\n \n return dummy->next;\n }\n};\n```\n# An Upvote will be encouraging \uD83D\uDC4D\n\n
2,337
Swap Nodes in Pairs
swap-nodes-in-pairs
Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)
Linked List,Recursion
Medium
null
46
7
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFirst intuition that comes to mind is that swap the pairs of nodes and modify the next pointers for each pair of nodes.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe basic ideology of recursion\n"Solve the first case, other cases will be handled by Recursion."\n\nHere, solve for the first pair of nodes, i.e., swap the first two nodes and modify their next pointers. First node will now point to the node where second node was pointing to and second node will point to the first node.\n\nCall the function recursively and store the head (first) node of the remaining part of the linked list in the next pointer of the first node.\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```\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* swapPairs(ListNode* head) {\n if (head == NULL || head->next==NULL){\n return head;\n }\n\n ListNode* temp1 = head;\n ListNode* temp2 = head->next;\n\n temp1->next = temp2->next;\n temp2->next = temp1;\n\n if (temp1->next!=NULL){\n temp1->next = swapPairs(temp1->next);\n }\n\n return temp2;\n }\n};\n```
2,344
Swap Nodes in Pairs
swap-nodes-in-pairs
Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)
Linked List,Recursion
Medium
null
98,865
787
public class Solution {\n public ListNode swapPairs(ListNode head) {\n if ((head == null)||(head.next == null))\n return head;\n ListNode n = head.next;\n head.next = swapPairs(head.next.next);\n n.next = head;\n return n;\n }\n }
2,345
Swap Nodes in Pairs
swap-nodes-in-pairs
Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)
Linked List,Recursion
Medium
null
1,436
6
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n1. Recursively traverse the list to the end.\n2. On the way back return every node at an even number position.\n3. Update the `next` pointers for nodes at odd and even positions with their own logic.\n\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$ on the stack\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n int cnt = 0;\n\n public ListNode swapPairs(ListNode node) {\n if (node == null) return null;\n\n cnt++;\n var ret = swapPairs(node.next);\n\n if (cnt % 2 == 1 && ret != null) {\n // node -> the first (left) node in each pair\n node.next = ret.next;\n ret.next = node;\n } else {\n // node -> the second (right) node in each pair\n node.next = ret;\n ret = node;\n }\n cnt--;\n return ret;\n }\n}\n```\nIf you like my solution, please upvote it!
2,350
Swap Nodes in Pairs
swap-nodes-in-pairs
Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)
Linked List,Recursion
Medium
null
16,749
342
### 24. Swap Nodes in Pairs\n\n```python\nclass Solution(object):\n def swapPairs(self, head):\n if not head or not head.next: return head\n dummy = ListNode(0)\n dummy.next = head\n cur = dummy\n \n while cur.next and cur.next.next:\n first = cur.next\n sec = cur.next.next\n cur.next = sec\n first.next = sec.next\n sec.next = first\n cur = cur.next.next\n return dummy.next \n```\n![]()\n\n#### Recursive\n```python\nclass Solution(object):\n def swapPairs(self, head):\n if not head or not head.next: return head\n new_start = head.next.next\n head, head.next = head.next, head\n head.next.next = self.swapPairs(new_start)\n return head\n```
2,351
Swap Nodes in Pairs
swap-nodes-in-pairs
Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)
Linked List,Recursion
Medium
null
6,312
13
\n\n# Code\nPLEASE UPVOTE IF YOU LIKE.\n\n```\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 swapPairs(ListNode head) {\n if(head == null || head.next == null)return head;\n ListNode d = new ListNode(0), a;\n d.next = head;\n a=d;\n while(head!=null&&head.next!=null) {\n a.next = head.next;\n head.next = head.next.next;\n a.next.next = head;\n a = a.next.next;\n head = head.next;\n }\n return d.next;\n }\n}\n```
2,352
Swap Nodes in Pairs
swap-nodes-in-pairs
Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)
Linked List,Recursion
Medium
null
2,022
6
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nStart\n# Approach\n<!-- Describe your approach to solving the problem. -->\nCheck if the linked list is empty or has only one node. If so, return the head of the linked list. \n\nOtherwise, create a pointer next to the second node in the linked list.\n\nSet the next pointer of the first node to the result of recursively calling swapPairs on the third node (if it exists) and beyond.\n\nSet the next pointer of the next node to the first node.\nReturn the next node as the new head of the linked list.\nDone !!!!\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(N)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(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 */\nclass Solution {\npublic:\n ListNode* swapPairs(ListNode* head) {\n if (!head || !head->next) {\n return head;\n }\n ListNode* next = head->next;\n head->next = swapPairs(next->next);\n next->next = head;\n return next;\n}\n\n};\n```\n![7abc56.jpg]()\n
2,357
Swap Nodes in Pairs
swap-nodes-in-pairs
Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)
Linked List,Recursion
Medium
null
1,761
5
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n**Three Pointer Iterative Approach where the swapping is done with help of Three Pointers**\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe approach to solve this problem is the three pointer approach, where I have taken the three pointers and with the help of that the swapping of nodes is done, The programming language used is Java. Here the three nodes p for previous, c for current and cn for current_next is taken and also the d node is taken at the starting which will act as p in the first iteration. \n\nSuppose the linked list is given\n1-->2-->3-->4-->null\nthen first we have declared the d node such that it\'s next pointer points to the head of the linked list hence\nD-->1-->2-->3-->4-->null\nNow During the first Iteration\n![Untitled.jpg]()\nAfter First Iteration \n![Untitled.jpg]()\nHence as the processing of swapping will be done the pointers will be moved as \n![Untitled.jpg]()\nAnd again the processing of swapping will be done\nTill the c and cn is null.\n\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n**Time Complexity - O(n)**\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n**Space Compleixty - O(1)**\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 swapPairs(ListNode head) {\n ListNode d = new ListNode(0);\n d.next = head;\n ListNode p = d;\n ListNode c = d.next;\n while(c!=null){\n ListNode cn = c.next;\n if(cn==null){\n break;\n }\n c.next = cn.next;\n cn.next=p.next;\n p.next = cn;\n p = c;\n c = c.next;\n }\n return d.next;\n }\n}\n```
2,358
Swap Nodes in Pairs
swap-nodes-in-pairs
Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)
Linked List,Recursion
Medium
null
1,557
7
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\ni have used basic concept of linkedlist and recursive call\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)$$ -->\nO(N)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1)\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 swapPairs(ListNode head) {\n if(head==null||head.next==null){\n return head;\n }\n ListNode prv=head;\n ListNode curr=head.next;\n ListNode next=head.next.next;\n head=curr;\n head.next=prv;\n head.next.next=swapPairs(next);\n return head;\n }\n}\n```
2,360
Swap Nodes in Pairs
swap-nodes-in-pairs
Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)
Linked List,Recursion
Medium
null
4,862
24
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTraverse the list and swap pairs of nodes one by one.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- The node "ans" is to point to the head of the original list. It then uses a "curr" node to traverse the list and swap pairs of nodes. The loop continues as long as there are at least two more nodes to swap.\n\n- Inside the loop, the solution uses two temporary nodes, "t1" and "t2", to hold the first and second nodes of the pair. Then, it updates the pointers to swap the nodes, and moves "curr" two nodes ahead. At the end, it returns the modified list starting from the next node of the "ans" node.\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```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 swapPairs(ListNode head) {\n if (head == null || head.next == null) {\n return head;\n }\n ListNode ans =new ListNode(0);\n ans.next=head;\n ListNode curr=ans;\n while (curr.next != null && curr.next.next != null) {\n ListNode t1 = curr.next;\n ListNode t2 = curr.next.next;\n curr.next = t2;\n t1.next = t2.next;\n t2.next = t1;\n curr = curr.next.next;\n } \n return ans.next;\n }\n}\n```\n```python []\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 swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:\n if not head or not head.next:\n return head\n \n ans = ListNode(0)\n ans.next = head\n curr = ans\n \n while curr.next and curr.next.next:\n t1 = curr.next\n t2 = curr.next.next\n curr.next = t2\n t1.next = t2.next\n t2.next = t1\n curr = curr.next.next\n \n return ans.next\n```\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* swapPairs(ListNode* head) {\n if (head == NULL || head->next == NULL) {\n return head;\n }\n struct ListNode* ans = (struct ListNode*) malloc(sizeof(struct ListNode));\n ans->next = head;\n struct ListNode* curr = ans;\n while (curr->next != NULL && curr->next->next != NULL) {\n struct ListNode* t1 = curr->next;\n struct ListNode* t2 = curr->next->next;\n curr->next = t2;\n t1->next = t2->next;\n t2->next = t1;\n curr = curr->next->next;\n }\n return ans->next;\n }\n};\n```\n```Javascript []\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 swapPairs = function(head) {\n if (head == null || head.next == null) {\n return head;\n }\n let ans = new ListNode(0);\n ans.next = head;\n let curr = ans;\n while (curr.next != null && curr.next.next != null) {\n let t1 = curr.next;\n let t2 = curr.next.next;\n curr.next = t2;\n t1.next = t2.next;\n t2.next = t1;\n curr = curr.next.next;\n }\n return ans.next;\n};\n```\n```C# []\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 SwapPairs(ListNode head) {\n if (head == null || head.next == null) {\n return head;\n }\n ListNode ans = new ListNode(0);\n ans.next = head;\n ListNode curr = ans;\n while (curr.next != null && curr.next.next != null) {\n ListNode t1 = curr.next;\n ListNode t2 = curr.next.next;\n curr.next = t2;\n t1.next = t2.next;\n t2.next = t1;\n curr = curr.next.next;\n }\n return ans.next; \n }\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 swapPairs(head: ListNode?): ListNode? {\n if (head == null || head.next == null) {\n return head\n }\n val ans = ListNode(0)\n ans.next = head\n var curr: ListNode? = ans\n while (curr?.next != null && curr.next?.next != null) {\n val t1 = curr.next\n val t2 = curr.next?.next\n curr.next = t2\n t1.next = t2?.next\n t2?.next = t1\n curr = curr.next?.next\n }\n return ans.next\n }\n}\n```\n```C []\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * struct ListNode *next;\n * };\n */\nstruct ListNode* swapPairs(struct ListNode* head){\n if (head == NULL || head->next == NULL) {\n return head;\n }\n struct ListNode* ans = (struct ListNode*) malloc(sizeof(struct ListNode));\n ans->next = head;\n struct ListNode* curr = ans;\n while (curr->next != NULL && curr->next->next != NULL) {\n struct ListNode* t1 = curr->next;\n struct ListNode* t2 = curr->next->next;\n curr->next = t2;\n t1->next = t2->next;\n t2->next = t1;\n curr = curr->next->next;\n }\n return ans->next;\n}\n```\n\nUPVOTES ARE ENCOURAGING!
2,361
Swap Nodes in Pairs
swap-nodes-in-pairs
Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)
Linked List,Recursion
Medium
null
83,375
403
Three different implementations of the same algorithm, taking advantage of different strengths of the three languages. I suggest reading all three, even if you don't know all three languages.\n\nAll three of course work swap the current node with the next node by rearranging pointers, then move on to the next pair, and repeat until the end of the list.\n\n---\n\n**C++**\n\nPointer-pointer `pp` points to the pointer to the current node. So at first, `pp` points to `head`, and later it points to the `next` field of ListNodes. Additionally, for convenience and clarity, pointers `a` and `b` point to the current node and the next node.\n\nWe need to go from `*pp == a -> b -> (b->next)` to `*pp == b -> a -> (b->next)`. The first three lines inside the loop do that, setting those three pointers (from right to left). The fourth line moves `pp` to the next pair.\n\n ListNode* swapPairs(ListNode* head) {\n ListNode **pp = &head, *a, *b;\n while ((a = *pp) && (b = a->next)) {\n a->next = b->next;\n b->next = a;\n *pp = b;\n pp = &(a->next);\n }\n return head;\n }\n\n---\n\n**Python**\n\nHere, `pre` is the previous node. Since the head doesn't have a previous node, I just use `self` instead. Again, `a` is the current node and `b` is the next node.\n\nTo go from `pre -> a -> b -> b.next` to `pre -> b -> a -> b.next`, we need to change those three references. Instead of thinking about in what order I change them, I just change all three at once.\n\n def swapPairs(self, head):\n pre, pre.next = self, head\n while pre.next and pre.next.next:\n a = pre.next\n b = a.next\n pre.next, b.next, a.next = b, a, b.next\n pre = a\n return self.next\n\n---\n\n**Ruby**\n\nAgain, `pre` is the previous node, but here I create a dummy as previous node of the head. And again, `a` is the current node and `b` is the next node. This time I go one node further and call it `c`.\n\nTo go from `pre -> a -> b -> c` to `pre -> b -> a -> c`, we need to change those three references. Here I chain the assignments, pretty much directly saying "`pre` points to `b`, which points to `a`, which points to `c`".\n\n def swap_pairs(head)\n pre = dummy = ListNode.new 0\n pre.next = head\n while a = pre.next and b = a.next\n c = b.next\n ((pre.next = b).next = a).next = c\n pre = a\n end\n dummy.next\n end
2,363
Swap Nodes in Pairs
swap-nodes-in-pairs
Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)
Linked List,Recursion
Medium
null
1,472
6
# Please Upvote!!!\n\n\n![Screenshot 2023-05-16 at 09.08.07.png]()\n\n\n\n# Intuition & Approach\n<!-- Describe your approach to solving the problem. -->\nTo swap every two adjacent nodes in a linked list without modifying the node values, you can manipulate the pointers of the nodes. Here\'s an algorithm to solve the problem:\n\nInitialize a dummy node and set its next pointer to the head of the given linked list. This dummy node will be useful as the new head of the modified list.\nInitialize three pointers: prev, curr, and next. Set prev to the dummy node and curr to the head of the list.\nIterate through the list while curr and curr.next are not null:\nSet next to curr.next.\nPoint curr.next to next.next.\nPoint next.next to curr.\nPoint prev.next to next.\nMove prev to curr.\nMove curr to curr.next.\nReturn the modified list\'s head, which is the dummy node\'s next node.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(N)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1)\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 swapPairs(ListNode head) {\n if(head==null||head.next==null){\n return head;\n }\n ListNode nodeSlow = null, nodeFast = head.next;\n ListNode temp = head;\n temp.next = nodeFast.next;\n nodeFast.next = temp;\n head = nodeFast;\n nodeFast = nodeFast.next;\n nodeSlow = head;\n while(nodeFast.next!=null){\n nodeSlow = nodeSlow.next;\n nodeFast = nodeFast.next;\n\n if(nodeFast.next!=null) {\n nodeSlow.next = nodeFast.next;\n temp = nodeFast.next.next;\n nodeSlow.next.next = nodeFast;\n nodeFast.next = temp;\n nodeSlow = nodeSlow.next;\n }\n }\n return head;\n }\n}\n```
2,366
Swap Nodes in Pairs
swap-nodes-in-pairs
Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)
Linked List,Recursion
Medium
null
64,908
352
public ListNode swapPairs(ListNode head) {\n ListNode dummy = new ListNode(0);\n dummy.next = head;\n ListNode current = dummy;\n while (current.next != null && current.next.next != null) {\n ListNode first = current.next;\n ListNode second = current.next.next;\n first.next = second.next;\n current.next = second;\n current.next.next = first;\n current = current.next.next;\n }\n return dummy.next;\n }
2,367
Swap Nodes in Pairs
swap-nodes-in-pairs
Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)
Linked List,Recursion
Medium
null
630
5
\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 */\nclass Solution {\npublic:\n ListNode* swapPairs(ListNode* head) {\n if(head==NULL || head->next==NULL)\n return head;\n ListNode* temp=head->next;\n head->next=swapPairs(head->next->next);\n temp->next=head;\n return temp;\n }\n};\n```\nPlease **UPVOTE** if it helps \u2764\uFE0F\uD83D\uDE0A\nThank You and Happy To Help You!!\n\n
2,372
Swap Nodes in Pairs
swap-nodes-in-pairs
Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)
Linked List,Recursion
Medium
null
1,371
12
\n\n\n\n# BRUTE\n```JAVA []\npublic ListNode swapPairs(ListNode head) {\n List<ListNode> list = new ArrayList<>();\n ListNode temNode = head;\n while (temNode != null) {\n list.add(temNode);\n temNode = temNode.next;\n }\n for (int i = 0; i < list.size() - 1; i += 2) {\n int swapElement = list.get(i).val;\n list.get(i).val = list.get(i + 1).val;\n list.get(i + 1).val = swapElement;\n }\n return head;\n}\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# Intuition & Approach\n<!-- Describe your approach to solving the problem. -->\nwe first check if the input head is null or has only one node. If so, we return the head as it is. Otherwise, we create two nodes first and second and set them to the first and second nodes of the linked list, respectively. We then recursively call the swapPairs function on the next of the second node and set the next of the first node to the result. We then swap the next pointers of the first and second nodes and return the second node.\n\n# BETTER\n```JAVA []\npublic ListNode swapPairs(ListNode head) {\n if (head == null || head.next == null) {\n return head;\n }\n ListNode first = head;\n ListNode second = head.next;\n first.next = swapPairs(second.next);\n second.next = first;\n return second;\n}\n```\n# Complexity\n- Time complexity:O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(LOG(N))\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n# OPTIMAL\nWe create a dummy node and set its next to the head. We then create a current node and initialize it to the dummy node. We use a single loop to swap every two adjacent nodes. We do this by creating two nodes first and second and swapping their next pointers. We then update the current node to point to the second node and continue the loop. Finally, we return the next of the dummy node.The time complexity of this solution is O(n) as we need to traverse the entire linked list once.\n```JAVA []\npublic ListNode swapPairs(ListNode head) {\n if (head == null || head.next == null) {\n return head;\n }\n ListNode dummy = new ListNode(0);\n dummy.next = head;\n ListNode current = dummy;\n while (current.next != null && current.next.next != null) {\n ListNode first = current.next;\n ListNode second = current.next.next;\n first.next = second.next;\n second.next = first;\n current.next = second;\n current = current.next.next;\n }\n return dummy.next;\n}\n```\n```c++ []\nListNode* swapPairs(ListNode* head) {\n ListNode* dummy = new ListNode(0);\n dummy->next = head;\n ListNode* current = dummy;\n while (current->next != NULL && current->next->next != NULL) {\n ListNode* first = current->next;\n ListNode* second = current->next->next;\n first->next = second->next;\n second->next = first;\n current->next = second;\n current = current->next->next;\n }\n return dummy->next;\n}\n```\n```python []\ndef swapPairs(self, head: ListNode) -> ListNode:\n dummy = ListNode(0)\n dummy.next = head\n current = dummy\n while current.next and current.next.next:\n first = current.next\n second = current.next.next\n first.next = second.next\n second.next = first\n current.next = second\n current = current.next.next\n return dummy.next\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\n![BREUSELEE.webp]()\n\n# Please Upvote\uD83D\uDC4D\uD83D\uDC4D\nThanks for visiting my solution.\uD83D\uDE0A Keep Learning\nPlease give my solution an upvote! \uD83D\uDC4D \uD83C\uDD99\uD83C\uDD99\uD83C\uDD99\nIt\'s a simple way to show your appreciation and\nkeep me motivated. Thank you! \uD83D\uDE0A\n \u2B06 \u2B06 \u2B06 \u2B06 \u2B06 \u2B06 \u2B06 \u2B06 \u2B06 \n
2,375
Swap Nodes in Pairs
swap-nodes-in-pairs
Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)
Linked List,Recursion
Medium
null
2,715
15
# Approach\n\n1. Check if the list is empty or contains only one node. If so, there is no need to perform any swaps, so the original head is returned.\n2. Initialize three pointers: `newHead` to store the new head after swapping, `prev` to keep track of the previous node, and `curr` to iterate through the list.\n3. Enter a loop that continues as long as both `curr` and `curr->next` are not null.\n4. Inside the loop, create a pointer `next` to store the next node after `curr`.\n5. Update the next pointers of `curr` and `next` to perform the swap. Set `curr->next` to `next->next` to connect `curr` with the next pair of nodes.\n6. Set `next->next` to `curr` to swap the positions of `curr` and `next`.\n7. If `prev` is not null, update its `next` pointer to `next` to connect the previous pair with the swapped pair.\n8. Update `prev` to `curr` and `curr` to `curr->next` to move forward in the list.\n9. After the loop ends, return `newHead`, which stores the new head of the swapped list.\n\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)$$ -->\nThe time complexity of this algorithm is O(n), where n is the number of nodes in the linked list. This is because the algorithm iterates through the list once. The space complexity is O(1) because it uses a constant amount of additional space to store the pointers.\n\n# C++\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* swapPairs(ListNode* head) {\n if (!head || !head->next) {\n return head;\n }\n ListNode* newHead = head->next;\n ListNode* prev = nullptr;\n ListNode* curr = head;\n \n while (curr && curr->next) {\n ListNode* next = curr->next;\n curr->next = next->next;\n next->next = curr;\n \n if (prev) {\n prev->next = next;\n }\n \n prev = curr;\n curr = curr->next;\n }\n \n return newHead;\n }\n};\n```\n---\n# JAVA\n```\nclass Solution {\n public ListNode swapPairs(ListNode head) {\n if (head == null || head.next == null) {\n return head;\n }\n \n ListNode newHead = head.next;\n ListNode prev = null;\n ListNode curr = head;\n \n while (curr != null && curr.next != null) {\n ListNode next = curr.next;\n curr.next = next.next;\n next.next = curr;\n \n if (prev != null) {\n prev.next = next;\n }\n \n prev = curr;\n curr = curr.next;\n }\n \n return newHead;\n }\n}\n```\n---\n# Python\n```\nclass Solution(object):\n def swapPairs(self, head):\n if not head or not head.next:\n return head\n \n new_head = head.next\n prev = None\n curr = head\n \n while curr and curr.next:\n next = curr.next\n curr.next = next.next\n next.next = curr\n \n if prev:\n prev.next = next\n \n prev = curr\n curr = curr.next\n \n return new_head\n```\n---\n# JavaScript\n```\nvar swapPairs = function(head) {\n if (!head || !head.next) {\n return head;\n }\n \n var newHead = head.next;\n var prev = null;\n var curr = head;\n \n while (curr && curr.next) {\n var next = curr.next;\n curr.next = next.next;\n next.next = curr;\n \n if (prev) {\n prev.next = next;\n }\n \n prev = curr;\n curr = curr.next;\n }\n \n return newHead;\n};\n\n```
2,380
Swap Nodes in Pairs
swap-nodes-in-pairs
Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)
Linked List,Recursion
Medium
null
508
7
\n# Approach\n<!-- Describe your approach to solving the problem. -->\nHere we are using a very simple and easy ***recursive*** approach to solve this\n\n\n**Steps:**\n\n1. At first we will check, if head value is null we will return null.\n\n `if(head==null) return null;`\n2. Then we check, if next head value is null we will return current head.\n\n `if (head.next == null) return head;`\n3. Later we will swap the 2 value of by creating a temp variable & recursively swapping the values.\n \n - Storing the next head to a temp ListNode that we will return at last. `ListNode temp = head.next;`\n - Then we get the call the function recursively for next head. \n `head.next = swapPairs(temp.next);`\n - Then we swap value next temp with the head.\n `temp.next = head;`\n4. At last we will return the temp ListNode we created .\n \n `return temp;`\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\n\n```\nclass Solution {\n public ListNode swapPairs(ListNode head) {\n \n if(head==null) return null;\n if (head.next == null) return head;\n\n ListNode temp = head.next;\n head.next = swapPairs(temp.next);\n temp.next = head;\n\n return temp;\n }\n}\n```\n\n<!-- ---\n**Iterative** \n```\npublic ListNode swapPairs1(ListNode head) {\n if (head == null || head.next == null) {\n return head;\n }\n ListNode pre = new ListNode(0), p = head, ret = head.next;\n while (p != null && p.next != null) {\n ListNode nxt = p.next;\n p.next = nxt.next;\n nxt.next = p;\n pre.next = nxt;\n pre = p;\n p = p.next;\n }\n return ret;\n}\n``` -->\n\n![please-upvote-and.jpg]()\n\n\n\n\n
2,384
Swap Nodes in Pairs
swap-nodes-in-pairs
Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)
Linked List,Recursion
Medium
null
1,555
23
```swift\nclass Solution {\n func swapPairs(_ head: ListNode?) -> ListNode? {\n var head = head, node = head, pre: ListNode?\n \n while node != nil, let next = node!.next {\n let cur = next, tmp = cur.next\n pre == nil ? (head = cur) : (pre!.next = cur)\n cur.next = node\n node!.next = tmp\n pre = node\n node = tmp\n }\n return head\n }\n}\n```\n\n---\n\n<p><details>\n<summary>\n<img src="" height="24">\n<b>TEST CASES</b>\n</summary>\n\n<p><pre>\n<b>Result:</b> Executed 3 tests, with 0 failures (0 unexpected) in 0.012 (0.014) seconds\n</pre></p>\n\n```swift\nimport XCTest\n\nclass Tests: XCTestCase {\n \n private let solution = Solution()\n \n func test0() {\n let value = solution.swapPairs(ListNode([1,2,3,4]))\n XCTAssertEqual(value?.val, ListNode([2,1,4,3])?.val)\n }\n \n func test1() {\n let value = solution.swapPairs(ListNode([]))\n XCTAssertEqual(value?.val, ListNode([])?.val)\n }\n \n func test2() {\n let value = solution.swapPairs(ListNode([1]))\n XCTAssertEqual(value?.val, ListNode([1])?.val)\n }\n}\n\nTests.defaultTestSuite.run()\n```\n\n</details></p>\n\n<p><details>\n<summary>\n<b>ListNode</b>\n</summary>\n\n```swift\npublic class ListNode {\n public var val: Int\n public var next: ListNode?\n public init() { self.val = 0; self.next = nil; }\n public init(_ val: Int) { self.val = val; self.next = nil; }\n public init(_ val: Int, _ next: ListNode?) { self.val = val; self.next = next; }\n\n\tpublic init?(_ array: [Int]) {\n guard !array.isEmpty else { return nil }\n self.val = array[0]\n var prev: ListNode = self\n for i in 1..<array.count {\n let new = ListNode(array[i])\n prev.next = new\n prev = new\n }\n }\n}\n```\n\n</details></p>
2,391
Swap Nodes in Pairs
swap-nodes-in-pairs
Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)
Linked List,Recursion
Medium
null
732
6
# Intuition\nA pretty simple approach using recursion\n\n# Approach\n1. We have to keep in mind that while swapping, we are only working with two nodes at a time.\n2. I have written the swapping steps under the comment in the code. Take a piece of paper and try to dry run it on two nodes, You will get it.\n3. Now we know how I am swapping them, One case is solved, rest will be done by recursion.\n4. After swapping the first two nodes, we will attach the result of swapping after the recursion has done it\'s work.\n5. we will have to return the temp as it will be pointing to the first node of the swapping result.\n6. and we\'re DONE !!\n\nMy solution is not the best, but is easy to understand for the beginners. \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 */\nclass Solution {\npublic:\n ListNode* swapPairs(ListNode* head) {\n if(head == NULL)\n return NULL;\n\n if(head->next == NULL)\n return head;\n\n ListNode* tempHead = head;\n\n //swapping\n ListNode* temp = tempHead->next;\n tempHead->next = tempHead->next->next;\n temp->next = tempHead;\n //tempHead = tempHead->next;\n\n tempHead->next = swapPairs(tempHead->next);\n\n return temp;\n }\n};\n```
2,394
Reverse Nodes in k-Group
reverse-nodes-in-k-group
Given the head of a linked list, reverse the nodes of the list k at a time, and return the modified list. k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is. You may not alter the values in the list's nodes, only nodes themselves may be changed.
Linked List,Recursion
Hard
null
688
10
Hi, guys!\nDespite the fact that the approach is recursive, the code is less than 35 lines. :)\n```python []\nclass Solution(object):\n def reverseKGroup(self, head, k):\n if not head or k == 1:\n return head\n\n # Check if there are at least k nodes remaining in the list\n count = 0\n current = head\n while current and count < k:\n current = current.next\n count += 1\n\n if count < k:\n return head # Not enough nodes to reverse\n\n # Reverse the first k nodes in the current group\n prev = None\n next_node = None\n current = head\n for i in range(k):\n next_node = current.next\n current.next = prev\n prev = current\n current = next_node\n\n # Recursively reverse the remaining part of the list\n head.next = self.reverseKGroup(current, k)\n\n return prev # \'prev\' is now the new head of this group\n```\n```java []\npublic class Solution {\n public ListNode reverseKGroup(ListNode head, int k) {\n if (head == null || k == 1) {\n return head;\n }\n\n // Check if there are at least k nodes remaining in the list\n int count = 0;\n ListNode current = head;\n while (current != null && count < k) {\n current = current.next;\n count++;\n }\n\n if (count < k) {\n return head; // Not enough nodes to reverse\n }\n\n // Reverse the first k nodes in the current group\n ListNode prev = null;\n ListNode next = null;\n current = head;\n for (int i = 0; i < k; i++) {\n next = current.next;\n current.next = prev;\n prev = current;\n current = next;\n }\n\n // Recursively reverse the remaining part of the list\n head.next = reverseKGroup(current, k);\n\n return prev; // \'prev\' is now the new head of this group\n }\n}\n```\n```cpp []\nclass Solution {\npublic:\n ListNode* reverseKGroup(ListNode* head, int k) {\n if (!head || k == 1) {\n return head;\n }\n\n int count = 0;\n ListNode* current = head;\n while (current && count < k) {\n current = current->next;\n count++;\n }\n\n if (count < k) {\n return head;\n }\n\n ListNode* prev = nullptr;\n ListNode* next = nullptr;\n current = head;\n for (int i = 0; i < k; i++) {\n next = current->next;\n current->next = prev;\n prev = current;\n current = next;\n }\n\n head->next = reverseKGroup(current, k);\n\n return prev;\n }\n};\n```\n``` c []\nstruct ListNode* reverseKGroup(struct ListNode* head, int k) {\n if (!head || k == 1) {\n return head;\n }\n\n // Check if there are at least k nodes remaining in the list\n int count = 0;\n struct ListNode* current = head;\n while (current && count < k) {\n current = current->next;\n count++;\n }\n\n if (count < k) {\n return head; // Not enough nodes to reverse\n }\n\n // Reverse the first k nodes in the current group\n struct ListNode* prev = NULL;\n struct ListNode* next = NULL;\n current = head;\n for (int i = 0; i < k; i++) {\n next = current->next;\n current->next = prev;\n prev = current;\n current = next;\n }\n\n // Recursively reverse the remaining part of the list\n head->next = reverseKGroup(current, k);\n\n return prev; // \'prev\' is now the new head of this group\n}\n```\n```csharp []\npublic class Solution {\n public ListNode ReverseKGroup(ListNode head, int k) {\n if (head == null || k == 1) {\n return head;\n }\n \n // Check if there are at least k nodes remaining in the list\n int count = 0;\n ListNode current = head;\n while (current != null && count < k) {\n current = current.next;\n count++;\n }\n\n if (count < k) {\n return head; // Not enough nodes to reverse\n }\n\n // Reverse the first k nodes in the current group\n ListNode prev = null;\n ListNode next = null;\n current = head;\n for (int i = 0; i < k; i++) {\n next = current.next;\n current.next = prev;\n prev = current;\n current = next;\n }\n\n // Recursively reverse the remaining part of the list\n head.next = ReverseKGroup(current, k);\n\n return prev; // \'prev\' is now the new head of this group\n }\n}\n```\n```javascript []\nvar reverseKGroup = function(head, k) {\n if (!head || k === 1) {\n return head;\n }\n\n let count = 0;\n let current = head;\n while (current && count < k) {\n current = current.next;\n count++;\n }\n\n if (count < k) {\n return head;\n }\n\n let prev = null;\n let next = null;\n current = head;\n for (let i = 0; i < k; i++) {\n next = current.next;\n current.next = prev;\n prev = current;\n current = next;\n }\n\n head.next = reverseKGroup(current, k);\n\n return prev;\n};\n```\n``` typescript []\nfunction reverseKGroup(head: ListNode | null, k: number): ListNode | null {\n if (!head || k === 1) {\n return head;\n }\n\n let count = 0;\n let current: ListNode | null = head;\n while (current && count < k) {\n current = current.next;\n count++;\n }\n\n if (count < k) {\n return head;\n }\n\n let prev: ListNode | null = null;\n let next: ListNode | null = null;\n current = head;\n for (let i = 0; i < k; i++) {\n next = current?.next;\n current.next = prev;\n prev = current;\n current = next;\n }\n\n if (head) {\n head.next = reverseKGroup(current, k);\n }\n\n return prev;\n};\n```\n```ruby []\ndef reverse_k_group(head, k)\n return head if !head || k == 1\n\n count = 0\n current = head\n while current && count < k\n current = current.next\n count += 1\n end\n\n return head if count < k\n\n prev = nil\n next_node = nil\n current = head\n k.times do\n next_node = current.next\n current.next = prev\n prev = current\n current = next_node\n end\n\n head.next = reverse_k_group(current, k)\n\n prev\nend\n```\n```kotlin []\nclass Solution {\n fun reverseKGroup(head: ListNode?, k: Int): ListNode? {\n if (head == null || k == 1) {\n return head\n }\n\n var count = 0\n var current = head\n while (current != null && count < k) {\n current = current.next\n count++\n }\n\n if (count < k) {\n return head\n }\n\n var prev: ListNode? = null\n var next: ListNode?\n current = head\n repeat(k) {\n next = current?.next\n current?.next = prev\n prev = current\n current = next\n }\n\n head?.next = reverseKGroup(current, k)\n\n return prev\n }\n}\n```\nHope it helps!\n\n![please upvote.png]()\n
2,402
Reverse Nodes in k-Group
reverse-nodes-in-k-group
Given the head of a linked list, reverse the nodes of the list k at a time, and return the modified list. k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is. You may not alter the values in the list's nodes, only nodes themselves may be changed.
Linked List,Recursion
Hard
null
124,739
640
Hi, guys!\nDespite the fact that the approach is recursive, the code is less than 20 lines. :)\n\n public ListNode reverseKGroup(ListNode head, int k) {\n ListNode curr = head;\n int count = 0;\n while (curr != null && count != k) { // find the k+1 node\n curr = curr.next;\n count++;\n }\n if (count == k) { // if k+1 node is found\n curr = reverseKGroup(curr, k); // reverse list with k+1 node as head\n // head - head-pointer to direct part, \n // curr - head-pointer to reversed part;\n while (count-- > 0) { // reverse current k-group: \n ListNode tmp = head.next; // tmp - next head in direct part\n head.next = curr; // preappending "direct" head to the reversed list \n curr = head; // move head of reversed part to a new node\n head = tmp; // move "direct" head to the next node in direct part\n }\n head = curr;\n }\n return head;\n }\n\nHope it helps!
2,405
Reverse Nodes in k-Group
reverse-nodes-in-k-group
Given the head of a linked list, reverse the nodes of the list k at a time, and return the modified list. k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is. You may not alter the values in the list's nodes, only nodes themselves may be changed.
Linked List,Recursion
Hard
null
23,487
250
# Recursive solution\n\nRecursive solution has `O(n)` space complexity because of call stacks.\n\n```c++\n\tListNode* reverseKGroup(ListNode* head, int k) {\n ListNode* cursor = head;\n for(int i = 0; i < k; i++){\n if(cursor == nullptr) return head;\n cursor = cursor->next;\n }\n ListNode* curr = head;\n ListNode* prev = nullptr;\n ListNode* nxt = nullptr;\n for(int i = 0; i < k; i++){\n nxt = curr->next;\n curr->next = prev;\n prev = curr;\n curr = nxt;\n }\n head->next = reverseKGroup(curr, k);\n return prev;\n }\n```\n\n\n******************************************************************************************\n\n\n# Iterative solution\n\nIterative solution has `O(1)` space complexity.\n\n```c++\n\tListNode* reverseKGroup(ListNode* head, int k) {\n ListNode* dummy = new ListNode(0);\n dummy->next = head;\n ListNode* before = dummy;\n ListNode* after = head;\n ListNode* curr = nullptr;\n ListNode* prev = nullptr;\n ListNode* nxt = nullptr;\n while(true){\n ListNode* cursor = after;\n for(int i = 0; i < k; i++){\n if(cursor == nullptr) return dummy->next;\n cursor = cursor->next;\n }\n curr = after;\n prev = before;\n for(int i = 0; i < k; i++){\n nxt = curr->next;\n curr->next = prev;\n prev = curr;\n curr = nxt;\n }\n after->next = curr;\n before->next = prev;\n before = after;\n after = curr;\n }\n }\n```
2,408
Reverse Nodes in k-Group
reverse-nodes-in-k-group
Given the head of a linked list, reverse the nodes of the list k at a time, and return the modified list. k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is. You may not alter the values in the list's nodes, only nodes themselves may be changed.
Linked List,Recursion
Hard
null
7,084
21
\n# Code\n```\nclass Solution {\npublic:\n ListNode* reverseKGroup(ListNode* head, int k) {\n if(head==NULL || head->next==NULL){\n return head;\n }\n int cnt = 0;\n ListNode* counter = head;\n ListNode* temp = head;\n ListNode* ans = head;\n while(counter!=NULL){\n cnt++;\n counter = counter->next;\n }\n cnt /= k;\n stack<int> st;\n int k1 = k;\n\n while(temp!=NULL){\n st.push(temp->val);\n k1--;\n temp = temp->next;\n if(k1==0){\n while(!st.empty()){\n ans->val = st.top();\n st.pop();\n ans = ans->next;\n }\n cnt--;\n k1 = k;\n }\n if(cnt==0){\n break;\n }\n }\n return head;\n }\n};\n```
2,409
Reverse Nodes in k-Group
reverse-nodes-in-k-group
Given the head of a linked list, reverse the nodes of the list k at a time, and return the modified list. k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is. You may not alter the values in the list's nodes, only nodes themselves may be changed.
Linked List,Recursion
Hard
null
56,803
449
Reference: \n\n\nFirst, build a function reverse() to reverse the ListNode between begin and end. See the explanation below:\n\n /**\n * Reverse a link list between begin and end exclusively\n * an example:\n * a linked list:\n * 0->1->2->3->4->5->6\n * | | \n * begin end\n * after call begin = reverse(begin, end)\n * \n * 0->3->2->1->4->5->6\n * | |\n * begin end\n * @return the reversed list's 'begin' node, which is the precedence of node end\n */\n\nThen walk thru the linked list and apply reverse() iteratively. See the code below.\n\n public ListNode reverseKGroup(ListNode head, int k) {\n ListNode begin;\n if (head==null || head.next ==null || k==1)\n \treturn head;\n ListNode dummyhead = new ListNode(-1);\n dummyhead.next = head;\n begin = dummyhead;\n int i=0;\n while (head != null){\n \ti++;\n \tif (i%k == 0){\n \t\tbegin = reverse(begin, head.next);\n \t\thead = begin.next;\n \t} else {\n \t\thead = head.next;\n \t}\n }\n return dummyhead.next;\n \n }\n \n public ListNode reverse(ListNode begin, ListNode end){\n \tListNode curr = begin.next;\n \tListNode next, first;\n \tListNode prev = begin;\n \tfirst = curr;\n \twhile (curr!=end){\n \t\tnext = curr.next;\n \t\tcurr.next = prev;\n \t\tprev = curr;\n \t\tcurr = next;\n \t}\n \tbegin.next = prev;\n \tfirst.next = curr;\n \treturn first;\n }
2,419
Reverse Nodes in k-Group
reverse-nodes-in-k-group
Given the head of a linked list, reverse the nodes of the list k at a time, and return the modified list. k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is. You may not alter the values in the list's nodes, only nodes themselves may be changed.
Linked List,Recursion
Hard
null
2,826
9
# Intuition\n**Simple** and **easy Brute force** intuition(read Approach you will get to know why it is **EASY** and **SIMPLE**).\n\n# Approach\n- Take a var and count if there are k nodes left in list to be reversed.\n- If there were no k nodes left So we will return the normal list without reversing according to the question.\n- If at least K nodes Left it means k nodes should be reversed So the normal Recursive reversing process(rest of the code) will be executed.\n- We will reverse the list till next k nodes.\n- We will have to attach next upcoming list to our current reversed list so we will get to the tail of current reversed list and attach it to the recursively reversed rest of the list(you will unterstand it properly when u see the code).\n- \n\n\n# Complexity\n- Time complexity: **O(N)**\n - Traversing to N nodes that\'s why N Time Complexity.\n\n- Space complexity: **Recursion Stack**\n\n\n# Code\n### swipe up a bit for clean code without comments\n```\nclass Solution {\npublic:\n ListNode* reverseKGroup(ListNode* curr, int k) {\n int t=0;\n ListNode* prev=nullptr, *check=curr;\n while(t<k && check!=nullptr) check=check->next,t++; //checking if there are k nodes left to be reversed (using loop)\n if(t<k) return curr; // if there are less than k nodes we need not reverse so return the normal List\n while(t-- && curr!=nullptr){ // reversing loop\n ListNode* next= curr->next;\n curr->next=prev;\n prev=curr;\n curr=next;\n }\n ListNode* tail=prev; //iterating till tail of the current reversed List\n while( tail!=nullptr && tail->next!=nullptr) tail=tail->next; // so that we can attach it to recursively reversed upcomming List\n tail->next = curr ? reverseKGroup(curr,k) : nullptr; //attacing the next upcomming reverse list the current reversed List\n return prev;\n }\n};\n```\n# C++ Solution\n```\nclass Solution {\npublic:\n ListNode* reverseKGroup(ListNode* curr, int k) {\n int t=0;\n ListNode* prev=nullptr, *check=curr;\n while(t<k && check!=nullptr) check=check->next,t++;\n if(t<k) return curr;\n while(t-- && curr!=nullptr){\n ListNode* next= curr->next;\n curr->next=prev;\n prev=curr;\n curr=next;\n }\n ListNode* tail=prev;\n while( tail!=nullptr && tail->next!=nullptr) tail=tail->next;\n tail->next = curr ? reverseKGroup(curr,k) : nullptr;\n return prev;\n }\n};\n```\n## Thanks for the Upvote \uD83D\uDE07
2,422
Reverse Nodes in k-Group
reverse-nodes-in-k-group
Given the head of a linked list, reverse the nodes of the list k at a time, and return the modified list. k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is. You may not alter the values in the list's nodes, only nodes themselves may be changed.
Linked List,Recursion
Hard
null
1,509
6
# Approach\nOptimal Approach\n\n# Complexity\n- Time complexity:\n$$O(n)$$\n\n- Space complexity:\n$$O(1)$$\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 */\nclass Solution {\nprivate:\n ListNode* reverse(ListNode* head, int k) {\n ListNode* prev = NULL;\n ListNode* cur = head;\n ListNode* nxt;\n while (k--) {\n nxt = cur->next;\n cur->next = prev;\n prev = cur;\n cur = nxt;\n }\n head->next = cur;\n return prev;\n } \n int length(ListNode* head) {\n int len = 0;\n while(head != NULL) {\n len++;\n head = head->next;\n }\n return len;\n }\npublic:\n ListNode* reverseKGroup(ListNode* head, int k) {\n int len = length(head);\n ListNode* dummy = new ListNode();\n ListNode* temp = dummy;\n ListNode* cur = head;\n while (cur != NULL) {\n if (len >= k) {\n temp->next = reverse(cur, k);\n len -= k;\n temp = cur;\n cur = cur->next;\n } else {\n break;\n }\n }\n return dummy->next;\n }\n};\n```
2,423
Reverse Nodes in k-Group
reverse-nodes-in-k-group
Given the head of a linked list, reverse the nodes of the list k at a time, and return the modified list. k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is. You may not alter the values in the list's nodes, only nodes themselves may be changed.
Linked List,Recursion
Hard
null
11,226
244
This problem can be split into several steps:\n1. Since we need to reverse the linked-list every k nodes, we need to check whether the number of list nodes are enough to reverse. Otherwise, there is no need to reverse.\n\n2. If we need to reverse the k nodes, how to do that? Following is my idea:\n\n\t If the structure of the linkedlist is like this: \n\t\t\n\t\t1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7\n\t\t\nThen there will always be a pointer, which points to the node **AHEAD** of the first node to reverse. The pointer will help to link the linkedlist after.\n\nAt first, we will add a dummy node in front of the linked list to act as the first pointer. After we add the pointer, the linked list will look like this:\n```\n 0 (pointer) -> 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7\n```\n\t\nSuppose that there are enough nodes to be reversed, we just use the "reverse linked list" trick to reverse the k nodes. Please refer to "" if you don\'t know how to reverse a linked list.\n\nif k = 3, we can reverse 1 to 3 first using the following code:\n```\n ListNode prev = null, curr = pointer.next, next = null;\n for (int i = 0; i < k; i++) {\n\t\tnext = curr.next;\n\t\tcurr.next = prev;\n\t\tprev = curr;\n\t\tcurr = next;\n }\n```\nThis is the illustartion of the first 3 steps:\n```\n step1: 0 (pointer) -> 1 2 -> 3 -> 4 -> 5 -> 6 -> 7\n\tstep2: 0 (pointer) -> 1 <- 2 3 -> 4 -> 5 -> 6 -> 7\n\tstep3: 0 (pointer) -> 1 <- 2 <- 3 4 -> 5 -> 6 -> 7\n```\n\nThis is an easy and general algorithm to reverse a linked list. However, if you are careful enough, you will find that after the for-loop, the link from 3 to 4 will be cut (as shown in step3).\n\t\nNow we need to reconstruct the linked list and fix the issue. You will figure out that at step3, the 3 is the **prev** node, 4 is the **curr** node. \n```\n\tstep3: 0 (pointer) -> 1 <- 2 <- 3 (prev) 4 (curr) -> 5 -> 6 -> 7\n```\nWe can fix the sequence based on the following codes. The basic idea is to link the pointer to 3 and link 1 to 4:\n```\n\tListNode tail = pointer.next;\n\ttail.next = curr; \n\tpointer.next = prev;\n\tpointer = tail;\n```\n\nThen the result is:\n```\n\tafter first line: 0 (pointer) -> 1 (tail) <- 2 <- 3 (prev) 4 (curr) -> 5 -> 6 -> 7\n\tafter second line: 0 (pointer) -> 1 (tail) <- 2 <- 3 (prev) 4 (curr) -> 5 -> 6 -> 7\n\t\t\t\t\t\t\t\t |____________________________\u2191\n\tafter third line: \n\t\t\t\t\t\t\t\t|-----------------------\u2193\n\t\t\t\t\t\t0 (pointer) 1 (tail) <- 2 <- 3 (prev) 4 (curr) -> 5 -> 6 -> 7\n\t\t\t\t\t\t\t\t\t |____________________________\u2191\n\t\t\t\t\t\t\t\t\t \n\tafter forth line:\t0 -> 3 -> 2 -> 1 (pointer) -> 4 -> 5 -> 6 -> 7\n```\n\t\t\t\nNow we get the new pointer, and we can repeat the process. Note that to retrieve the head, we need to record the first dummy node (0).\n\nHere is the code:\n```\npublic ListNode reverseKGroup(ListNode head, int k) {\n ListNode dummy = new ListNode(0);\n dummy.next = head;\n ListNode pointer = dummy;\n while (pointer != null) {\n ListNode node = pointer;\n // first check whether there are k nodes to reverse\n for (int i = 0; i < k && node != null; i++) {\n node = node.next;\n }\n if (node == null) break;\n \n // now we know that we have k nodes, we will start from the first node\n ListNode prev = null, curr = pointer.next, next = null;\n for (int i = 0; i < k; i++) {\n next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n ListNode tail = pointer.next;\n tail.next = curr;\n pointer.next = prev;\n pointer = tail;\n }\n return dummy.next;\n }\n```\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t\t\n\n\t\t
2,425
Reverse Nodes in k-Group
reverse-nodes-in-k-group
Given the head of a linked list, reverse the nodes of the list k at a time, and return the modified list. k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is. You may not alter the values in the list's nodes, only nodes themselves may be changed.
Linked List,Recursion
Hard
null
837
11
```\nclass Solution:\n def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:\n count=0\n temp=head\n while temp:\n temp=temp.next\n count+=1\n n=count//k #No. of groups to be reversed\n prev=dummy=ListNode()\n dummy.next=head\n while n:\n curr=prev.next\n nex=curr.next\n for i in range(1,k): #If we have to reverse k nodes then k-1 links will be reversed\n curr.next=nex.next\n nex.next=prev.next\n prev.next=nex\n nex=curr.next\n prev=curr\n n-=1\n return dummy.next\n```\n**An upvote will be encouraging**
2,428
Reverse Nodes in k-Group
reverse-nodes-in-k-group
Given the head of a linked list, reverse the nodes of the list k at a time, and return the modified list. k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is. You may not alter the values in the list's nodes, only nodes themselves may be changed.
Linked List,Recursion
Hard
null
498
5
\n# Approach\nReverse k node at a time. \nThen reduce Linked List size as size-k.\nMake a recursive call for further nodes.\n\n# Complexity\n- Time complexity: O(n)\n\n\n- Space complexity: O(1)\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 */\nclass Solution {\n// Reverse the node.\n ListNode * reverse(ListNode * ptr, int &k, int size)\n {\n if(size < k) return ptr;\n if(ptr == NULL) return ptr;\n\n ListNode * cur = ptr, *temp = NULL, *pre = NULL;\n int cnt = 0;\n while(cur!=NULL && cnt < k)\n {\n temp = cur->next;\n cur->next = pre;\n pre = cur;\n cur = temp;\n cnt++;\n }\n\n ptr->next = reverse(temp,k,size-k);\n return pre;\n }\n\n// Find the length of the Linked List.\n int func(ListNode * ptr)\n {\n int len = 0;\n while(ptr)\n {\n len++;\n ptr = ptr->next;\n }\n return len;\n }\npublic:\n ListNode* reverseKGroup(ListNode* head, int k) {\n int n = func(head);\n return reverse(head,k,n);\n }\n};\n```
2,435
Reverse Nodes in k-Group
reverse-nodes-in-k-group
Given the head of a linked list, reverse the nodes of the list k at a time, and return the modified list. k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is. You may not alter the values in the list's nodes, only nodes themselves may be changed.
Linked List,Recursion
Hard
null
535
5
# 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 {\n ListNode * reverse(ListNode * ptr, int &k, int size)\n {\n if(size < k) {\n return ptr;\n }\n if(ptr == NULL){\n return ptr;\n }\n\n ListNode * cur = ptr;\n ListNode * temp = NULL;\n ListNode * pre = NULL;\n int cnt = 0;\n while(cur!=NULL && cnt < k)\n {\n temp = cur->next;\n cur->next = pre;\n pre = cur;\n cur = temp;\n cnt++;\n }\n\n ptr->next = reverse(temp,k,size-k);\n return pre;\n }\n\n int func(ListNode * ptr)\n {\n int len = 0;\n while(ptr)\n {\n len++;\n ptr = ptr->next;\n }\n return len;\n }\npublic:\n ListNode* reverseKGroup(ListNode* head, int k) {\n int n = func(head);\n return reverse(head,k,n);\n }\n};\n```
2,436
Reverse Nodes in k-Group
reverse-nodes-in-k-group
Given the head of a linked list, reverse the nodes of the list k at a time, and return the modified list. k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is. You may not alter the values in the list's nodes, only nodes themselves may be changed.
Linked List,Recursion
Hard
null
44,334
334
Use a dummy head, and\n\nl, r : define reversing range\n\npre, cur : used in reversing, standard reverse linked linked list method\n\njump : used to connect last node in previous k-group to first node in following k-group\n\n def reverseKGroup(self, head, k):\n dummy = jump = ListNode(0)\n dummy.next = l = r = head\n \n while True:\n count = 0\n while r and count < k: # use r to locate the range\n r = r.next\n count += 1\n if count == k: # if size k satisfied, reverse the inner linked list\n pre, cur = r, l\n for _ in range(k):\n cur.next, cur, pre = pre, cur.next, cur # standard reversing\n jump.next, jump, l = pre, l, r # connect two k-groups\n else:\n return dummy.next
2,437
Reverse Nodes in k-Group
reverse-nodes-in-k-group
Given the head of a linked list, reverse the nodes of the list k at a time, and return the modified list. k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is. You may not alter the values in the list's nodes, only nodes themselves may be changed.
Linked List,Recursion
Hard
null
2,448
5
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nReverse k nodes and then do recursion.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n**IMPORTANT: Read the comments in the code, they are self-explanatory.**\n1. Reverse k nodes initially.\n2. Call for the remaining \'len - k\' nodes, where len = length of the Linked List.\n3. Connect the kth node of the k nodes reversed linked list to the head of the remaining linked list.\n\n# Complexity\n- Time complexity: **O(len)**\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(len) for the length function\nO(len/k) for the loop inside reverseKGroup\nO(len) for the recursive calls inside reverseKGroup\n\nOverall ~ O(len)\n\n- Space complexity:**O(len)**\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nlen = length of the linked list, this is due to recursive call stack.\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 */\nclass Solution {\npublic:\n int length (ListNode* head)\n {\n int len = 0;\n while(head != NULL)\n {\n len++;\n head = head -> next;\n }\n return len;\n }\n\n ListNode* reverseKGroup(ListNode* head, int k) {\n \n //head = 1\n\n int len = length(head); //Calculate length of LL\n if(len < k) //As mentioned in aue, if len < k don\'t reverse\n {\n return head;\n }\n int cnt = 0;\n ListNode* curr = head; //1 --- After 1st step, curr = 2\n ListNode* prev = NULL; //NULL\n ListNode* forward = NULL;\n\n while(curr != NULL && cnt < k) //Reverseing \'k\' nodes initially\n {\n forward = curr -> next; //2 --- 3\n curr -> next = prev; //1 -> 2 is broken and NULL <- 1 --- 2 -> 1\n prev = curr; //prev = 1 --- prev = 2\n curr = forward; // curr = 2 --- curr = 3\n cnt++;\n }\n if(forward != NULL)\n {\n head -> next = reverseKGroup(forward, k); //Recursively calling for remaining nodes\n }\n //I\'ve stored it in head -> next bcz, head = 1 and I\'ve coneected it with 4, head of the new LL\n\n return prev; // return prev bcz, 2 is the head of our final LL and it is stored in prev\n }\n};\n```
2,438
Reverse Nodes in k-Group
reverse-nodes-in-k-group
Given the head of a linked list, reverse the nodes of the list k at a time, and return the modified list. k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is. You may not alter the values in the list's nodes, only nodes themselves may be changed.
Linked List,Recursion
Hard
null
1,336
9
\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 */\nclass Solution {\npublic:\n ListNode* reverseKGroup(ListNode* head, int k) {\n ListNode* curr = head;\n ListNode* nodenext=NULL;\n ListNode* prevnode = NULL;\n int count=0;\n while(curr!=NULL && count<k){\n nodenext = curr->next;\n curr->next = prevnode;\n prevnode = curr;\n curr = nodenext;\n count++;\n }\n if(count!=k){\n ListNode* t = prevnode;\n prevnode = NULL;\n while(t!=NULL){\n nodenext = t->next;\n t->next = prevnode;\n prevnode = t;\n t = nodenext;\n }\n return prevnode;\n }\n if(nodenext!=NULL){\n ListNode* rest_head = reverseKGroup(nodenext , k);\n head->next = rest_head;\n }\n return prevnode;\n }\n};\n```
2,443
Reverse Nodes in k-Group
reverse-nodes-in-k-group
Given the head of a linked list, reverse the nodes of the list k at a time, and return the modified list. k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is. You may not alter the values in the list's nodes, only nodes themselves may be changed.
Linked List,Recursion
Hard
null
6,868
21
# Intuition:\nWe can use a two-pointer approach to reverse the linked list in groups of k nodes. We will maintain a `prevGroupTail` pointer that will point to the tail of the previous reversed group, and we will connect it to the head of the current group after reversing it. We will also use a `dummy` node as the head of the resulting list to avoid edge cases.\n\n# Approach:\n1. Create a dummy node and set its next to the head of the input list.\n2. Initialize a `prevGroupTail` pointer to the dummy node.\n3. Loop through the list until we reach the end.\n4. In each iteration, set `groupStart` to the current `head`, and find `groupEnd` using the `getGroupEnd` function, which returns the end node of the current group (which is `k` nodes away from the `groupStart`). If `groupEnd` is null, then we don\'t need to reverse the remaining nodes because there are less than `k` nodes left in the list.\n5. Set `nextGroupStart` to `groupEnd->next`, and then set `groupEnd->next` to null to separate the group to be reversed from the rest of the list.\n6. Reverse the current group using the `reverseList` function and set `prevGroupTail->next` to the new head of the reversed group. Then set `groupStart->next` to `nextGroupStart`.\n7. Update `prevGroupTail` to the `groupStart`.\n8. Set `head` to `nextGroupStart`.\n9. Return the head of the resulting list (which is the `dummy->next` node).\n\n# Complexity\n- Time Complexity:\nThe time complexity of the algorithm is O(n), where n is the number of nodes in the list, since we visit each node once.\n\n- Space Complexity:\nThe space complexity of the algorithm is O(1), since we only use a constant amount of extra space for the `dummy` and `prevGroupTail` nodes, and we reverse the list in-place without using any additional data structures.\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 */\nclass Solution {\npublic:\n ListNode* reverseKGroup(ListNode* head, int k) {\n ListNode* dummy = new ListNode(0);\n dummy->next = head;\n ListNode* prevGroupTail = dummy;\n \n while (head) {\n ListNode* groupStart = head;\n ListNode* groupEnd = getGroupEnd(head, k);\n \n if (!groupEnd) {\n break; // Remaining nodes are less than k, so no need to reverse\n }\n \n ListNode* nextGroupStart = groupEnd->next;\n groupEnd->next = nullptr; // Separate the group to be reversed\n \n // Reverse the group\n prevGroupTail->next = reverseList(groupStart);\n groupStart->next = nextGroupStart;\n \n prevGroupTail = groupStart;\n head = nextGroupStart;\n }\n \n ListNode* newHead = dummy->next;\n delete dummy;\n return newHead;\n }\n \nprivate:\n ListNode* getGroupEnd(ListNode* head, int k) {\n while (head && k > 1) {\n head = head->next;\n k--;\n }\n return head;\n }\n \n ListNode* reverseList(ListNode* head) {\n ListNode* prev = nullptr;\n ListNode* curr = head;\n \n while (curr) {\n ListNode* next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n }\n \n return prev;\n }\n};\n\n```\n\n---\n# Java\n```\nclass Solution {\n public ListNode reverseKGroup(ListNode head, int k) {\n ListNode dummy = new ListNode(0);\n dummy.next = head;\n ListNode prevGroupTail = dummy;\n\n while (head != null) {\n ListNode groupStart = head;\n ListNode groupEnd = getGroupEnd(head, k);\n\n if (groupEnd == null)\n break;\n\n prevGroupTail.next = reverseList(groupStart, groupEnd.next);\n prevGroupTail = groupStart;\n head = prevGroupTail.next;\n }\n\n ListNode newHead = dummy.next;\n return newHead;\n }\n\n private ListNode getGroupEnd(ListNode head, int k) {\n while (head != null && --k > 0)\n head = head.next;\n return head;\n }\n\n private ListNode reverseList(ListNode head, ListNode stop) {\n ListNode prev = stop;\n while (head != stop) {\n ListNode next = head.next;\n head.next = prev;\n prev = head;\n head = next;\n }\n return prev;\n }\n}\n\n```\n\n---\n\n# Python\n```\nclass Solution(object):\n def reverseKGroup(self, head, k):\n dummy = ListNode(0)\n dummy.next = head\n prevGroupTail = dummy\n\n while head:\n groupStart = head\n groupEnd = self.getGroupEnd(head, k)\n\n if not groupEnd:\n break\n\n prevGroupTail.next = self.reverseList(groupStart, groupEnd.next)\n prevGroupTail = groupStart\n head = prevGroupTail.next\n\n newHead = dummy.next\n return newHead\n\n def getGroupEnd(self, head, k):\n while head and k > 1:\n head = head.next\n k -= 1\n return head\n\n def reverseList(self, head, stop):\n prev = stop\n while head != stop:\n next = head.next\n head.next = prev\n prev = head\n head = next\n return prev\n```\n---\n# JavaScript\n```\nvar reverseKGroup = function(head, k) {\n var dummy = new ListNode(0);\n dummy.next = head;\n var prevGroupTail = dummy;\n\n while (head) {\n var groupStart = head;\n var groupEnd = getGroupEnd(head, k);\n\n if (!groupEnd)\n break;\n\n prevGroupTail.next = reverseList(groupStart, groupEnd.next);\n prevGroupTail = groupStart;\n head = prevGroupTail.next;\n }\n var newHead = dummy.next;\n return newHead;\n}\n\nvar getGroupEnd = function(head, k) {\n while (head && k > 1) {\n head = head.next;\n k--;\n }\n return head;\n}\n\nvar reverseList = function(head, stop) {\n var prev = stop;\n while (head !== stop) {\n var next = head.next;\n head.next = prev;\n prev = head;\n head = next;\n }\n return prev;\n}\n```
2,451
Reverse Nodes in k-Group
reverse-nodes-in-k-group
Given the head of a linked list, reverse the nodes of the list k at a time, and return the modified list. k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is. You may not alter the values in the list's nodes, only nodes themselves may be changed.
Linked List,Recursion
Hard
null
2,543
15
# Iterative solution:\n```python3 []\nclass Solution:\n def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:\n def getGroupEnd(cur, k):\n while k > 1 and cur.next:\n cur = cur.next \n k-=1\n return cur if k == 1 else None\n\n def reverseGroup(start, end):\n prev, cur, new_group_start = None, start, end.next\n while cur != new_group_start:\n cur.next, cur, prev = prev, cur.next, cur \n\n dummy = ListNode()\n prev_group = dummy\n while head:\n group_start = head\n group_end = getGroupEnd(head, k)\n if not group_end: break # not enough todes to make a new group\n next_group_start = group_end.next # save link to the next group start\n reverseGroup(group_start, group_end) # reverse the current group\n prev_group.next = group_end # group_end is the start of the reversed group\n prev_group = group_start # group_start is the end of the reversed group\n group_start.next = next_group_start # link current reversed group with the next group\n head = next_group_start # move current point to the start of the next group\n\n return dummy.next \n```\n```python3 []\nclass Solution:\n def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:\n dummy = ListNode()\n prev_group = dummy\n while head:\n j, group_end = 1, head #start of group = end after reverse\n while j < k and head.next:\n head = head.next \n j+=1\n group_start = head #end of group = start after reverse\n next_group = head = head.next #start of next group\n\n if j != k: #don\'t need reverse (not enough nodes)\n break\n #reverse current group without links to prev and next groups\n prev, cur = None, group_end\n while cur != next_group:\n cur.next, cur, prev = prev, cur.next, cur \n\n prev_group.next = group_start\n prev_group = group_end\n group_end.next = next_group\n\n return dummy.next \n```\n![Screenshot 2023-08-03 at 03.09.07.png]()\n# Recursive solution:\n```python3 []\nclass Solution:\n def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:\n if not head: return\n start, end = head, head\n for _ in range(k):\n if not end: return head\n end = end.next\n \n # reverse diapason [start:end)\n def reverse(start, end):\n prev = None\n while start != end:\n start.next, start, prev = prev, start.next, start\n return prev # return head node of the reversed group\n \n newHead = reverse(start, end)\n start.next = self.reverseKGroup(end, k)\n\n return newHead\n```\n![Screenshot 2023-08-03 at 04.06.16.png]()\n\n
2,457
Reverse Nodes in k-Group
reverse-nodes-in-k-group
Given the head of a linked list, reverse the nodes of the list k at a time, and return the modified list. k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is. You may not alter the values in the list's nodes, only nodes themselves may be changed.
Linked List,Recursion
Hard
null
764
8
/**\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 //please UPVOTE\nclass Solution {\npublic:\n int getllsize(ListNode* head){\n ListNode* temp=head;\n int c=0;\n while(temp!=NULL){\n temp=temp->next;\n c++;\n }\n return c;\n }\n \n ListNode* reverseKGroup(ListNode* head, int k) {\n int n =getllsize(head);\n if(head==NULL || n < k)return head;\n ListNode *prev=NULL;\n ListNode *curr=head;\n ListNode *forw=NULL;\n int c=0;\n while(curr!=NULL && c!=k ){\n forw = curr -> next;\n curr -> next=prev;\n prev=curr;\n curr=forw;\n c++;\n }\n head->next=reverseKGroup(curr,k);\n \n \n \n return prev;\n }\n\n};
2,458
Reverse Nodes in k-Group
reverse-nodes-in-k-group
Given the head of a linked list, reverse the nodes of the list k at a time, and return the modified list. k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is. You may not alter the values in the list's nodes, only nodes themselves may be changed.
Linked List,Recursion
Hard
null
37,167
235
class Solution \n {\n public:\n \n ListNode* reverse(ListNode* first, ListNode* last)\n {\n ListNode* prev = last;\n \n while ( first != last )\n {\n auto tmp = first->next;\n first->next = prev;\n prev = first;\n first = tmp;\n }\n \n return prev;\n }\n \n ListNode* reverseKGroup(ListNode* head, int k) \n {\n auto node=head;\n for (int i=0; i < k; ++i)\n {\n if ( ! node )\n return head; // nothing to do list too sort\n node = node->next;\n }\n \n auto new_head = reverse( head, node);\n head->next = reverseKGroup( node, k);\n return new_head;\n }\n };
2,461
Reverse Nodes in k-Group
reverse-nodes-in-k-group
Given the head of a linked list, reverse the nodes of the list k at a time, and return the modified list. k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is. You may not alter the values in the list's nodes, only nodes themselves may be changed.
Linked List,Recursion
Hard
null
1,204
5
\n\n# Code\n```\nclass Solution {\npublic:\n int length(ListNode* head){\n ListNode* temp=head;\n int i=0;\n while(temp!=NULL){\n i++;\n temp=temp->next;\n }\n return i;\n }\n ListNode* reverseKGroup(ListNode* head, int k) {\n if(head==NULL)\n return NULL;\n int len=length(head);\n if(k>len)\n return head;\n\n int count=0;\n ListNode* prev=NULL;\n ListNode* curr=head;\n ListNode* next=head->next;\n //reverse\n while(count<k){\n next=curr->next;\n curr->next=prev;\n prev=curr;\n curr=next;\n count++;\n }\n //reverse ll\n if(next!=NULL)\n head->next=reverseKGroup(next,k);\n return prev;\n }\n};\n```
2,464
Reverse Nodes in k-Group
reverse-nodes-in-k-group
Given the head of a linked list, reverse the nodes of the list k at a time, and return the modified list. k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is. You may not alter the values in the list's nodes, only nodes themselves may be changed.
Linked List,Recursion
Hard
null
1,485
23
```swift\nclass Solution {\n func reverseKGroup(_ head: ListNode?, _ k: Int) -> ListNode? {\n let node = ListNode(0)\n node.next = head\n \n var prev = node\n \n while prev.next != nil {\n var tail: ListNode? = prev\n for _ in 1...k { tail = tail?.next }\n guard var node = tail else { break }\n \n let next = node.next\n var last = next\n var curr = prev.next\n \n while curr !== next {\n let cnext = curr!.next\n curr!.next = last\n last = curr\n curr = cnext\n }\n if let pnext = prev.next { node = pnext }\n prev.next = last\n prev = node\n }\n return node.next\n }\n}\n```\n\n---\n\n<p><details>\n<summary>\n<img src="" height="24">\n<b>TEST CASES</b>\n</summary>\n\n<p><pre>\n<b>Result:</b> Executed 2 tests, with 0 failures (0 unexpected) in 0.040 (0.042) seconds\n</pre></p>\n\n```swift\n// Result: Executed 2 tests, with 0 failures (0 unexpected) in 0.020 (0.022) seconds\n\nimport XCTest\n\nclass Tests: XCTestCase {\n \n private let solution = Solution()\n \n func test0() {\n let value = solution.reverseKGroup(ListNode([1,2,3,4,5]), 2)\n XCTAssertEqual(value?.val, ListNode([2,1,4,3,5])?.val)\n }\n \n func test1() {\n let value = solution.reverseKGroup(ListNode([1,2,3,4,5]), 3)\n XCTAssertEqual(value?.val, ListNode([3,2,1,4,5])?.val)\n }\n}\n\nTests.defaultTestSuite.run()\n```\n\n</details></p>\n\n<p><details>\n<summary>\n<b>ListNode</b>\n</summary>\n\n```swift\npublic class ListNode {\n public var val: Int\n public var next: ListNode?\n public init() { self.val = 0; self.next = nil; }\n public init(_ val: Int) { self.val = val; self.next = nil; }\n public init(_ val: Int, _ next: ListNode?) { self.val = val; self.next = next; }\n \n public init?(_ array: [Int]) {\n guard !array.isEmpty else { return nil }\n self.val = array[0]\n var prev: ListNode = self\n for i in 1..<array.count {\n let new = ListNode(array[i])\n prev.next = new\n prev = new\n }\n }\n}\n```\n\n</details></p>
2,465
Reverse Nodes in k-Group
reverse-nodes-in-k-group
Given the head of a linked list, reverse the nodes of the list k at a time, and return the modified list. k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is. You may not alter the values in the list's nodes, only nodes themselves may be changed.
Linked List,Recursion
Hard
null
654
10
\n![image]()\n![image]()\n![image]()\n\n```\nclass Solution {\npublic:\n int lengthofll(ListNode* head){\n int cnt=0;\n while(head != nullptr){\n cnt++;\n head = head->next;\n }\n return cnt;\n }\n \n ListNode* reverseKGroup(ListNode* head, int k) {\n if(!head || !head->next || k == 1) return head; \n int n = lengthofll(head);\n ListNode* dummy = new ListNode(0);\n dummy->next = head;\n ListNode* pre = dummy;\n ListNode* curr;\n ListNode* nex;\n while(n >= k){\n curr = pre->next;\n nex = curr->next;\n for(int i=1;i < k;i++){\n curr->next = nex->next;\n nex->next = pre->next;\n pre->next = nex;\n nex = curr->next;\n }\n pre = curr;\n n = n-k;\n }\n return dummy->next;\n }\n};\n```\n\n
2,467
Reverse Nodes in k-Group
reverse-nodes-in-k-group
Given the head of a linked list, reverse the nodes of the list k at a time, and return the modified list. k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is. You may not alter the values in the list's nodes, only nodes themselves may be changed.
Linked List,Recursion
Hard
null
4,618
93
```\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 reverseKGroup(self, head: ListNode, k: int) -> ListNode: \n # Check if we need to reverse the group\n curr = head\n for _ in range(k):\n if not curr: return head\n curr = curr.next\n\t\t \n\t\t\t\t\n # Reverse the group (basic way to reverse linked list)\n prev = None\n curr = head\n for _ in range(k):\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n \n\t\t\n # After reverse, we know that `head` is the tail of the group.\n\t\t# And `curr` is the next pointer in original linked list order\n head.next = self.reverseKGroup(curr, k)\n return prev\n ```
2,470
Reverse Nodes in k-Group
reverse-nodes-in-k-group
Given the head of a linked list, reverse the nodes of the list k at a time, and return the modified list. k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is. You may not alter the values in the list's nodes, only nodes themselves may be changed.
Linked List,Recursion
Hard
null
555
5
# [Video link]() \n\n# Code\n```\n// Recursive approach Space O(N) (Stack)\nclass Solution {\npublic:\n ListNode* reverseKGroup(ListNode* head, int k) {\n int size = 0;\n ListNode *temp = head;\n while(temp!=NULL){\n temp = temp -> next;\n size++;\n }\n if(size < k) return head; \n\n // Base call\n if(head == NULL)\n return NULL;\n\n // Step 1 - Reverse first k nodes\n ListNode *curr = head, *prev = NULL, *next = NULL;\n int count = 0;\n while(curr != NULL && count <k){\n next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n count++;\n }\n\n // Step 2 - Use recursion to reverse rest of the nodes\n if(next!=NULL){\n head->next = reverseKGroup(next, k);\n }\n\n // Step 3 - Return head\n return prev;\n }\n};\n\n// Iterative approach Space - O(1)\nclass Solution {\npublic:\n\tListNode* reverseKGroup(ListNode* head, int k) {\n ListNode *dummy = new ListNode(0);\n dummy->next = head;\n ListNode *before = dummy, *after = head;\n ListNode *curr = NULL, *prev = NULL, *nxt = NULL;\n while(true){\n ListNode* cursor = after;\n for(int i = 0; i < k; i++){\n if(cursor == nullptr) \n return dummy->next;\n cursor = cursor->next;\n }\n curr = after;\n prev = before;\n for(int i = 0; i < k; i++){\n nxt = curr->next;\n curr->next = prev;\n prev = curr;\n curr = nxt;\n }\n after->next = curr;\n before->next = prev;\n before = after;\n after = curr;\n }\n }\n};\n```
2,473
Reverse Nodes in k-Group
reverse-nodes-in-k-group
Given the head of a linked list, reverse the nodes of the list k at a time, and return the modified list. k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is. You may not alter the values in the list's nodes, only nodes themselves may be changed.
Linked List,Recursion
Hard
null
9,983
125
This problem is a standard follow up to `LC 206 Reverse Linked List` A lot of the solutions implemented the reversing logic from scratch I am going to pretend that I just finish writing the standard reverse method, and reuse the method on the follow up. ### LC 206 Reverse Linked List ```python class Solution: def reverseList(self, head): if not head or not head.next: return head prev, cur, nxt = None, head, head while cur: nxt = cur.next cur.next = prev prev = cur cur = nxt return prev ``` ### Follow up: Please reverse the list into K Group ```python class Solution(object): def reverseKGroup(self, head, k): count, node = 0, head while node and count < k: node = node.next count += 1 if count < k: return head new_head, prev = self.reverse(head, count) head.next = self.reverseKGroup(new_head, k) return prev def reverse(self, head, count): prev, cur, nxt = None, head, head while count > 0: nxt = cur.next cur.next = prev prev = cur cur = nxt count -= 1 return (cur, prev) ```
2,474
Reverse Nodes in k-Group
reverse-nodes-in-k-group
Given the head of a linked list, reverse the nodes of the list k at a time, and return the modified list. k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is. You may not alter the values in the list's nodes, only nodes themselves may be changed.
Linked List,Recursion
Hard
null
623
6
\n\n\n\n# Code\n```\nclass Solution {\npublic:\n ListNode* reverseKGroup(ListNode* head, int k) {\n // Base case\n if (head == NULL || k == 1) {\n return head;\n }\n\n //step 1: reverse first k Nodes\n ListNode* next = NULL;\n ListNode* curr = head;\n ListNode* prev = NULL;\n int count = 0;\n\n while (curr != NULL && count < k) {\n next = curr->next;\n curr->next = prev;\n prev = curr;\n curr = next;\n count++;\n }\n\n // Check if there are enough nodes to reverse\n if (count < k) {\n // Reverse back the first count nodes to maintain the original order\n ListNode* temp = NULL;\n while (count > 0) {\n temp = prev->next;\n prev->next = curr;\n curr = prev;\n prev = temp;\n count--;\n }\n return curr;\n }\n\n // step 2: recursion for k groups\n if (next != NULL) {\n head->next = reverseKGroup(next, k);\n }\n\n // step 3: return the head of reversed list\n return prev;\n }\n};\n\n```\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(k)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->
2,475
Reverse Nodes in k-Group
reverse-nodes-in-k-group
Given the head of a linked list, reverse the nodes of the list k at a time, and return the modified list. k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is. You may not alter the values in the list's nodes, only nodes themselves may be changed.
Linked List,Recursion
Hard
null
898
6
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(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 */\nclass Solution {\n public ListNode reverseKGroup(ListNode head, int k) {\n if(head==null || k==1) return head;\n\n ListNode dummy = new ListNode();\n dummy.next = head;\n\n ListNode curr = dummy,nex = dummy,pre = dummy;\n\n int count=0;\n while(curr.next!=null){\n curr = curr.next; // counting number of nodes.\n count++;\n }\n\n while(count>=k){ // iterate till groups of k.\n curr = pre.next; // put curr at first and nex at second node of that group.\n nex = curr.next; \n for(int i=1;i<k;i++){ //rum loop K-1 times and revrerse every link.\n curr.next = nex.next;\n nex.next = pre.next;\n pre.next = nex;\n nex = curr.next;\n }\n pre = curr; // to make pre stand at last node of previous reversed group of size k.\n count-=k; // decrementing count by k as the group is reversed and we move to next group of k if present.\n }\n return dummy.next;\n }\n}\n```
2,476
Reverse Nodes in k-Group
reverse-nodes-in-k-group
Given the head of a linked list, reverse the nodes of the list k at a time, and return the modified list. k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is. You may not alter the values in the list's nodes, only nodes themselves may be changed.
Linked List,Recursion
Hard
null
4,468
53
***Solution 1:(Recursion)***\n***\n**Approach:**\n```\n1) The first step is to check whether the Head is NULL or Not, if its NULL then we can directly return NULL,\n2) If the Head is not NULL, then we need to check the length of Linked List starting from current Head.\n3) If it is not a multiple of K(Less than K) , then there is no need to reverse it and hence we can directly return head,\n4) Else if its a multiple of K, then we have to reverse the K elements starting from current Head,\n5) We will follow the same steps for the rest of the elements Recursively.\n```\n***\n**C++:**\n```\nclass Solution {\npublic:\n ListNode* reverseKGroup(ListNode* head, int k) \n {\n if(!head)\n return NULL;\n ListNode *KSizeChecker = head;\n for(int i=0;i<k;i++)\n {\n if(KSizeChecker==NULL)\n return head;\n KSizeChecker = KSizeChecker->next;\n }\n int cnt=0;\n ListNode *cur=head,*prev=NULL,*next=NULL;\n while(cur and cnt<k)\n {\n next=cur->next;\n cur->next=prev;\n prev=cur;\n cur=next;\n cnt++;\n }\n if(next)\n head->next=reverseKGroup(next,k);\n return prev;\n }\n};\n```\n\n***\n***Solution 2:(Iterative):***\n**Approach:**\n```\n1) We first try to find out the length of linked list,\nLet it be "Len"\n2) Now we try to find out , how many groups of size "K" are there to reverse,\nthis can be easily done using the formula --- "Len/K"\n3) Hence we have Len/K groups to reverse,\n4) To easily find out the new Linked List\'s Head(After reversal), we will make a dummyNode just before the head,\nand at last for new Head we can directly return dummyNode->next,\n5) The reversal of linked list is very easy ,\nwe just need to keep track of remaining Nodes and the new head for reversed linked list.\n```\n\n**C++:**\n```\nclass Solution {\n int getLengthOfLinkedList(ListNode *head)\n {\n ListNode *ptr = head;\n int cnt=0;\n while(ptr)\n {\n cnt++;\n ptr=ptr->next;\n }\n return cnt;\n }\npublic:\n ListNode* reverseKGroup(ListNode* head, int k) \n {\n if(!head)\n return NULL;\n \n int len = getLengthOfLinkedList(head);\n if(len<k)\n return head;\n \n int numberOfGroupsToReverse = len/k;\n \n ListNode *dummyNode = new ListNode(-1);\n dummyNode->next = head;\n ListNode *start = dummyNode;\n\n ListNode *pre,*remaining,*next;\n for(int i=0;i<numberOfGroupsToReverse;i++)\n {\n pre = NULL;\n remaining = head;\n for(int j=0;j<k;j++)\n {\n next = head->next;\n head->next = pre;\n pre=head;\n head=next;\n }\n start->next = pre;\n remaining->next = head;\n start = remaining;\n }\n \n return dummyNode->next;\n }\n};\n```\n
2,477
Reverse Nodes in k-Group
reverse-nodes-in-k-group
Given the head of a linked list, reverse the nodes of the list k at a time, and return the modified list. k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is. You may not alter the values in the list's nodes, only nodes themselves may be changed.
Linked List,Recursion
Hard
null
977
5
```\nclass Solution {\n public ListNode reverseKGroup(ListNode head, int k) {\n // base case\n if(k == 1) return head;\n\t\t// first keep finding each group until we found last group\n\t\t// there is no need to reverse the last group when we found it, just return start point of it\n\t\t// even if the last group is null, it is still fine, just return it\n ListNode curr = head;\n for(int i = 0 ; i < k ; i ++) {\n if(head != null) {\n head = head.next;\n }else {\n // last group found\n return curr;\n }\n }\n // recursion\n ListNode nextGroup = reverseKGroup(head,k);\n // back tracking reverse curr group\n ListNode finalTail = curr;\n ListNode prev = curr;\n ListNode tempNext = null;\n for(int i = 0 ; i < k ; i ++) {\n tempNext = curr.next;\n curr.next = prev;\n prev = curr;\n curr = tempNext;\n }\n // connect reversed curr to next group\n finalTail.next = nextGroup;\n\t\t// return new reversed first node of curr group(which the prev point to) and keep back tracking until stack is empty\n return prev;\n }\n}\n```
2,479
Reverse Nodes in k-Group
reverse-nodes-in-k-group
Given the head of a linked list, reverse the nodes of the list k at a time, and return the modified list. k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is. You may not alter the values in the list's nodes, only nodes themselves may be changed.
Linked List,Recursion
Hard
null
1,052
6
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe are asked to reverse nodes in groups. We will reverse first k nodes, then make a recursive call.\n\nif you dont know, how to reverse LL, go and check- \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. check reverse LL, through link.\n2. Here, we take x = k, to check if Further k nodes are present or not.\n3. if present, then reverse the K nodes. \n4. if not, return head bcz head is pointing to the next element , that is, forward node. EXAMPLE- 1,2,3,4,5 AND K = 3, in this, head points to 4. and it gets attached to head->next pointer. \n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->O(N)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->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 */\nclass Solution {\npublic:\n ListNode* reverseKGroup(ListNode* head, int k) {\n if(head == NULL)\n return head;\n\n int x = k, count = 0;\n ListNode* temp = head;\n while(x > 0 && temp != NULL){\n temp = temp -> next;\n x--;\n }\n if(x == 0)\n {\n ListNode* forward = NULL;\n ListNode* curr = head;\n ListNode* prev = NULL;\n while(count < k){\n forward = curr -> next;\n curr -> next = prev;\n prev = curr;\n curr = forward;\n count++:\n }\n head -> next = reverseKGroup(forward, k);\n return prev;\n }\n else\n return head; // gets attached to head->next as it points to null.\n }\n};\n```
2,483
Reverse Nodes in k-Group
reverse-nodes-in-k-group
Given the head of a linked list, reverse the nodes of the list k at a time, and return the modified list. k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is. You may not alter the values in the list's nodes, only nodes themselves may be changed.
Linked List,Recursion
Hard
null
2,467
43
This is quite classical linked list problem and it is quite nasty in my opinion. It can be a bit problematic to imagine all this in your head, do it on paper. The idea is to add dummy variable, then calculate number of nodes. We need this, because we do not need to reverse last group. Then we use idea similar to problem **0206** Reverse Linked List: but here we need to reverse `k` elements, and then reconnect first and last nodes in each group and update `cnt`.\n\n#### Complexity\nTime complexity is `O(n)`, space complexity is `O(1)`.\n\n#### Code\n```python\nclass Solution:\n def reverseKGroup(self, head, k):\n dummy = ListNode(0)\n dummy.next = head\n cur, nxt, pre = dummy, dummy, dummy\n cnt = 0\n while cur.next:\n cnt += 1\n cur = cur.next\n \n while cnt >= k:\n cur = new = pre.next\n nxt = cur.next\n for _ in range(k-1):\n tmp = nxt.next\n nxt.next = cur\n cur = nxt\n nxt = tmp\n \n pre.next = cur\n new.next = nxt\n pre = new\n cnt -= k\n \n return dummy.next\n```\n\nIf you have any questions, feel free to ask. If you like solution and explanations, please **Upvote!**
2,489
Reverse Nodes in k-Group
reverse-nodes-in-k-group
Given the head of a linked list, reverse the nodes of the list k at a time, and return the modified list. k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is. You may not alter the values in the list's nodes, only nodes themselves may be changed.
Linked List,Recursion
Hard
null
1,358
8
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(N)\n<!-- Add your space complexity here, 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 */\nclass Solution {\npublic:\n ListNode* reverseKGroup(ListNode* head, int k) {\n \n if(head==NULL)\n return NULL;\n \n //reverse 1st k nodes\n ListNode* forward=NULL;\n ListNode* prev=NULL;\n ListNode* curr=head;\n int cnt=0;\n \n ListNode* cursor = head;\n for(int i = 0; i < k; i++){\n if(cursor == nullptr) \n return head;\n cursor = cursor->next;\n }\n while(curr!=NULL && cnt<k ){\n forward=curr->next;\n curr->next=prev;\n prev=curr;\n curr=forward;\n cnt++;\n }\n \n head->next=reverseKGroup(forward,k);\n return prev;\n }\n};\n```
2,490
Reverse Nodes in k-Group
reverse-nodes-in-k-group
Given the head of a linked list, reverse the nodes of the list k at a time, and return the modified list. k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is. You may not alter the values in the list's nodes, only nodes themselves may be changed.
Linked List,Recursion
Hard
null
522
8
We will use the intuition behind Reverse Linked List.Only difference is we will reverse Nodes in K group. So we will seggregate the Linked List into size K and let recursion handle the rest.\n```\nclass Solution {\npublic:\n ListNode* reverseKGroup(ListNode* head, int k) {\n \n //base condition\n //to not reverse the last group which is less than k\n ListNode* temp=head;\n for(int i=0;i<k;i++)\n {\n if(temp==nullptr)\n return head;\n temp=temp->next;\n }\n \n \n //reverse first k nodes\n ListNode* prev=nullptr;\n ListNode* curr=head;\n ListNode* next=nullptr;\n int count=0;\n \n while(curr && count<k){\n next=curr->next;\n curr->next=prev;\n prev=curr;\n curr=next;\n count++;\n }\n \n //recursion will take care the rest\n if(next){\n head->next = reverseKGroup(next,k);\n }\n \n //return head of reversed list i.e., prev\n return prev;\n }\n};\n```\n\n**PLEASE UPVOTE** *if you liked the approach*
2,493
Reverse Nodes in k-Group
reverse-nodes-in-k-group
Given the head of a linked list, reverse the nodes of the list k at a time, and return the modified list. k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is. You may not alter the values in the list's nodes, only nodes themselves may be changed.
Linked List,Recursion
Hard
null
1,615
6
*Time Complexity - O(n)*\nPlease upvote if it was helpful\n\n```\n\nclass Solution {\n public ListNode reverseKGroup(ListNode head, int k) {\n \n ListNode dum = new ListNode(0);\n dum.next = head;\n ListNode pointer = dum;\n while (pointer != null) {\n ListNode node = pointer;\n // check there are k nodes to reverse\n for (int i = 0; i < k && node != null; i++) {\n node = node.next;\n }\n if (node == null) break;\n \n // we have k nodes, then start from the first node\n ListNode prev = null, curr = pointer.next, next = null;\n for (int i = 0; i < k; i++) {\n next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n ListNode tail = pointer.next;\n tail.next = curr;\n pointer.next = prev;\n pointer = tail;\n }\n return dum.next;\n }\n }\n```\n
2,494
Remove Duplicates from Sorted Array
remove-duplicates-from-sorted-array
Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements. Return k after placing the final result in the first k slots of nums. Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory. Custom Judge: The judge will test your solution with the following code: If all assertions pass, then your solution will be accepted.
Array,Two Pointers
Easy
In this problem, the key point to focus on is the input array being sorted. As far as duplicate elements are concerned, what is their positioning in the array when the given array is sorted? Look at the image above for the answer. If we know the position of one of the elements, do we also know the positioning of all the duplicate elements? We need to modify the array in-place and the size of the final array would potentially be smaller than the size of the input array. So, we ought to use a two-pointer approach here. One, that would keep track of the current element in the original array and another one for just the unique elements. Essentially, once an element is encountered, you simply need to bypass its duplicates and move on to the next unique element.
175,562
1,168
# Intuition:\nThe Intuition is to use two pointers, `i` and `j`, to iterate through the array. The variable `j` is used to keep track of the current index where a unique element should be placed. The initial value of `j` is 1 since the first element in the array is always unique and doesn\'t need to be changed.\n\n# Explanation:\nThe code starts iterating from `i = 1` because we need to compare each element with its previous element to check for duplicates.\n\nThe main logic is inside the `for` loop:\n1. If the current element `nums[i]` is not equal to the previous element `nums[i - 1]`, it means we have encountered a new unique element.\n2. In that case, we update `nums[j]` with the value of the unique element at `nums[i]`, and then increment `j` by 1 to mark the next position for a new unique element.\n3. By doing this, we effectively overwrite any duplicates in the array and only keep the unique elements.\n\nOnce the loop finishes, the value of `j` represents the length of the resulting array with duplicates removed.\n\nFinally, we return `j` as the desired result.\n\n# Code\n```C++ []\nclass Solution {\npublic:\n int removeDuplicates(vector<int>& nums) {\n int j = 1;\n for(int i = 1; i < nums.size(); i++){\n if(nums[i] != nums[i - 1]){\n nums[j] = nums[i];\n j++;\n }\n }\n return j;\n }\n};\n```\n```Java []\nclass Solution {\n public int removeDuplicates(int[] nums) {\n int j = 1;\n for (int i = 1; i < nums.length; i++) {\n if (nums[i] != nums[i - 1]) {\n nums[j] = nums[i];\n j++;\n }\n }\n return j;\n }\n}\n```\n```Python3 []\nclass Solution:\n def removeDuplicates(self, nums: List[int]) -> int:\n j = 1\n for i in range(1, len(nums)):\n if nums[i] != nums[i - 1]:\n nums[j] = nums[i]\n j += 1\n return j\n```\n\n![CUTE_CAT.png]()\n\n**If you are a beginner solve these problems which makes concepts clear for future coding:**\n1. [Two Sum]()\n2. [Roman to Integer]()\n3. [Palindrome Number]()\n4. [Maximum Subarray]()\n5. [Remove Element]()\n6. [Contains Duplicate]()\n7. [Add Two Numbers]()\n8. [Majority Element]()\n9. [Remove Duplicates from Sorted Array]()\n10. **Practice them in a row for better understanding and please Upvote the post for more questions.**\n\n**If you found my solution helpful, I would greatly appreciate your upvote, as it would motivate me to continue sharing more solutions.**
2,500
Remove Duplicates from Sorted Array
remove-duplicates-from-sorted-array
Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements. Return k after placing the final result in the first k slots of nums. Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory. Custom Judge: The judge will test your solution with the following code: If all assertions pass, then your solution will be accepted.
Array,Two Pointers
Easy
In this problem, the key point to focus on is the input array being sorted. As far as duplicate elements are concerned, what is their positioning in the array when the given array is sorted? Look at the image above for the answer. If we know the position of one of the elements, do we also know the positioning of all the duplicate elements? We need to modify the array in-place and the size of the final array would potentially be smaller than the size of the input array. So, we ought to use a two-pointer approach here. One, that would keep track of the current element in the original array and another one for just the unique elements. Essentially, once an element is encountered, you simply need to bypass its duplicates and move on to the next unique element.
66,272
377
# Intuition\nWe can think of using two pointers \u2018i\u2019 and \u2018j\u2019, we move \u2018j\u2019 till we don\u2019t get a number arr[j] which is different from arr[i]. As we got a unique number we will increase the i pointer and update its value by arr[j]. \n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nTake a variable i as 0;\nUse a for loop by using a variable \u2018j\u2019 from 1 to length of the array.\nIf arr[j] != arr[i], increase \u2018i\u2019 and update arr[i] == arr[j].\n After completion of the loop return i+1, i.e size of the array of unique elements.\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```\nclass Solution {\n public int removeDuplicates(int[] arr) {\n int i=0;\n for(int j=1;j<arr.length;j++){\n if(arr[i]!=arr[j]){\n i++;\n arr[i]=arr[j];\n }\n }\n return i+1;\n \n }\n}\n```\n![images.jpeg]()\n
2,501
Remove Duplicates from Sorted Array
remove-duplicates-from-sorted-array
Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements. Return k after placing the final result in the first k slots of nums. Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory. Custom Judge: The judge will test your solution with the following code: If all assertions pass, then your solution will be accepted.
Array,Two Pointers
Easy
In this problem, the key point to focus on is the input array being sorted. As far as duplicate elements are concerned, what is their positioning in the array when the given array is sorted? Look at the image above for the answer. If we know the position of one of the elements, do we also know the positioning of all the duplicate elements? We need to modify the array in-place and the size of the final array would potentially be smaller than the size of the input array. So, we ought to use a two-pointer approach here. One, that would keep track of the current element in the original array and another one for just the unique elements. Essentially, once an element is encountered, you simply need to bypass its duplicates and move on to the next unique element.
52,009
575
\n## \u2705 Method 1: sort in place using `[:]`\n```\n\tdef removeDuplicates(self, nums: List[int]) -> int:\n\t\tnums[:] = sorted(set(nums))\n\t\treturn len(nums)\n```\n\n\n**Time Complexity:** `O(n)`\n**Space Complexity:** `O(1)`\n\n\n### \u274C Common Wrong Answers:\n```\n\tnums = sorted(set(nums))\n\treturn len(nums)\n```\n\xA0`nums =`\xA0 doesn\'t replace elements in the original list.\n `nums[:] =`\xA0replaces element in place\n\nIn short, without `[:]`, we\'re creating a new list object, which is against what this problem is asking for:\n"Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory."\n\n-----------------------\n## \u2705 Method 2: Two-pointers\n### \uD83E\uDD14 Initial Intuition:\nUse a `slow` pointer to "lock" the "wanted" element, and use a `fast` pointer to move forward along the list and look for new unique elements in the list.\nOr, in other words, the current `slow` pointer is used to locate the latest unique number for the results, and `fast` is used for iterating and discovery.\n\nHave `fast` advanced in every iteration, but `slow` is only advanced when two pointers are onto two different elements. \n\nThat means, the elements after `nums[slow]` and before `nums[fast]` are numbers we\'ve **seen** before and don\'t need anymore (one copy of these numbers is already saved before the current `slow` (inclusive)). \n\nTherefore, in order to have this newly discovered (unseen) number pointed by the current `fast` to the front of the array for the final answer, we just need to swap this newly discovered number to the location that follows the current `slow` pointer, with one of the **seen** numbers (we don\'t need it for the answer regardlessly), and then advance the `slow` in the same iteration to lock this new number.\n\n```\n\tdef removeDuplicates(self, nums: List[int]) -> int:\n\t\tslow, fast = 0, 1\n\t\twhile fast in range(len(nums)):\n\t\t\tif nums[slow] == nums[fast]:\n\t\t\t\tfast += 1\n\t\t\telse:\n\t\t\t\tnums[slow+1] = nums[fast]\n\t\t\t\tfast += 1\n\t\t\t\tslow += 1\n\n\t\treturn slow + 1\n```\n\n### \u2747\uFE0F Simplified two-pointers with for loops:\n\uD83D\uDCA1 However, observe, `fast` pointer is simply incremented in every iteration regardless of the conditions, that\'s just a typical for loop\'s job. Therefore, we can simplify this "two-pointers" system as follows:\n```\n\tdef removeDuplicates(self, nums: List[int]) -> int:\n\t\tj = 0\n\t\tfor i in range(1, len(nums)):\n\t\t\tif nums[j] != nums[i]:\n\t\t\t\tj += 1\n\t\t\t\tnums[j] = nums[i]\n\t\treturn j + 1\n```\n\n**Time Complexity:** `O(n)`\n**Space Complexity:** `O(1)`\n\n-----------------------\n## Method 3: Using `.pop()`\n```\n\tdef removeDuplicates(self, nums: List[int]) -> int:\n\t\ti = 1\n\t\twhile i < len(nums):\n\t\t\tif nums[i] == nums[i - 1]:\n\t\t\t\tnums.pop(i)\n\t\t\telse:\n\t\t\t\ti += 1\n\t\treturn len(nums)\n```\n-----------------------\n## Method 4: Using `OrderedDict.fromkeys()`\n```\nfrom collections import OrderedDict\nclass Solution(object):\n def removeDuplicates(self, nums):\n nums[:] = OrderedDict.fromkeys(nums)\n return len(nums)\n```\n-------------------\n-----------------------\nAs a total beginner, I am 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 for beginners in anyway.\nYour upvote is much more than just supportive to me. \uD83D\uDE33\uD83E\uDD13\uD83E\uDD70\n\nIf you find this is not helpful, needs improvement, or is questionable, would you please leave a quick comment below to point out the problem before you decide to downvote? It will be very helpful for me (maybe also others) to learn as a beginner.\n\nThank you very much either way \uD83E\uDD13.
2,502
Remove Duplicates from Sorted Array
remove-duplicates-from-sorted-array
Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements. Return k after placing the final result in the first k slots of nums. Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory. Custom Judge: The judge will test your solution with the following code: If all assertions pass, then your solution will be accepted.
Array,Two Pointers
Easy
In this problem, the key point to focus on is the input array being sorted. As far as duplicate elements are concerned, what is their positioning in the array when the given array is sorted? Look at the image above for the answer. If we know the position of one of the elements, do we also know the positioning of all the duplicate elements? We need to modify the array in-place and the size of the final array would potentially be smaller than the size of the input array. So, we ought to use a two-pointer approach here. One, that would keep track of the current element in the original array and another one for just the unique elements. Essentially, once an element is encountered, you simply need to bypass its duplicates and move on to the next unique element.
627
10
\n\nOne option is to use the pop() method to pop any duplicates that are detected, but using pop() is actually very inefficient because if we pop an element near the start of the array, we now have to shift all the other elements back 1 space. So each pop() runs in O(n) time, and in the worst case, we\'d have to pop n-1 elements, so the algorithm would run in O(n<sup>2</sup>) time.\n\nInstead, we\'ll use an O(n) 2-pointer approach. One pointer, `replace`, will keep track of which element we need to overwrite/replace. The other one, loop variable `i`, will traverse the entire array and detect duplicates. Since we know the array is already sorted, we can detect duplicates by comparing each element to the one before it. If they\'re the same, then we\'ve found a duplicate.\n\nIf a duplicate is found, we just keep incrementing `i` while keeping `replace` at the same spot. Basically, we keep searching for the next unique element. Once a unique element is found, we overwrite the element at the `replace`index with the unique one we just found. Then we increment `replace` so that it\'s ready to write at the next slot.\n\nAt the end, we can just return `replace` since it\'s been keeping track of the index of the last unique element written.\n\n# Code\n```\nclass Solution(object):\n def removeDuplicates(self, nums):\n replace = 1\n for i in range(1, len(nums)):\n if nums[i-1] != nums[i]:\n nums[replace] = nums[i]\n replace += 1\n return replace\n```
2,505
Remove Duplicates from Sorted Array
remove-duplicates-from-sorted-array
Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements. Return k after placing the final result in the first k slots of nums. Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory. Custom Judge: The judge will test your solution with the following code: If all assertions pass, then your solution will be accepted.
Array,Two Pointers
Easy
In this problem, the key point to focus on is the input array being sorted. As far as duplicate elements are concerned, what is their positioning in the array when the given array is sorted? Look at the image above for the answer. If we know the position of one of the elements, do we also know the positioning of all the duplicate elements? We need to modify the array in-place and the size of the final array would potentially be smaller than the size of the input array. So, we ought to use a two-pointer approach here. One, that would keep track of the current element in the original array and another one for just the unique elements. Essentially, once an element is encountered, you simply need to bypass its duplicates and move on to the next unique element.
7,465
43
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe goal is to remove duplicates from a sorted integer array nums while keeping track of the number of unique elements. The function should return the count of unique elements and modify the input array in-place to contain only the unique elements at the beginning in the same order.\n\n---\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. First, we check if the input vector nums is empty. If it is empty, there are no unique elements, so we return 0.\n\n2. We initialize a variable k to 1. This variable will keep track of the count of unique elements in the modified nums array.\n\n3. We iterate through the input vector nums starting from the second element (index 1) using a for loop.\n\n4. Inside the loop, we compare the current element nums[i] with the previous unique element nums[k - 1]. If they are not equal, it means we have encountered a new unique element. In this case, we update the nums[k] position with the current element to keep it in place. We then increment k to indicate that we have found one more unique element.\n\n5. After the loop completes, k contains the count of unique elements, and the first k elements of the nums vector contain the unique elements in the same order they appeared in the input.\n\n6. We return the value of k as the final count of unique elements.\n\n---\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nThe time complexity of this algorithm is O(n), where n is the number of elements in the input vector nums. This is because we iterate through the input vector once, and each iteration takes constant time.\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nThe space complexity of this algorithm is O(1) because it modifies the input array in-place without using any additional data structures that depend on the size of the input.\n\n---\n\n# \uD83D\uDCA1"If you have advanced to this point, I kindly request that you consider upvoting this solution to broaden its reach among others."\u2763\uFE0F\uD83D\uDCA1\n\n---\n\n```C++ []\nclass Solution {\npublic:\n int removeDuplicates(vector<int>& nums) {\n if (nums.empty()) {\n return 0;\n }\n\n int k = 1; // Initialize the count of unique elements to 1\n for (int i = 1; i < nums.size(); i++) {\n if (nums[i] != nums[i - 1]) {\n nums[k] = nums[i]; // Overwrite the next unique element\n k++;\n }\n }\n \n return k;\n }\n};\n\n```\n```Java []\npublic class Solution {\n public int removeDuplicates(int[] nums) {\n if (nums.length == 0) {\n return 0;\n }\n\n int k = 1; // Initialize the count of unique elements to 1\n for (int i = 1; i < nums.length; i++) {\n if (nums[i] != nums[k - 1]) {\n nums[k] = nums[i]; // Overwrite the next unique element\n k++;\n }\n }\n \n return k;\n }\n}\n\n```\n```Python []\nclass Solution:\n def removeDuplicates(self, nums):\n if not nums:\n return 0\n \n k = 1 # Initialize the count of unique elements to 1\n for i in range(1, len(nums)):\n if nums[i] != nums[i - 1]:\n nums[k] = nums[i] # Overwrite the next unique element\n k += 1\n \n return k\n\n```\n```Javascript []\nfunction removeDuplicates(nums) {\n if (nums.length === 0) {\n return 0;\n }\n\n let k = 1; // Initialize the count of unique elements to 1\n for (let i = 1; i < nums.length; i++) {\n if (nums[i] !== nums[k - 1]) {\n nums[k] = nums[i]; // Overwrite the next unique element\n k++;\n }\n }\n\n return k;\n}\n\n```\n```C []\nint removeDuplicates(int* nums, int numsSize) {\n if (numsSize == 0) {\n return 0;\n }\n\n int k = 1; // Initialize the count of unique elements to 1\n for (int i = 1; i < numsSize; i++) {\n if (nums[i] != nums[k - 1]) {\n nums[k] = nums[i]; // Overwrite the next unique element\n k++;\n }\n }\n\n return k;\n}\n\n```\n```Ruby []\nclass Solution\n def remove_duplicates(nums)\n return 0 if nums.empty?\n\n k = 1 # Initialize the count of unique elements to 1\n (1...nums.size).each do |i|\n if nums[i] != nums[k - 1]\n nums[k] = nums[i] # Overwrite the next unique element\n k += 1\n end\n end\n\n k\n end\nend\n\n```\n\n# Do Upvote if you like the solution and Explanation please \u2763\uFE0F
2,506
Remove Duplicates from Sorted Array
remove-duplicates-from-sorted-array
Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements. Return k after placing the final result in the first k slots of nums. Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory. Custom Judge: The judge will test your solution with the following code: If all assertions pass, then your solution will be accepted.
Array,Two Pointers
Easy
In this problem, the key point to focus on is the input array being sorted. As far as duplicate elements are concerned, what is their positioning in the array when the given array is sorted? Look at the image above for the answer. If we know the position of one of the elements, do we also know the positioning of all the duplicate elements? We need to modify the array in-place and the size of the final array would potentially be smaller than the size of the input array. So, we ought to use a two-pointer approach here. One, that would keep track of the current element in the original array and another one for just the unique elements. Essentially, once an element is encountered, you simply need to bypass its duplicates and move on to the next unique element.
33,894
169
# 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# Code\n```\nclass Solution:\n def removeDuplicates(self, nums: List[int]) -> int:\n i,j=0,1\n while i<=j and j<len(nums):\n if nums[i]==nums[j]:\n j+=1\n else:\n nums[i+1]=nums[j]\n i+=1\n return i+1\n\n\n \n```\n# Consider upvoting if found helpul\n \n![57jfh9.jpg]()\n
2,507
Remove Duplicates from Sorted Array
remove-duplicates-from-sorted-array
Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements. Return k after placing the final result in the first k slots of nums. Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory. Custom Judge: The judge will test your solution with the following code: If all assertions pass, then your solution will be accepted.
Array,Two Pointers
Easy
In this problem, the key point to focus on is the input array being sorted. As far as duplicate elements are concerned, what is their positioning in the array when the given array is sorted? Look at the image above for the answer. If we know the position of one of the elements, do we also know the positioning of all the duplicate elements? We need to modify the array in-place and the size of the final array would potentially be smaller than the size of the input array. So, we ought to use a two-pointer approach here. One, that would keep track of the current element in the original array and another one for just the unique elements. Essentially, once an element is encountered, you simply need to bypass its duplicates and move on to the next unique element.
26,932
166
THIS QUESTION IS SOLVED BY USING SET .......\n 1.First of all we have to create an empty set then we have to store all the element in the set.\n 2.As we know in set all element appears once...so it is clear that no element is repeated.\n 3.Then we have to return the size of element and which is present in set but before we have to restore all the element in the nums array.\n 4.so first of all clear all the element in the nums array using **nums.clear( );**\n 5.Then in nums array push all the set element.\n 6.And in last return the size of set.\n\n```\nclass Solution {\npublic:\n int removeDuplicates(vector<int>& nums) {\n set<int> s; \n for(int i =0; i<nums.size(); i++)\n {\n s.insert(nums[i]);\n }\n \n int ans = s.size();\n nums.clear();\n for(auto i:s)\n {\n //int k = *i;\n nums.push_back(i);\n }\n return ans;\n }\n};\n```\n IF MY EFFORTS HELP YOU PLEASE LIKE IT\uD83D\uDE0A\uD83D\uDE0A\n ![image]()\n\n \n
2,509
Remove Duplicates from Sorted Array
remove-duplicates-from-sorted-array
Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements. Return k after placing the final result in the first k slots of nums. Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory. Custom Judge: The judge will test your solution with the following code: If all assertions pass, then your solution will be accepted.
Array,Two Pointers
Easy
In this problem, the key point to focus on is the input array being sorted. As far as duplicate elements are concerned, what is their positioning in the array when the given array is sorted? Look at the image above for the answer. If we know the position of one of the elements, do we also know the positioning of all the duplicate elements? We need to modify the array in-place and the size of the final array would potentially be smaller than the size of the input array. So, we ought to use a two-pointer approach here. One, that would keep track of the current element in the original array and another one for just the unique elements. Essentially, once an element is encountered, you simply need to bypass its duplicates and move on to the next unique element.
2,281
32
# Intuition\nsee below image and see code simultenously\n![Screenshot (1100).png]()\n![Screenshot (1102).png]()\n![Screenshot (1103).png]()\n![Screenshot (1104).png]()\n![Screenshot (1105).png]()\n\n\n\n\n\n\n\n\n\n# Code\n```\nclass Solution {\npublic:\n int removeDuplicates(vector<int>& nums) {\n if(nums.size()<=1) return nums.size();\n int position=1;\n for(int i=1;i<nums.size();++i){\n if(nums[i]!=nums[position-1]){\n nums[position]=nums[i];\n position++;\n }\n }\n return position;\n }\n};\n```\n\n# Time complexity :- O(n)\n# space complexity :- O(1);\n\n# PLEASE upvote if you like my solution \n![begging.jpg]()\n
2,512
Remove Duplicates from Sorted Array
remove-duplicates-from-sorted-array
Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements. Return k after placing the final result in the first k slots of nums. Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory. Custom Judge: The judge will test your solution with the following code: If all assertions pass, then your solution will be accepted.
Array,Two Pointers
Easy
In this problem, the key point to focus on is the input array being sorted. As far as duplicate elements are concerned, what is their positioning in the array when the given array is sorted? Look at the image above for the answer. If we know the position of one of the elements, do we also know the positioning of all the duplicate elements? We need to modify the array in-place and the size of the final array would potentially be smaller than the size of the input array. So, we ought to use a two-pointer approach here. One, that would keep track of the current element in the original array and another one for just the unique elements. Essentially, once an element is encountered, you simply need to bypass its duplicates and move on to the next unique element.
7,358
48
**\u2705 IF YOU LIKE THIS SOLUTION, PLEASE UPVOTE.**\n****\nThis solution employs a two-pointers approach for rearrangement of numbers in a sorted array. Time complexity is linear: **O(N)**. Space complexity is constant: **O(1)**.\n\n**Comment.** The strategy here is to iterate over the input array (first pointer) and move its unique elements to the end of deduplicated array. The input array is sorted, thus, during iteration, each unique value appears as the one that differs from the last one. When encountered a new unique value, we also update the position of the end of deduplicated array (second pointer).\n\n**Python #1**.\n```\nclass Solution:\n def removeDuplicates(self, nums: List[int], k = 1) -> int:\n for i in range(1,len(nums)):\n if nums[i] != nums[i-1]: # detect next unique value \n nums[k] = nums[i] # move it to the end of deduplicated array\n k += 1 # update the size of deduplicated array\n return k\n```\n\nThere is also a stack-based type of solution that is **O(N\\*N)** in time (due to the linear-time *pop*) but still **O(1)** in (additionally allocated) space.\n\n**Python #2.**\n```\nclass Solution:\n def removeDuplicates(self, nums: List[int]) -> int:\n\n for i in reversed(range(1,len(nums))):\n if nums[i] == nums[i-1]:\n nums.pop(i)\n return len(nums)\n```\n\n<iframe src="" frameBorder="0" width="800" height="250"></iframe>\n\n**\u2705 YOU MADE IT TILL THE BONUS SECTION... YOUR GREAT EFFORT DESERVES UPVOTING THIS POST!**\n\nAs a **BONUS**, I provide a couple of one-liners...\n\n**Python #1.** Note that here we use a generator that has **O(1)** space complexity.\n```\nclass Solution:\n def removeDuplicates(self, nums: List[int]) -> int:\n nums[:] = (n for i, n in enumerate(nums) if i == 0 or nums[i-1] != n)\n```\n\n**Python #2.** Well, here it\'s not an **O(1)**-complexity solution, but very concise...\n```\nclass Solution:\n def removeDuplicates(self, nums: List[int], k = 1) -> int:\n nums[:] = sorted(list(set(nums)))\n```\n\n**C++.** The *unique* function returns an iterator to which we can apply *distance* or just subtraction.\n```\nclass Solution \n{\npublic:\n int removeDuplicates(vector<int>& nums, int k = 1)\n {\n\t\treturn distance(nums.begin(), unique(nums.begin(), nums.end()));\n\t\t// or just subtract iterators...\n\t\t// return unique(nums.begin(), nums.end()) - nums.begin();\n }\n};\n```\n\n**Rust.** Using a built-in *dedup* function.\n```\nimpl Solution \n{\n pub fn remove_duplicates(nums: &mut Vec<i32>) -> i32 \n {\n nums.dedup(); nums.len() as _\n }\n}\n```
2,515
Remove Duplicates from Sorted Array
remove-duplicates-from-sorted-array
Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements. Return k after placing the final result in the first k slots of nums. Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory. Custom Judge: The judge will test your solution with the following code: If all assertions pass, then your solution will be accepted.
Array,Two Pointers
Easy
In this problem, the key point to focus on is the input array being sorted. As far as duplicate elements are concerned, what is their positioning in the array when the given array is sorted? Look at the image above for the answer. If we know the position of one of the elements, do we also know the positioning of all the duplicate elements? We need to modify the array in-place and the size of the final array would potentially be smaller than the size of the input array. So, we ought to use a two-pointer approach here. One, that would keep track of the current element in the original array and another one for just the unique elements. Essentially, once an element is encountered, you simply need to bypass its duplicates and move on to the next unique element.
38,962
120
# Approach\nBy iterating through the array and checking if `nums` at the current index `i` is less than `nums` at `i + 1`, we can find an index for all unique numbers in the array. We can then insert each of these numbers to the beginning of the array, at `addIndex`. `addIndex` starts at 0 as the first element in the array is always unique.\n\n# Complexity\n- Time complexity: O(n)\n\n- Space complexity: O(1)\n\n# Code\n```\nclass Solution {\n public int removeDuplicates(int[] nums) {\n if(nums.length == 0)\n return 0;\n \n int addIndex = 1; //index that unique characters will be inserted at\n\n for(int i = 0; i < nums.length - 1; i++) {\n \n if(nums[i] < nums[i + 1]){ //if true, num[i + 1] is a new unique number\n nums[addIndex] = nums[i + 1];\n addIndex++;\n }\n }\n return addIndex;\n }\n}\n```
2,517
Remove Duplicates from Sorted Array
remove-duplicates-from-sorted-array
Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements. Return k after placing the final result in the first k slots of nums. Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory. Custom Judge: The judge will test your solution with the following code: If all assertions pass, then your solution will be accepted.
Array,Two Pointers
Easy
In this problem, the key point to focus on is the input array being sorted. As far as duplicate elements are concerned, what is their positioning in the array when the given array is sorted? Look at the image above for the answer. If we know the position of one of the elements, do we also know the positioning of all the duplicate elements? We need to modify the array in-place and the size of the final array would potentially be smaller than the size of the input array. So, we ought to use a two-pointer approach here. One, that would keep track of the current element in the original array and another one for just the unique elements. Essentially, once an element is encountered, you simply need to bypass its duplicates and move on to the next unique element.
4,201
12
# Explanation \nTake a pointer `position` to point the available position for distinct value\n\nCheck for each current value `currValue` whether the element is new or not, if new then place it in `position` and increment the `position` else continue.\n\n# Code\n```\nclass Solution {\npublic:\n int removeDuplicates(vector<int>& arr) {\n int n = size(arr);\n int position = 0;\n int currValue = INT_MIN;\n for(int i=0;i<n;i++){\n\n // if current value and arr[i] is not same\n // place it in position \n\n if(currValue!=arr[i]){\n \n currValue= arr[i];\n arr[position++] = currValue;\n }\n else{\n continue;\n }\n }\n return position;\n }\n};\n```\n#### Please UPVOTE if you liked the solution
2,520
Remove Duplicates from Sorted Array
remove-duplicates-from-sorted-array
Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements. Return k after placing the final result in the first k slots of nums. Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory. Custom Judge: The judge will test your solution with the following code: If all assertions pass, then your solution will be accepted.
Array,Two Pointers
Easy
In this problem, the key point to focus on is the input array being sorted. As far as duplicate elements are concerned, what is their positioning in the array when the given array is sorted? Look at the image above for the answer. If we know the position of one of the elements, do we also know the positioning of all the duplicate elements? We need to modify the array in-place and the size of the final array would potentially be smaller than the size of the input array. So, we ought to use a two-pointer approach here. One, that would keep track of the current element in the original array and another one for just the unique elements. Essentially, once an element is encountered, you simply need to bypass its duplicates and move on to the next unique element.
19,496
86
# 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)$$ -->O(N)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->O(1)\n\n![Screenshot_20230205_171246.png]()\n\n# Code\n```\npublic int removeDuplicates(int[] nums) {\n \n int newIndex = 1; // Start with index 1 because the first element is already in place\n\n for (int i = 0; i < nums.length - 1; i++) {\n\n if (nums[i] < nums[i+1]) { // If the current element is less than the next element\n \n nums[newIndex] = nums[i+1]; // Move the next element to the new index\n newIndex++; // Increment the new index\n }\n }\n return newIndex; // Return the length of the new subarray\n\n\n\n---\nSecond Approach (here we are using extra space for this space complexity will be O(N))\n\nclass Solution {\n public int removeDuplicates(int[] nums) {\n\n //Insert all array element in the Set. \n //Set does not allow duplicates and sets like LinkedHashSet maintains the order of insertion so it will remove duplicates and elements will be printed in the same order in which it is inserted\n\n LinkedHashSet<Integer> set = new LinkedHashSet<>();\n\n for(int i = 0; i < nums.length; i++){\n set.add(nums[i]);\n }\n //copy unique element back to array\n int i = 0;\n\n for(int ele:set){\n nums[i++] = ele;\n }\n return set.size();\n }\n}\n```
2,522
Remove Duplicates from Sorted Array
remove-duplicates-from-sorted-array
Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements. Return k after placing the final result in the first k slots of nums. Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory. Custom Judge: The judge will test your solution with the following code: If all assertions pass, then your solution will be accepted.
Array,Two Pointers
Easy
In this problem, the key point to focus on is the input array being sorted. As far as duplicate elements are concerned, what is their positioning in the array when the given array is sorted? Look at the image above for the answer. If we know the position of one of the elements, do we also know the positioning of all the duplicate elements? We need to modify the array in-place and the size of the final array would potentially be smaller than the size of the input array. So, we ought to use a two-pointer approach here. One, that would keep track of the current element in the original array and another one for just the unique elements. Essentially, once an element is encountered, you simply need to bypass its duplicates and move on to the next unique element.
18,480
121
```\n\tint k=1;\n\tfor(int i=1; i<nums.size(); i++) \n\t\tif(nums[i]!=nums[i-1]) nums[k++] = nums[i]; \n\treturn k;\n```
2,525
Remove Duplicates from Sorted Array
remove-duplicates-from-sorted-array
Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements. Return k after placing the final result in the first k slots of nums. Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory. Custom Judge: The judge will test your solution with the following code: If all assertions pass, then your solution will be accepted.
Array,Two Pointers
Easy
In this problem, the key point to focus on is the input array being sorted. As far as duplicate elements are concerned, what is their positioning in the array when the given array is sorted? Look at the image above for the answer. If we know the position of one of the elements, do we also know the positioning of all the duplicate elements? We need to modify the array in-place and the size of the final array would potentially be smaller than the size of the input array. So, we ought to use a two-pointer approach here. One, that would keep track of the current element in the original array and another one for just the unique elements. Essentially, once an element is encountered, you simply need to bypass its duplicates and move on to the next unique element.
1,361
5
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n- Just take two pointers, for comparing and updating when get un-similar elements\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- take two pointer repeat, nonRepeat.\n- nonRepeat will start from 0, and repeat starts from 1.\n- if both are same element increment the repeat pointer.\n- if different, increment nonRepeat and put the value of repeat.\n- At last retrun nonRepeat+1. (initially index started from 0)\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```\nclass Solution {\npublic:\n int removeDuplicates(vector<int>& nums) {\n // array-sorted-non-decreasing order\n // in-place, elements apper only once\n // relative order should be same\n int nonRepeat=0;\n for(int repeat=1; repeat<nums.size(); repeat++){\n if(nums[nonRepeat] != nums[repeat]){\n nonRepeat++;\n nums[nonRepeat] = nums[repeat];\n }\n }\n return nonRepeat+1;\n }\n};\n```
2,536
Remove Duplicates from Sorted Array
remove-duplicates-from-sorted-array
Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements. Return k after placing the final result in the first k slots of nums. Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory. Custom Judge: The judge will test your solution with the following code: If all assertions pass, then your solution will be accepted.
Array,Two Pointers
Easy
In this problem, the key point to focus on is the input array being sorted. As far as duplicate elements are concerned, what is their positioning in the array when the given array is sorted? Look at the image above for the answer. If we know the position of one of the elements, do we also know the positioning of all the duplicate elements? We need to modify the array in-place and the size of the final array would potentially be smaller than the size of the input array. So, we ought to use a two-pointer approach here. One, that would keep track of the current element in the original array and another one for just the unique elements. Essentially, once an element is encountered, you simply need to bypass its duplicates and move on to the next unique element.
23,353
69
# Intuition:\nThe problem requires us to remove duplicate elements from a sorted array, i.e., we need to keep only one copy of each element in the array. Since the array is sorted, all duplicate elements will be adjacent to each other, so we can easily remove them by shifting the subsequent elements of the array to the left.\n\n# Approach:\nWe can use two pointers i and j, where i points to the last unique element found so far, and j points to the current element being examined. If nums[i] and nums[j] are equal, we just increment j. Otherwise, we increment i and copy nums[j] to nums[i]. At the end, we return i+1, which represents the length of the modified array.\n\n# Complexity:\n- Time complexity: Since we only traverse the array once, the time complexity of the algorithm is O(n).\n- Space complexity: The algorithm uses constant extra space, so the space complexity is O(1).\n\n# C++\n```\nclass Solution {\npublic:\n int removeDuplicates(vector<int>& nums) {\n int i = 0;\n for (int j = 1; j < nums.size(); j++) {\n if (nums[i] != nums[j]) {\n i++;\n nums[i] = nums[j];\n }\n }\n return i + 1;\n }\n};\n```\n# JavaScript\n```\n/**\n * @param {number[]} nums\n * @return {number}\n */\nvar removeDuplicates = function(nums) {\n let i = 0;\n for (let j = 1; j < nums.length; j++) {\n if (nums[i] !== nums[j]) {\n i++;\n nums[i] = nums[j];\n }\n }\n return i + 1;\n}\n\n```\n# Java\n```\nclass Solution {\n public int removeDuplicates(int[] nums) {\n int i = 0;\n for (int j = 1; j < nums.length; j++) {\n if (nums[i] != nums[j]) {\n i++;\n nums[i] = nums[j];\n }\n }\n return i + 1;\n }\n}\n\n```\n# Python\n```\nclass Solution(object):\n def removeDuplicates(self, nums):\n i = 0\n for j in range(1, len(nums)):\n if nums[i] != nums[j]:\n i += 1\n nums[i] = nums[j]\n return i + 1\n\n```\n\n**THANK YOU**
2,539
Remove Duplicates from Sorted Array
remove-duplicates-from-sorted-array
Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements. Return k after placing the final result in the first k slots of nums. Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory. Custom Judge: The judge will test your solution with the following code: If all assertions pass, then your solution will be accepted.
Array,Two Pointers
Easy
In this problem, the key point to focus on is the input array being sorted. As far as duplicate elements are concerned, what is their positioning in the array when the given array is sorted? Look at the image above for the answer. If we know the position of one of the elements, do we also know the positioning of all the duplicate elements? We need to modify the array in-place and the size of the final array would potentially be smaller than the size of the input array. So, we ought to use a two-pointer approach here. One, that would keep track of the current element in the original array and another one for just the unique elements. Essentially, once an element is encountered, you simply need to bypass its duplicates and move on to the next unique element.
1,189
5
# 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```\nclass Solution {\npublic:\n int removeDuplicates(vector<int>& nums) {\n int ans=1,j=1;\n for(int i=1;i<nums.size();i++)\n {\n if(nums[i]!=nums[i-1])\n {\n nums[j]=nums[i];\n j++;\n }\n }\n // sort(nums.begin(),nums.end());\n return j;\n\n\n }\n};\n```
2,540
Remove Duplicates from Sorted Array
remove-duplicates-from-sorted-array
Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements. Return k after placing the final result in the first k slots of nums. Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory. Custom Judge: The judge will test your solution with the following code: If all assertions pass, then your solution will be accepted.
Array,Two Pointers
Easy
In this problem, the key point to focus on is the input array being sorted. As far as duplicate elements are concerned, what is their positioning in the array when the given array is sorted? Look at the image above for the answer. If we know the position of one of the elements, do we also know the positioning of all the duplicate elements? We need to modify the array in-place and the size of the final array would potentially be smaller than the size of the input array. So, we ought to use a two-pointer approach here. One, that would keep track of the current element in the original array and another one for just the unique elements. Essentially, once an element is encountered, you simply need to bypass its duplicates and move on to the next unique element.
107,413
924
int count = 0;\n for(int i = 1; i < n; i++){\n if(A[i] == A[i-1]) count++;\n else A[i-count] = A[i];\n }\n return n-count;
2,542
Remove Duplicates from Sorted Array
remove-duplicates-from-sorted-array
Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements. Return k after placing the final result in the first k slots of nums. Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory. Custom Judge: The judge will test your solution with the following code: If all assertions pass, then your solution will be accepted.
Array,Two Pointers
Easy
In this problem, the key point to focus on is the input array being sorted. As far as duplicate elements are concerned, what is their positioning in the array when the given array is sorted? Look at the image above for the answer. If we know the position of one of the elements, do we also know the positioning of all the duplicate elements? We need to modify the array in-place and the size of the final array would potentially be smaller than the size of the input array. So, we ought to use a two-pointer approach here. One, that would keep track of the current element in the original array and another one for just the unique elements. Essentially, once an element is encountered, you simply need to bypass its duplicates and move on to the next unique element.
2,462
6
The Objective of the problem is to move all the non duplicates to the front of the Array\nGiving that the Array is on Ascending order, taking it to the advantage to solve the problem\n\nUsing two pointer algorithm\nWhere pointer\n```x``` - keeps track of **next** non duplicate to handle \n```y``` - runs throught the array in search of next non duplicate to replace in place of pointer ```x```\n\nsince its an ascending array, the search criteria is number should be greater than the previous non duplicate(```x-1```)\n\nOnce we found the next non duplicate number replace in place of ```x``` and continue the search until array ends\n\nReturn ```x``` though it is incremented at the end, since we start ```x``` pointer from 1 considering the index 0 contains the first non duplicate number and array size is minimum 1.\n\n```class Solution {\n public int removeDuplicates(int[] nums) {\n \n int x=1;\n \n for(int y=x ; y < nums.length; y++)\n {\n if(nums[y] > nums[x-1])\n {\n nums[x++]=nums[y];\n }\n }\n return x;\n }\n}
2,543
Remove Duplicates from Sorted Array
remove-duplicates-from-sorted-array
Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements. Return k after placing the final result in the first k slots of nums. Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory. Custom Judge: The judge will test your solution with the following code: If all assertions pass, then your solution will be accepted.
Array,Two Pointers
Easy
In this problem, the key point to focus on is the input array being sorted. As far as duplicate elements are concerned, what is their positioning in the array when the given array is sorted? Look at the image above for the answer. If we know the position of one of the elements, do we also know the positioning of all the duplicate elements? We need to modify the array in-place and the size of the final array would potentially be smaller than the size of the input array. So, we ought to use a two-pointer approach here. One, that would keep track of the current element in the original array and another one for just the unique elements. Essentially, once an element is encountered, you simply need to bypass its duplicates and move on to the next unique element.
2,215
14
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIts basically a easy problem you can solve this problem with implementing array. \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n-> First of all take an integer with initialization 1.\n-> traverse the vector or array from 1 to end.\n-> if i-1th element is not equal to the ith element \nthen put ith element to the initialized int position.\n-> increment the initialized element.\n-> After ending the loop return the int number.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n)\n# Code\n```\nclass Solution {\npublic:\n int removeDuplicates(vector<int>& nums) {\n int insert=1;\n for(int i=1;i<nums.size();i++){\n if(nums[i-1]!=nums[i]){\n nums[insert]=nums[i];\n insert++;\n }\n }\n return insert;\n \n }\n};\n```
2,544
Remove Duplicates from Sorted Array
remove-duplicates-from-sorted-array
Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements. Return k after placing the final result in the first k slots of nums. Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory. Custom Judge: The judge will test your solution with the following code: If all assertions pass, then your solution will be accepted.
Array,Two Pointers
Easy
In this problem, the key point to focus on is the input array being sorted. As far as duplicate elements are concerned, what is their positioning in the array when the given array is sorted? Look at the image above for the answer. If we know the position of one of the elements, do we also know the positioning of all the duplicate elements? We need to modify the array in-place and the size of the final array would potentially be smaller than the size of the input array. So, we ought to use a two-pointer approach here. One, that would keep track of the current element in the original array and another one for just the unique elements. Essentially, once an element is encountered, you simply need to bypass its duplicates and move on to the next unique element.
22,240
222
**Two pointer Approach** \n**Time Complexity - O(N)**\n**Space Complexity - O(1)**\n\nThe problem has asked to do inplace so we need to modify the given nums vector only \n```\nclass Solution {\npublic:\n int removeDuplicates(vector<int>& nums) {\n if(nums.size() == 0) return 0;\n int left = 0;\n for(int right =1; right< nums.size(); right++){\n if(nums[left] != nums[right])\n left++;\n nums[left] = nums[right];\n }\n return left+1;\n }\n};\n```\n**Please upvote if you like the solution**\n**comment if have doubts**
2,546
Remove Duplicates from Sorted Array
remove-duplicates-from-sorted-array
Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements. Return k after placing the final result in the first k slots of nums. Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory. Custom Judge: The judge will test your solution with the following code: If all assertions pass, then your solution will be accepted.
Array,Two Pointers
Easy
In this problem, the key point to focus on is the input array being sorted. As far as duplicate elements are concerned, what is their positioning in the array when the given array is sorted? Look at the image above for the answer. If we know the position of one of the elements, do we also know the positioning of all the duplicate elements? We need to modify the array in-place and the size of the final array would potentially be smaller than the size of the input array. So, we ought to use a two-pointer approach here. One, that would keep track of the current element in the original array and another one for just the unique elements. Essentially, once an element is encountered, you simply need to bypass its duplicates and move on to the next unique element.
815
5
\n# Code\n```\nclass Solution {\npublic:\n int removeDuplicates(vector<int>& nums) {\n if(nums.size()<=1) return nums.size();\n int position=1;\n for(int i=1;i<nums.size();++i){\n if(nums[i]!=nums[position-1]){\n nums[position]=nums[i];\n position++;\n }\n }\n return position;\n }\n};\n```
2,547
Remove Duplicates from Sorted Array
remove-duplicates-from-sorted-array
Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements. Return k after placing the final result in the first k slots of nums. Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory. Custom Judge: The judge will test your solution with the following code: If all assertions pass, then your solution will be accepted.
Array,Two Pointers
Easy
In this problem, the key point to focus on is the input array being sorted. As far as duplicate elements are concerned, what is their positioning in the array when the given array is sorted? Look at the image above for the answer. If we know the position of one of the elements, do we also know the positioning of all the duplicate elements? We need to modify the array in-place and the size of the final array would potentially be smaller than the size of the input array. So, we ought to use a two-pointer approach here. One, that would keep track of the current element in the original array and another one for just the unique elements. Essentially, once an element is encountered, you simply need to bypass its duplicates and move on to the next unique element.
1,115
18
# Intuition\nMy initial thoughts on this problem involve finding an optimized solution to remove duplicates from a sorted array.\n\n# Approach\nThe chosen approach utilizes a two-pointer technique to efficiently remove duplicates from the sorted array `nums`. The two pointers, `i` and `j`, are initialized to 0 and 1 respectively. \n\nThe algorithm proceeds as follows:\n1. Iterate through the array from index 1 to the end:\n - Compare the element at position `i` with the element at position `j-1` (previous distinct element).\n - If they are not equal, it means a new distinct element is found.\n - Increment the pointer `j` and assign the element at position `i` to position `j`.\n2. After completing the iteration, the value of `j` represents the index of the last distinct element in the array. Adding 1 to `j` gives the count of distinct elements.\n\nThe algorithm effectively removes duplicates from the sorted array while maintaining the relative order of the elements.\n\n# Complexity\n- Time complexity: O(n)\n The algorithm iterates through the array once, performing constant-time operations at each step.\n\n- Space complexity: O(1)\n The algorithm utilizes a constant amount of additional memory space for variables, ensuring that the space complexity remains constant.\n\n\n# Code\n```\nclass Solution {\n public int removeDuplicates(int[] nums) {\n\n int j = 0;\n \n for (int i = 1; i < nums.length; i++) {\n if (nums[i] != nums[j]) {\n j++;\n nums[j] = nums[i];\n }\n }\n \n return j + 1;\n \n }\n}\n```\n![c0504eaf-5fb8-4a1d-a769-833262d1b86e_1674433591.3836212.webp]()\n
2,549
Remove Duplicates from Sorted Array
remove-duplicates-from-sorted-array
Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements. Return k after placing the final result in the first k slots of nums. Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory. Custom Judge: The judge will test your solution with the following code: If all assertions pass, then your solution will be accepted.
Array,Two Pointers
Easy
In this problem, the key point to focus on is the input array being sorted. As far as duplicate elements are concerned, what is their positioning in the array when the given array is sorted? Look at the image above for the answer. If we know the position of one of the elements, do we also know the positioning of all the duplicate elements? We need to modify the array in-place and the size of the final array would potentially be smaller than the size of the input array. So, we ought to use a two-pointer approach here. One, that would keep track of the current element in the original array and another one for just the unique elements. Essentially, once an element is encountered, you simply need to bypass its duplicates and move on to the next unique element.
1,266
18
\t int i=0;\n\t\t\tfor(int j=0;j<nums.size();j++){\n\t\t\t\tif (nums[i] != nums[j]) i++;\n\t\t\t\tnums[i] = nums[j];\n\t\t\t}\n\t\t\treturn i+1;\n\t\t
2,550
Remove Duplicates from Sorted Array
remove-duplicates-from-sorted-array
Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements. Return k after placing the final result in the first k slots of nums. Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory. Custom Judge: The judge will test your solution with the following code: If all assertions pass, then your solution will be accepted.
Array,Two Pointers
Easy
In this problem, the key point to focus on is the input array being sorted. As far as duplicate elements are concerned, what is their positioning in the array when the given array is sorted? Look at the image above for the answer. If we know the position of one of the elements, do we also know the positioning of all the duplicate elements? We need to modify the array in-place and the size of the final array would potentially be smaller than the size of the input array. So, we ought to use a two-pointer approach here. One, that would keep track of the current element in the original array and another one for just the unique elements. Essentially, once an element is encountered, you simply need to bypass its duplicates and move on to the next unique element.
4,188
30
Since the problem is asking us to remove duplicates **in place**, it seems like the only choice we have is to use a two-pointers approach. Also since the array is sorted, duplicates are grouped together in the array.\n(1) Using a pointer ```i``` to point to the index where the element will be replaced.\n(2) Using another pointer, ```j```, to go through the array and check if the jth element is the same as the j-1 element or not. \n(3) If ```nums[j]!=nums[j-1]```, we should replace nums[i] with nums[j] and move ```i``` forward by 1. This is because ```nums[j]``` is the first element without duplicates before it, and we should keep it in the results. \n\nIn the end, ```nums[:i]``` will be the array without any duplicates, so we just return ```i```. Note that ```i``` should start at 1 since ```nums[0]``` will always be there no matter what.\n\n```\nclass Solution:\n def removeDuplicates(self, nums: List[int]) -> int:\n i = 0\n for j in range(1,len(nums)):\n if nums[j] != nums[j-1]:\n nums[i] = nums[j-1]\n i += 1\n nums[i] = nums[-1]\n return i+1\n```\n\n**Upvote** if you like this post.\n\n**Connect with me on [LinkedIn]()** if you\'d like to discuss other related topics\n\nJust in case if you are working on **ML/DL 3D data-related projects** or are interested in the topic, please check out our project **[HERE]()**
2,551
Remove Duplicates from Sorted Array
remove-duplicates-from-sorted-array
Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements. Return k after placing the final result in the first k slots of nums. Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory. Custom Judge: The judge will test your solution with the following code: If all assertions pass, then your solution will be accepted.
Array,Two Pointers
Easy
In this problem, the key point to focus on is the input array being sorted. As far as duplicate elements are concerned, what is their positioning in the array when the given array is sorted? Look at the image above for the answer. If we know the position of one of the elements, do we also know the positioning of all the duplicate elements? We need to modify the array in-place and the size of the final array would potentially be smaller than the size of the input array. So, we ought to use a two-pointer approach here. One, that would keep track of the current element in the original array and another one for just the unique elements. Essentially, once an element is encountered, you simply need to bypass its duplicates and move on to the next unique element.
740
9
# 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# Code\n```\nclass Solution {\n public int removeDuplicates(int[] nums) {\n int k = 1;\n for (int i = 0; i < nums.length - 1; i++) {\n\n if (nums[i] < nums[i+1]) {\n\n nums[k] = nums[i+1];\n k++;\n }\n }\n\n return k;\n }\n}\n```\n## For additional problem-solving solutions, you can explore my repository on GitHub: [GitHub Repository]()\n\n![abcd1.jpeg]()\n
2,564
Remove Duplicates from Sorted Array
remove-duplicates-from-sorted-array
Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements. Return k after placing the final result in the first k slots of nums. Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory. Custom Judge: The judge will test your solution with the following code: If all assertions pass, then your solution will be accepted.
Array,Two Pointers
Easy
In this problem, the key point to focus on is the input array being sorted. As far as duplicate elements are concerned, what is their positioning in the array when the given array is sorted? Look at the image above for the answer. If we know the position of one of the elements, do we also know the positioning of all the duplicate elements? We need to modify the array in-place and the size of the final array would potentially be smaller than the size of the input array. So, we ought to use a two-pointer approach here. One, that would keep track of the current element in the original array and another one for just the unique elements. Essentially, once an element is encountered, you simply need to bypass its duplicates and move on to the next unique element.
2,581
10
# Intuition\nJust simply swap the duplicate element in the array to the end\n\n# Approach\nTraverse the array if there is any duplicate element with index position\n\n# Complexity\n- Time complexity:O(n)\n\n\n- Space complexity:O(1)\n\n# Code\n```\nclass Solution {\n public int removeDuplicates(int[] nums) {\n int j=0;\n for(int i=1;i<nums.length;i++){\n if(nums[i]!=nums[j]){\n nums[j+1]=nums[i];\n j++;}\n }\n return j+1;\n }\n}\n```
2,566
Remove Duplicates from Sorted Array
remove-duplicates-from-sorted-array
Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements. Return k after placing the final result in the first k slots of nums. Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory. Custom Judge: The judge will test your solution with the following code: If all assertions pass, then your solution will be accepted.
Array,Two Pointers
Easy
In this problem, the key point to focus on is the input array being sorted. As far as duplicate elements are concerned, what is their positioning in the array when the given array is sorted? Look at the image above for the answer. If we know the position of one of the elements, do we also know the positioning of all the duplicate elements? We need to modify the array in-place and the size of the final array would potentially be smaller than the size of the input array. So, we ought to use a two-pointer approach here. One, that would keep track of the current element in the original array and another one for just the unique elements. Essentially, once an element is encountered, you simply need to bypass its duplicates and move on to the next unique element.
658
5
**Time complexity - O(n)\nSpace complexity - O(1)**\n```\nclass Solution {\npublic:\n int removeDuplicates(vector<int>& nums) {\n int left = 0;\n int right = 0;\n \n while(right < nums.size()) {\n if(nums[left] != nums[right]) {\n left++;\n nums[left] = nums[right];\n }\n right++;\n }\n \n return left+1;\n }\n};\n```\n\nSimplified solution -\n```\nclass Solution {\npublic:\n int removeDuplicates(vector<int>& nums) {\n int left = 0;\n \n for(int i=0;i<nums.size();i++) {\n if(nums[left] != nums[i]) {\n left++;\n nums[left] = nums[i];\n }\n }\n \n return left+1;\n }\n};\n```\n\n**Like the solution?\nPlease upvote \u30C4**\n\nIf you can\'t understand any step/point, feel free to comment.\nHappy to help.
2,568
Remove Duplicates from Sorted Array
remove-duplicates-from-sorted-array
Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements. Return k after placing the final result in the first k slots of nums. Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory. Custom Judge: The judge will test your solution with the following code: If all assertions pass, then your solution will be accepted.
Array,Two Pointers
Easy
In this problem, the key point to focus on is the input array being sorted. As far as duplicate elements are concerned, what is their positioning in the array when the given array is sorted? Look at the image above for the answer. If we know the position of one of the elements, do we also know the positioning of all the duplicate elements? We need to modify the array in-place and the size of the final array would potentially be smaller than the size of the input array. So, we ought to use a two-pointer approach here. One, that would keep track of the current element in the original array and another one for just the unique elements. Essentially, once an element is encountered, you simply need to bypass its duplicates and move on to the next unique element.
3,219
20
\uD83D\uDC69 If you like this solution, please click UpVote button. If you have any question, feel free write as a comment. Thanks :)\n\n```\nclass Solution {\n public int removeDuplicates(int[] nums) {\n\t\tif (nums.length == 0 || nums.length == 1) {\n\t\t\treturn nums.length;\n\t\t}\n\t\tint j = 0;\n\t\tfor (int i = 0; i < nums.length - 1; i++) {\n\t\t\tif (nums[i] != nums[i + 1]) {\n\t\t\t\tnums[j++] = nums[i];\n\t\t\t}\n\t\t}\n\t\tnums[j++] = nums[nums.length - 1];\n\t\treturn j;\n\t}\n}
2,569
Remove Duplicates from Sorted Array
remove-duplicates-from-sorted-array
Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements. Return k after placing the final result in the first k slots of nums. Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory. Custom Judge: The judge will test your solution with the following code: If all assertions pass, then your solution will be accepted.
Array,Two Pointers
Easy
In this problem, the key point to focus on is the input array being sorted. As far as duplicate elements are concerned, what is their positioning in the array when the given array is sorted? Look at the image above for the answer. If we know the position of one of the elements, do we also know the positioning of all the duplicate elements? We need to modify the array in-place and the size of the final array would potentially be smaller than the size of the input array. So, we ought to use a two-pointer approach here. One, that would keep track of the current element in the original array and another one for just the unique elements. Essentially, once an element is encountered, you simply need to bypass its duplicates and move on to the next unique element.
1,465
5
<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nIts very easy if you know how to play with arrays and loops.\nFor solving this problem I have used 2 pointers.\n- Take a **variable i = 0;**\n- Use a for loop by using a **variable \u2018j\u2019 from 1 to length of the array.**\n- **If arr[j] != arr[i], increase \u2018i\u2019 and update arr[i] == arr[j].**\n- After completion of the loop return i+1, i.e size of the array of unique elements.\n\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\nO(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\nO(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int removeDuplicates(int[] nums) {\n int i = 0,size=nums.length;\n for( int j=1; j<size;j++){\n if(nums[j]!=nums[i]){\n nums[i+1]=nums[j];\n i++;\n }\n }\n return i+1;\n }\n}\n```
2,570
Remove Duplicates from Sorted Array
remove-duplicates-from-sorted-array
Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements. Return k after placing the final result in the first k slots of nums. Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory. Custom Judge: The judge will test your solution with the following code: If all assertions pass, then your solution will be accepted.
Array,Two Pointers
Easy
In this problem, the key point to focus on is the input array being sorted. As far as duplicate elements are concerned, what is their positioning in the array when the given array is sorted? Look at the image above for the answer. If we know the position of one of the elements, do we also know the positioning of all the duplicate elements? We need to modify the array in-place and the size of the final array would potentially be smaller than the size of the input array. So, we ought to use a two-pointer approach here. One, that would keep track of the current element in the original array and another one for just the unique elements. Essentially, once an element is encountered, you simply need to bypass its duplicates and move on to the next unique element.
946
6
```\nclass Solution {\n public int removeDuplicates(int[] nums) {\n int j=1;\n int count = 0;\n for(int i = 0;i<nums.length-1;i++){\n if(nums[i] != nums[j]){\n count++;\n nums[count] = nums[j];\n }\n j++;\n }\n return count+1;\n }\n}\n```
2,572
Remove Duplicates from Sorted Array
remove-duplicates-from-sorted-array
Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements. Return k after placing the final result in the first k slots of nums. Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory. Custom Judge: The judge will test your solution with the following code: If all assertions pass, then your solution will be accepted.
Array,Two Pointers
Easy
In this problem, the key point to focus on is the input array being sorted. As far as duplicate elements are concerned, what is their positioning in the array when the given array is sorted? Look at the image above for the answer. If we know the position of one of the elements, do we also know the positioning of all the duplicate elements? We need to modify the array in-place and the size of the final array would potentially be smaller than the size of the input array. So, we ought to use a two-pointer approach here. One, that would keep track of the current element in the original array and another one for just the unique elements. Essentially, once an element is encountered, you simply need to bypass its duplicates and move on to the next unique element.
9,615
18
# Intuition\nMove elements to their desired index.\nFind non-repetitive elements and move them to their desired index.\n\n# Approach\nThe provided Java code is an implementation of a function that removes duplicates from a sorted array in place. It uses two pointers to achieve this task efficiently. Here\'s how the code works:\n\n1. `int p = 0;`: Initialize a pointer `p` to 0. This pointer will keep track of the position in the array where the unique elements are stored.\n\n2. The code enters a loop that iterates through the `nums` array starting from the second element (index 1).\n\n3. `if (nums[p] != nums[i]) { ... }`: It checks if the element at the current position `p` is different from the element at index `i`.\n\n - If they are different, it means a new unique element is found. In this case, the code updates the next position (at `p + 1`) in the array `nums` with the new unique element `nums[i]`.\n\n - Then, it increments the pointer `p` to point to the next available position for the next unique element.\n\n4. The loop continues until all elements are processed, and unique elements are moved to the front of the array. The variable `p` keeps track of the number of unique elements.\n\n5. Finally, the function returns `p + 1`, which is the count of unique elements in the modified `nums` array.\n\nThis algorithm works efficiently for removing duplicates from a sorted array in-place, and it has a time complexity of O(n), where n is the number of elements in the input array `nums`. The space complexity is O(1) because it modifies the array in place without using any additional data structures.\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution {\n public int removeDuplicates(int[] nums) {\n int p = 0;\n for(int i = 1 ; i < nums.length ; i++){\n if(nums[p] != nums[i]){\n nums[p+1] = nums[i];\n p++;\n }\n }\n return p + 1;\n }\n}\n```
2,578
Remove Duplicates from Sorted Array
remove-duplicates-from-sorted-array
Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements. Return k after placing the final result in the first k slots of nums. Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory. Custom Judge: The judge will test your solution with the following code: If all assertions pass, then your solution will be accepted.
Array,Two Pointers
Easy
In this problem, the key point to focus on is the input array being sorted. As far as duplicate elements are concerned, what is their positioning in the array when the given array is sorted? Look at the image above for the answer. If we know the position of one of the elements, do we also know the positioning of all the duplicate elements? We need to modify the array in-place and the size of the final array would potentially be smaller than the size of the input array. So, we ought to use a two-pointer approach here. One, that would keep track of the current element in the original array and another one for just the unique elements. Essentially, once an element is encountered, you simply need to bypass its duplicates and move on to the next unique element.
1,480
6
# Brute Force Approach -->\n# Approach\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe know the set only keeps the unique elements, So we will insert all the given elements in a set, then we will put them in the array from begining and will increase the index . At last we can return Index, Because it is the number of unique values. \n# Brute force code\n```\nset<int>st;\nfor(int i=0;i<nums.size();i++){\n st.insert(nums[i]);\n}\nint idx=0;\nfor(auto it : st){\n nums[idx]=it;\n idx++;\n}\nreturn idx;\n``` \n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n##### $$O(nlogn + n)$$ (insert() takes logn time)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n##### $$O(n)$$ (size of set might be \'n\')\n# Optimal Approach -->\nWe will use two pointer approach , where at first \'i\' pointer will be at first position ans \'j\' pointer will be at second position then we will compare both values as they are equal or not. If the values are not equal then \n```\nnums[i+1]=nums[j];\ni++\n```\n\n# Optimal Code\n```\nclass Solution {\npublic:\n int removeDuplicates(vector<int>& nums) {\n int i=0;\n for(int j=1;j<nums.size();j++){\n if(nums[i]!=nums[j]){\n nums[i+1]=nums[j];\n i++;\n }\n }\n return i+1;\n }\n};\n```\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n##### $$O(n)$$ (A loop is running from \'0\' to \'n\')\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n##### $$O(1)$$ \n\n# Please Upvote if it was helpful \u2B06\uFE0F
2,579
Remove Duplicates from Sorted Array
remove-duplicates-from-sorted-array
Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements. Return k after placing the final result in the first k slots of nums. Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory. Custom Judge: The judge will test your solution with the following code: If all assertions pass, then your solution will be accepted.
Array,Two Pointers
Easy
In this problem, the key point to focus on is the input array being sorted. As far as duplicate elements are concerned, what is their positioning in the array when the given array is sorted? Look at the image above for the answer. If we know the position of one of the elements, do we also know the positioning of all the duplicate elements? We need to modify the array in-place and the size of the final array would potentially be smaller than the size of the input array. So, we ought to use a two-pointer approach here. One, that would keep track of the current element in the original array and another one for just the unique elements. Essentially, once an element is encountered, you simply need to bypass its duplicates and move on to the next unique element.
53,959
294
Given a sorted array and we need to return the length of the unique elements instead of the entire array. There is no need to delete the duplicate elements also. \n* Since, our first element is already present at index 0 (**it is a unique element**), we quickly run a for loop for the entire array to scan for unique elements.\n* If the current element and the next element are the same, then we just keep on going till we find a different element\n* Once we find a different element, it is inserted at index 1, because, index 0 is taken by the first unique element. \n* Once this is done, the same scanning is done to find out the next unique element and this element is to be inserted at index 2. This process continues until we are done with unique elements.\n* **We use a variable (x = 1) which is incremented to the next index whenever we find a unique element and we insert this element at its corresponding index**.\n```\nx = 1\nfor i in range(len(nums)-1):\n\tif(nums[i]!=nums[i+1]):\n\t\tnums[x] = nums[i+1]\n\t\tx+=1\nreturn(x)\n```
2,581
Remove Duplicates from Sorted Array
remove-duplicates-from-sorted-array
Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements. Return k after placing the final result in the first k slots of nums. Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory. Custom Judge: The judge will test your solution with the following code: If all assertions pass, then your solution will be accepted.
Array,Two Pointers
Easy
In this problem, the key point to focus on is the input array being sorted. As far as duplicate elements are concerned, what is their positioning in the array when the given array is sorted? Look at the image above for the answer. If we know the position of one of the elements, do we also know the positioning of all the duplicate elements? We need to modify the array in-place and the size of the final array would potentially be smaller than the size of the input array. So, we ought to use a two-pointer approach here. One, that would keep track of the current element in the original array and another one for just the unique elements. Essentially, once an element is encountered, you simply need to bypass its duplicates and move on to the next unique element.
2,141
16
```\nclass Solution {\n public int removeDuplicates(int[] nums) {\n int ptr = 1;\n for(int i = 0 ; i < nums.length -1 ; i++ ){\n if(nums[i] != nums[i + 1]){ //When we get unique No.\n nums[ptr] = nums[i+1]; //update previous pointer with new element\n ptr++;\n }\n }\n return ptr ;\n }\n}\n```\n\n**Please Upvote**
2,591
Remove Duplicates from Sorted Array
remove-duplicates-from-sorted-array
Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements. Return k after placing the final result in the first k slots of nums. Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory. Custom Judge: The judge will test your solution with the following code: If all assertions pass, then your solution will be accepted.
Array,Two Pointers
Easy
In this problem, the key point to focus on is the input array being sorted. As far as duplicate elements are concerned, what is their positioning in the array when the given array is sorted? Look at the image above for the answer. If we know the position of one of the elements, do we also know the positioning of all the duplicate elements? We need to modify the array in-place and the size of the final array would potentially be smaller than the size of the input array. So, we ought to use a two-pointer approach here. One, that would keep track of the current element in the original array and another one for just the unique elements. Essentially, once an element is encountered, you simply need to bypass its duplicates and move on to the next unique element.
668
6
```\nclass Solution {\npublic:\n int removeDuplicates(vector<int>& nums) {\n \n \n int k=1;\n for(int i=1;i<nums.size();++i)\n {\n if(nums[i]!=nums[i-1])\n {\n nums[k]=nums[i];\n k++;\n }\n }\n return k;\n }\n};\n```\n//comment your suggestion
2,598
Remove Duplicates from Sorted Array
remove-duplicates-from-sorted-array
Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements. Return k after placing the final result in the first k slots of nums. Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory. Custom Judge: The judge will test your solution with the following code: If all assertions pass, then your solution will be accepted.
Array,Two Pointers
Easy
In this problem, the key point to focus on is the input array being sorted. As far as duplicate elements are concerned, what is their positioning in the array when the given array is sorted? Look at the image above for the answer. If we know the position of one of the elements, do we also know the positioning of all the duplicate elements? We need to modify the array in-place and the size of the final array would potentially be smaller than the size of the input array. So, we ought to use a two-pointer approach here. One, that would keep track of the current element in the original array and another one for just the unique elements. Essentially, once an element is encountered, you simply need to bypass its duplicates and move on to the next unique element.
7,943
8
```\nclass Solution:\n def removeDuplicates(self, nums: List[int]) -> int:\n if len(nums)==1:\n return 1\n x=nums[0]\n i=0\n while i<len(nums)-1:\n if x==nums[1+i]:\n del nums[1+i]\n else:\n x=nums[1+i]\n i+=1\n return i+1\n```
2,599
Remove Element
remove-element
Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The relative order of the elements may be changed. Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements. Return k after placing the final result in the first k slots of nums. Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory. Custom Judge: The judge will test your solution with the following code: If all assertions pass, then your solution will be accepted.
Array,Two Pointers
Easy
The problem statement clearly asks us to modify the array in-place and it also says that the element beyond the new length of the array can be anything. Given an element, we need to remove all the occurrences of it from the array. We don't technically need to remove that element per-say, right? We can move all the occurrences of this element to the end of the array. Use two pointers! Yet another direction of thought is to consider the elements to be removed as non-existent. In a single pass, if we keep copying the visible elements in-place, that should also solve this problem for us.
142,844
1,020
# Intuition\r\n<!-- Describe your first thoughts on how to solve this problem. -->\r\nThe intuition behind this solution is to iterate through the array and keep track of two pointers: `index` and `i`. The `index` pointer represents the position where the next non-target element should be placed, while the `i` pointer iterates through the array elements. By overwriting the target elements with non-target elements, the solution effectively removes all occurrences of the target value from the array.\r\n# Approach\r\n<!-- Describe your approach to solving the problem. -->\r\n1. Initialize `index` to 0, which represents the current position for the next non-target element.\r\n2. Iterate through each element of the input array using the `i` pointer.\r\n3. For each element `nums[i]`, check if it is equal to the target value.\r\n - If `nums[i]` is not equal to `val`, it means it is a non-target element.\r\n - Set `nums[index]` to `nums[i]` to store the non-target element at the current `index` position.\r\n - Increment `index` by 1 to move to the next position for the next non-target element.\r\n4. Continue this process until all elements in the array have been processed.\r\n5. Finally, return the value of `index`, which represents the length of the modified array.\r\n\r\n# Complexity\r\n- Time complexity:\r\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\r\n$$ O(n) $$\r\n- Space complexity:\r\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\r\n$$ O(1) $$\r\n\r\n# Code\r\n```C++ []\r\nclass Solution {\r\npublic:\r\n int removeElement(vector<int>& nums, int val) {\r\n int index = 0;\r\n for(int i = 0; i< nums.size(); i++){\r\n if(nums[i] != val){\r\n nums[index] = nums[i];\r\n index++;\r\n }\r\n }\r\n return index;\r\n }\r\n};\r\n```\r\n```Java []\r\nclass Solution {\r\n public int removeElement(int[] nums, int val) {\r\n int index = 0;\r\n for (int i = 0; i < nums.length; i++) {\r\n if (nums[i] != val) {\r\n nums[index] = nums[i];\r\n index++;\r\n }\r\n }\r\n return index;\r\n }\r\n}\r\n```\r\n```Python3 []\r\nclass Solution:\r\n def removeElement(self, nums: List[int], val: int) -> int:\r\n index = 0\r\n for i in range(len(nums)):\r\n if nums[i] != val:\r\n nums[index] = nums[i]\r\n index += 1\r\n return index\r\n```\r\n\r\n![CUTE_CAT.png]()\r\n\r\n\r\n**If you are a beginner solve these problems which makes concepts clear for future coding:**\r\n1. [Two Sum]()\r\n2. [Roman to Integer]()\r\n3. [Palindrome Number]()\r\n4. [Maximum Subarray]()\r\n5. [Remove Element]()\r\n6. [Contains Duplicate]()\r\n7. [Add Two Numbers]()\r\n8. [Majority Element]()\r\n9. [Remove Duplicates from Sorted Array]()\r\n10. **Practice them in a row for better understanding and please Upvote for more questions.**\r\n\r\n\r\n**If you found my solution helpful, I would greatly appreciate your upvote, as it would motivate me to continue sharing more solutions.**\r\n
2,600
Remove Element
remove-element
Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The relative order of the elements may be changed. Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements. Return k after placing the final result in the first k slots of nums. Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory. Custom Judge: The judge will test your solution with the following code: If all assertions pass, then your solution will be accepted.
Array,Two Pointers
Easy
The problem statement clearly asks us to modify the array in-place and it also says that the element beyond the new length of the array can be anything. Given an element, we need to remove all the occurrences of it from the array. We don't technically need to remove that element per-say, right? We can move all the occurrences of this element to the end of the array. Use two pointers! Yet another direction of thought is to consider the elements to be removed as non-existent. In a single pass, if we keep copying the visible elements in-place, that should also solve this problem for us.
70,446
379
# Approach\n- I am using Two pointers method\n- After shifting the val to the right side of the array.\n- Just return the value of k which is length of array excluding val.\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```\nclass Solution {\n public int removeElement(int[] nums, int val) {\n int i = 0;\n for (int j = 0; j < nums.length; j++) {\n if (nums[j] != val) {\n int temp = nums[i];\n nums[i] = nums[j];\n nums[j] = temp;\n i++;\n }\n }\n return i;\n }\n}\n```\n![please-upvote-and.jpg]()\n
2,602
Remove Element
remove-element
Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The relative order of the elements may be changed. Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements. Return k after placing the final result in the first k slots of nums. Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory. Custom Judge: The judge will test your solution with the following code: If all assertions pass, then your solution will be accepted.
Array,Two Pointers
Easy
The problem statement clearly asks us to modify the array in-place and it also says that the element beyond the new length of the array can be anything. Given an element, we need to remove all the occurrences of it from the array. We don't technically need to remove that element per-say, right? We can move all the occurrences of this element to the end of the array. Use two pointers! Yet another direction of thought is to consider the elements to be removed as non-existent. In a single pass, if we keep copying the visible elements in-place, that should also solve this problem for us.
912
12
\n\nOne way to do this is to check every element of `nums`, and if an element is equal to `val`, then we use the pop method to pop it off. This works, but the problem is that the pop method is very inefficient because if we pop an element near the start of the array, all the other elements have to be shifted back one spot. Each shift runs in O(n) time, and in the worst case, we\'d have to do n shifts, so this algorithm ends up running in O(n<sup>2</sup>) time.\n\nInstead, we can use a two pointer approach that overwrites the first `k` elements of the array, where `k` is the number of elements that are not equal to `val`. The index variable `i` keeps track of the next spot to overwrite in the array, and we use `x` to check the value of each element and compare it to `val`.\n\nIf an element is equal to `val`, we just move on and don\'t do anything. Basically, we keep searching until we find an element that is not equal to `val`. Once we do find an element not equal to `val`, we write it to the array at index `i`, then increment `i` so that it\'s ready to write at the next spot.\n\nAt the end, we can just return `i` since it has been incremented exactly once for each element found that is not equal to `val`.\n\n```\nclass Solution(object):\n def removeElement(self, nums, val):\n i = 0\n for x in nums:\n if x != val:\n nums[i] = x\n i += 1\n return i\n```
2,607
Remove Element
remove-element
Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The relative order of the elements may be changed. Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements. Return k after placing the final result in the first k slots of nums. Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory. Custom Judge: The judge will test your solution with the following code: If all assertions pass, then your solution will be accepted.
Array,Two Pointers
Easy
The problem statement clearly asks us to modify the array in-place and it also says that the element beyond the new length of the array can be anything. Given an element, we need to remove all the occurrences of it from the array. We don't technically need to remove that element per-say, right? We can move all the occurrences of this element to the end of the array. Use two pointers! Yet another direction of thought is to consider the elements to be removed as non-existent. In a single pass, if we keep copying the visible elements in-place, that should also solve this problem for us.
29,651
117
# 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# Code\n```\nclass Solution:\n def removeElement(self, nums: List[int], val: int) -> int:\n while val in nums:\n nums.remove(val)\n#please upvote me it would encourage me alot\n\n```
2,609
Remove Element
remove-element
Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The relative order of the elements may be changed. Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements. Return k after placing the final result in the first k slots of nums. Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory. Custom Judge: The judge will test your solution with the following code: If all assertions pass, then your solution will be accepted.
Array,Two Pointers
Easy
The problem statement clearly asks us to modify the array in-place and it also says that the element beyond the new length of the array can be anything. Given an element, we need to remove all the occurrences of it from the array. We don't technically need to remove that element per-say, right? We can move all the occurrences of this element to the end of the array. Use two pointers! Yet another direction of thought is to consider the elements to be removed as non-existent. In a single pass, if we keep copying the visible elements in-place, that should also solve this problem for us.
1,665
25
# Intuition\nThe problem at hand requires the removal of all instances of a specified value, `val`, from an integer array `nums`. My initial thoughts gravitate towards a straightforward approach that effectively eliminates the target value while maintaining the relative order of the remaining elements.\n\n# Approach\nThe chosen approach relies on a two-pointer technique to efficiently handle the task of removing elements equal to `val` from the array `nums`. The two pointers, `i` and `newLength`, serve the following purposes:\n- `i` traverses through the array to identify elements equal to `val`.\n- `newLength` keeps track of the length of the modified array, excluding elements equal to `val`.\n\nThe algorithm unfolds as follows:\n1. Initialize `newLength` to 0, indicating the initial length of the modified array.\n2. Iterate through the `nums` array with the pointer `i`:\n - If `nums[i]` is not equal to the target value `val`, it implies a non-target element:\n - Assign `nums[i]` to `nums[newLength]`, effectively overwriting any potential `val` occurrence with the non-target value.\n - Increment `newLength` to reflect the modified array\'s length.\n3. After the iteration concludes, `newLength` holds the length of the modified array with the target values removed.\n\nThe algorithm excels at efficiently removing all instances of the specified value while preserving the original relative order of the remaining elements.\n\n# Complexity\n- Time complexity: O(n)\n The algorithm traverses through the `nums` array once, performing constant-time operations at each step.\n\n- Space complexity: O(1)\n The algorithm utilizes a fixed amount of additional memory space for variables, ensuring a constant space complexity.\n\n\n# Code\n```\nclass Solution {\n public int removeElement(int[] nums, int val) {\n \n int newLength = 0 ; \n\n for (int i = 0; i < nums.length; i++) {\n \n if (nums[i] != val) {\n nums[newLength] = nums[i];\n newLength++;\n }\n }\n\n return newLength;\n \n }\n}\n```\n\n![c0504eaf-5fb8-4a1d-a769-833262d1b86e_1674433591.3836212.webp]()\n
2,610