L21. Reverse Nodes in K Group Size of LinkedList

  Рет қаралды 102,974

take U forward

take U forward

Күн бұрын

Пікірлер: 126
@udaypandey5659
@udaypandey5659 Жыл бұрын
This question solution was already given by striver in past, but this latest one is very clear and easily understandable. This is a very good thing about him that he always upgrades his art of teaching and his content as well.
@alessandrocamilleri1239
@alessandrocamilleri1239 10 ай бұрын
Yes. It is not about making a cookie cutter video to gain views. A lot of research goes in the production of these videos, mainly in planning the best and easiest approach for the viewer. The content is highly curated and the logic builds on preceeding videos. The man is a very good teacher who happens to know the subject really well.
@suhasherle7350
@suhasherle7350 17 күн бұрын
exactly, I found this solution better than the previous video
@venub8853
@venub8853 7 ай бұрын
What a fantastic explanation by breaking the problem into subparts!!!💥
@CrazyHunk14
@CrazyHunk14 7 ай бұрын
I was able to write almost the same code by myself thanks Striver!
@ayushidalal5488
@ayushidalal5488 18 күн бұрын
Got the approach even before watching this video, coded the recursive solution by myself and came back here to check how you did it, and it was exactly the same way!! So happy😊
@ankitsharda1131
@ankitsharda1131 10 ай бұрын
Superb Explanation!! Didn't understood in the first watch but got it while watching for the second time!!
@CodeWithSeenu
@CodeWithSeenu 6 күн бұрын
Great explanation 🔥... Additionally, I would like to highlight the following point if (kthNode == null){ if (prevLast != null) prevLast.next = temp; break; } Just use if (kthNode == null){ prevLast.next = temp; break; } "if (prevLast != null)" ---- This if condition is redundant and can be safely removed, as when len % k == 0 then ----> temp is null in the last loop and then ----> while (temp != NULL ) will exit the while loop when len % k !=0 then it comes to the above condition(to add the remaining nodes) and then "prevLast != null" will always be true
@vasanthdamera5896
@vasanthdamera5896 5 ай бұрын
just after listening once i had code the solution in one go and it executed perfectly.... great explanation by striver
@manishmahajan6094
@manishmahajan6094 3 ай бұрын
Marking my Day 31 of learning DSA. Thank you @striver for the best explanations !!!
@humanity7880
@humanity7880 Ай бұрын
Best video on this topic! watched 2 times and now the logic is crystal clear in my head
@DevilJim-p1s
@DevilJim-p1s Күн бұрын
I found the solution of this problem before that video 💪 thanks striver you're best teacher ❤
@iayushsharma
@iayushsharma 6 ай бұрын
You can also solve this question using recursion: Step 1: Base Case -> if LL is empty return null Step 2: Check do we even have k nodes to reverse if not you can return head(teh node itself). Step 3: Just reverse the first k group nodes and then leave everything on recursion. Step 4: return the head of the first LL that you have reversed. Below is the detailed code of c++: Code: ListNode* reverseKGroup(ListNode* head, int k) { // Recursive solution // Base Case if (head == nullptr) { return nullptr; } // step 1: Check if there are at least k nodes to reverse ListNode* temp = head; int count = 0; while (temp != nullptr && count < k) { temp = temp->next; count++; } // If there are fewer than k nodes left, return head without reversing if (count < k) { return head; } // Step 2 : reverse k nodes ListNode* prev = nullptr; temp = head; ListNode* next = nullptr; count = 0; while (temp != nullptr && count < k) { next = temp->next; temp->next = prev; prev = temp; temp = next; count++; } // recursive call; if (next != nullptr) { head->next = reverseKGroup(next, k); } // return return prev; } TC -> O(N) Sc -> O(N) -> recursive call stack memory
@salonisharma9709
@salonisharma9709 5 ай бұрын
thanku
@dhruvkushwaha9286
@dhruvkushwaha9286 3 ай бұрын
jdbc
@akshaychavan5511
@akshaychavan5511 6 ай бұрын
Loved it. I did it recursively as it was much easier for me to understand. class Solution: # returns first node and last node of the revered list def reverse(self, head): if head == None: return None prev = None current = head while current: nxt = current.next current.next = prev prev = current current = nxt return (prev, head) def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]: if not head: return head kBackup = k newHead = head start = head while head: if k==1: # kth node found newHead = head nextListStart = head.next head.next = None # break the link first, last = self.reverse(start) last.next = self.reverseKGroup(nextListStart, kBackup) # recursively call for remaining list k-=1 head = head.next return newHead
@brokegod5871
@brokegod5871 3 ай бұрын
You can just write the usual reverse LL code and call it recursively after handling the first one yourself, since each LL is doing the same work repeatedly ListNode* reverseKGroup(ListNode* head, int k) { ListNode* temp=head; for(int i = 0; i < k; i++) { if(temp == NULL) return head; temp = temp->next; } ListNode* curr=head; ListNode* prev=NULL; ListNode* next=NULL; int count=0; while(curr!=NULL && countnext; curr->next=prev; prev=curr; curr=next; count++; } if(next!=NULL){ head->next=reverseKGroup(curr,k); } return prev; } Do a dry run and you'll understand why prev was returned
@prabhjeetsingh6305
@prabhjeetsingh6305 2 ай бұрын
thanks. I got a headache looking at this question until I saw this approach.
@shashankarora2945
@shashankarora2945 4 ай бұрын
You made it look so easy. Absolutely FAB!
@apmotivationakashparmar722
@apmotivationakashparmar722 2 ай бұрын
Great and clear explaination by striver. 🙏🙏
@Oldmonk3321
@Oldmonk3321 6 ай бұрын
DAY42:Got the intuition before starting this video 😅failled in edgecase
@ItsAbhiDestiny
@ItsAbhiDestiny 5 ай бұрын
understood bhaiya !! Amazing explaination
@RajatKumar-re2ql
@RajatKumar-re2ql 2 ай бұрын
Here to find previous solution.... Ik its same time comlexity. But idk i just love that solution.
@arnabkundu1648
@arnabkundu1648 5 ай бұрын
We can also use dummyNode and at last return dummyNode->next
@anddevsahil
@anddevsahil 3 ай бұрын
superb explanation
@hashcodez757
@hashcodez757 4 ай бұрын
Mza aagya bhaiya!! suoerb explanation
@rupendarkumar3003
@rupendarkumar3003 7 ай бұрын
explained 100x times better than leetcode yt channel
@jyotirmaysingh4059
@jyotirmaysingh4059 5 ай бұрын
wonderful solution '
@champ-kx9lb
@champ-kx9lb 3 ай бұрын
The leet code code is here : class Solution { public: ListNode* reverseList(ListNode* head) { if(head== NULL || head->next==NULL) { return head; } ListNode*newhead=reverseList(head->next); ListNode*front=head->next; front->next=head; head->next=NULL; return newhead; } ListNode* findkthnode( ListNode* temp,int k) { k=k-1; while(k>0&&temp!=NULL) { k--; temp=temp->next; } return temp; } ListNode* reverseKGroup(ListNode* head, int k) { ListNode* temp=head; ListNode* prev=NULL; while(temp!=NULL) { ListNode* knode=findkthnode(temp,k); if(knode==NULL) { if(prev) { prev->next=temp; } break; } ListNode* nextnode=knode->next; knode->next=NULL; reverseList(temp); if(temp==head) { head=knode; } else{ prev->next=knode; } prev=temp; temp=nextnode; } return head; } };
@invinciblearmyvlogsshorts7911
@invinciblearmyvlogsshorts7911 10 ай бұрын
this got to be the hardest linked list question
@shankysays
@shankysays 9 ай бұрын
Recursion se socho. It's not that difficult if solved recursively
@rajputadi01
@rajputadi01 2 ай бұрын
its just about changing the links while properly handling the edge cases and keeping track of all those pointers as you traverse the linked list. But yeah, good question!
@jha.brajesh
@jha.brajesh 8 ай бұрын
Thanks for the great explanation Striver. Have one query at 21:14 Even if we do not add if(prevNode != null), just "prevNode.next = temp" would also work fine. In that case null node will be pointing to head but that is fine, since we are returning head.
@ratulmanna2923
@ratulmanna2923 6 ай бұрын
If prevNode is NULL, then prevNode->next will be NULL->next,.... That will eventually throw NULL POINTER EXCEPTION
@subhankarkanrar9494
@subhankarkanrar9494 8 ай бұрын
Best explanation ❤
@pranjalnama2420
@pranjalnama2420 6 ай бұрын
amazing explanation
@jk-sj4nf
@jk-sj4nf Жыл бұрын
hey can we expect strings / bit manipulation as next plz
@assasingh8305
@assasingh8305 9 ай бұрын
Heaps also
@hat_awesome21
@hat_awesome21 Жыл бұрын
Bro stack and queue next 😢
@tonylee1868
@tonylee1868 11 ай бұрын
Already hai bhai
@dayashankarlakhotia4943
@dayashankarlakhotia4943 Жыл бұрын
if(head==null) return head; Node prev=null,cur=head,next=null; int cnt=0; while(cur!=null&&cnt
@takeUforward
@takeUforward Жыл бұрын
It’s not always about writing the shortest code. A readable and self explanatory code is always preferred. Cheers!
@rishabh_pant
@rishabh_pant 11 ай бұрын
​@@takeUforward owned that laughing fella
@gautam6405
@gautam6405 10 ай бұрын
ur solution is not space optimized as recursion has call stack which can consume memory
@Sam-gx9xl
@Sam-gx9xl 8 ай бұрын
I have already tried this code in code studio and it was not working ...it seems he has copied from love babbar ...he has also done the same thing but has missed some parameters
@KingBS89
@KingBS89 3 ай бұрын
Why?! In every lecture you write the code and dry run it then why don't you done this in this video But still the best explanation ❤‍🔥
@aanishas1925
@aanishas1925 2 ай бұрын
Thank you sir😊
@abhaythakur2597
@abhaythakur2597 4 ай бұрын
well explained
@manojkumar-hr7tj
@manojkumar-hr7tj 7 ай бұрын
Amazing explanation.
@nooblancer
@nooblancer 5 ай бұрын
with dummy node approach we will not have to remember previous nodes node * reverseKGroup(node * head, int k) { node * dummy = new node(-1, head); node * start = dummy, * end= nullptr; while(start->next != nullptr) { end = start->next; int n = k-1; while(end->next != nullptr && n--) //finding end end = end->next; if(n > 0) break; //if group cant be formed break out node * nextnode = end->next, * t = start->next; //remembering start, and preserving the next node end->next = nullptr; //breaking list node * temp = reverse(start->next); //reverse the LL using recursion t->next = nextnode; //joining the starting node to next node to the next node start->next = temp; //connecting with previous nodes start = t; //moving the start to end of current group } return dummy->next; }
@saswatrath4646
@saswatrath4646 7 ай бұрын
Time complexity in worst case will be O(N^2). consider a case when K =1, the inner loops will go through every node and the outer loops will go through every element individually as well. So, overall tc is O(N^2). How come nobody is the comment section except one student is asking about it ?
@maverick_8707
@maverick_8707 7 ай бұрын
BRO U DIDN'T UNDERSTAND THE CONCEPT IT WILL ALWAYS BE O(2N) NOT MORE THAN THAT EVEN K=1 THEN REVERSE WILL DIRECTLY RETURN THE HEAD WHICH WILL BE ONE LOOP AND OVERALL WE WILL TRAVERSE TO THE GIVEN LINKED LIST WHICH IS O(N)
@AK-nj1je
@AK-nj1je 6 ай бұрын
@@maverick_8707 bro please explain the tc i didn't understood one is for finding the kth node which we can take O(k) and then reverse which also we can take O(k) and what about the outer while loop it will also run for k times no ?
@shankysays
@shankysays 9 ай бұрын
This is much complex implementation. Using recursion it can be done much easier way . Just reverse first three and call solve function again on rest or linked list. Base condition will be when list is exhausted or length is less than k.
@akshaychavan5511
@akshaychavan5511 6 ай бұрын
Agree! I did it recursively. class Solution: # returns first node and last node of the revered list def reverse(self, head): if head == None: return None prev = None current = head while current: nxt = current.next current.next = prev prev = current current = nxt return (prev, head) def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]: if not head: return head kBackup = k newHead = head start = head while head: if k==1: # kth node found newHead = head nextListStart = head.next head.next = None # break the link first, last = self.reverse(start) last.next = self.reverseKGroup(nextListStart, kBackup) # recursively call for remaining list k-=1 head = head.next return newHead
@RahulPatel-hr4qe
@RahulPatel-hr4qe 3 ай бұрын
I tried it by myself , i got the initution like yours but then got confused how to write it in code
@gauravbairagi209
@gauravbairagi209 Жыл бұрын
great video
@az-zm4ji
@az-zm4ji 4 ай бұрын
Can be done by recursion(which is easier than striver's method - his is too messy) /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode* reverseKsteps(ListNode* node, int k){ //reverse the LL starting from node till k steps if(k == 1) return node; ListNode* prev = NULL; ListNode* curr = node; ListNode* next = node->next; ListNode* newHead; while(k--){ curr->next = prev; prev = curr; curr = next; if(next) next = next->next; } newHead = prev; return newHead; } ListNode* solve(ListNode* node, int k){ if(node == NULL) return node; int x = k; ListNode* temp = node; while(x--){ if(temp == NULL) return node; temp = temp->next; } ListNode* headToBeJoined = solve(temp, k); ListNode* parentTail = node; ListNode* parentHead = reverseKsteps(node, k); parentTail->next = headToBeJoined; return parentHead; } ListNode* reverseKGroup(ListNode* head, int k) { return solve(head, k); } };
@DeadPoolx1712
@DeadPoolx1712 2 ай бұрын
UNDERSTOOD;
@rajatshukla2605
@rajatshukla2605 Ай бұрын
Understood!
@ashishpradhan6250
@ashishpradhan6250 5 ай бұрын
superb
@himanshusekharnayak5558
@himanshusekharnayak5558 11 ай бұрын
There is a slight problem in the code where prevLast is not able to connect with nextNode. I've introduced a newHead variable to store the head of the reversed group. Also, I added temp->next = nextNode; after reversing the linked list to connect the reversed group to the nextNode. while (temp != nullptr) { ListNode *kthNode = getKthNode(temp, k); if (kthNode == nullptr) { break; } ListNode *nextNode = kthNode->next; kthNode->next = nullptr; ListNode *newHead = reverseLL(temp); if (temp == head) { head = newHead; } else { prevNode->next = newHead; } temp->next = nextNode; prevNode = temp; temp = nextNode; } Thanks for this amazing video. I tried it in copy and saw links missing so made little changes so that links can be connected. Again thanks.
@MaheshPatil-of1zy
@MaheshPatil-of1zy 8 ай бұрын
your code not working
@TheSpiritualOne401
@TheSpiritualOne401 11 ай бұрын
yes pleaseeee striver bhaiyaa we need bit manipulation and strings as next playlist pleasssse bhaiyaa
@abacas2175
@abacas2175 9 ай бұрын
Okay spoonfeeder😂
@Learnprogramming-q7f
@Learnprogramming-q7f 8 ай бұрын
Thank you Bhaiya
@bishalkundu7592
@bishalkundu7592 11 ай бұрын
Understood ❤
@prathameshjadhav2942
@prathameshjadhav2942 10 ай бұрын
Thanku ji
@myyoutubeisthis
@myyoutubeisthis 6 ай бұрын
Thank you sir.
@YourCodeVerse
@YourCodeVerse 9 ай бұрын
Understood✅🔥🔥
@hardikpatel352
@hardikpatel352 6 ай бұрын
Understood
@lucygaming9726
@lucygaming9726 9 ай бұрын
Should have also added the recursive O(k) stack space solution here. That is a bit easier to come up with.
@naveenkumargembali3494
@naveenkumargembali3494 9 ай бұрын
In worst case it will be 0(n)
@maverick_8707
@maverick_8707 7 ай бұрын
UNDERSTOOOD
@NARUTOUZUMAKI-bk4nx
@NARUTOUZUMAKI-bk4nx 10 ай бұрын
Understooood
@alessandrocamilleri1239
@alessandrocamilleri1239 11 ай бұрын
Excellent explanation. The following solution reduces worst time complexity to O(n+k): pair reverseK(Node* head, int k) { Node* p = NULL; Node* q = head; int count = k; while (count > 0 && q) { count--; Node*r = q->next; q->next = p; p = q; q = r; } if (count > 0) return reverseK(p, k-count); return {p, q}; } Node* reverseKGroup(Node* head, int k) { Node* dummyNode = new Node(-1, head); Node* prevTail = dummyNode; Node* kHead = dummyNode->next; while (kHead) { pair p = reverseK(kHead, k); prevTail-> next = p.first; prevTail = kHead; kHead = p.second; } Node* ans = dummyNode->next; delete dummyNode; return ans; }
@udsingh3044
@udsingh3044 10 ай бұрын
I have used recursion. ``` Node *helper(Node *root, int k) { if(root == NULL || root->next == NULL) return root; int count = 0; Node *curr = root, *prev = NULL, *nxt = NULL; while(count != k && curr != NULL) { curr = curr->next; count++; } if(count < k) return root; curr = root; count = 0; while(count < k && curr != NULL) { nxt = curr->next; curr->next = prev; prev = curr; curr = nxt; count++; } Node *temp = helper(nxt, k); root->next = temp; return prev; } ```
@pravinthakur7791
@pravinthakur7791 7 ай бұрын
Impressive and easy to understand
@chiragbansod8252
@chiragbansod8252 8 ай бұрын
understood
@ashikahmmed8809
@ashikahmmed8809 Жыл бұрын
1st comment bhaiya
@veditakamat6060
@veditakamat6060 8 ай бұрын
Isn't this TC O(N^2) because of outer loop traversing the whole linked list & inner functions traversing sections of linked list ?
@saswatrath4646
@saswatrath4646 7 ай бұрын
yes it will be.
@AK-nj1je
@AK-nj1je 6 ай бұрын
@@saswatrath4646 not n^2 but k^2
@sathwikakovvuri6019
@sathwikakovvuri6019 4 ай бұрын
Your eyes 👀 became too weak take care man
@anupkhismatrao9280
@anupkhismatrao9280 8 ай бұрын
❤❤❤
@ashwaniagrawal27
@ashwaniagrawal27 9 ай бұрын
Confusion prevlast is a pointer toh usme hum prevlast->next = Kthnode kaise store karwa sakte hai??
@piyushmakad4768
@piyushmakad4768 9 ай бұрын
It is not a pointer,it is node which is initiated as null or head...And while traveling we are assigning prevNode to temp and incrementing temp...
@parthh1112
@parthh1112 7 ай бұрын
class Solution { public: ListNode *reverse(ListNode *&head) { ListNode *temp = head; ListNode *put = nullptr; while (temp) { ListNode *h = temp->next; temp->next = put; put = temp; temp = h; } return put; } ListNode *reverseKGroup(ListNode *head, int k) { if (k == 1) return head; int i = 1; ListNode *temp = head, *start = head, *pre = nullptr, *ans = nullptr; bool chk = 1; while (temp) { if (i == k) { ListNode *upcoming = temp->next; temp->next = nullptr; ListNode *coming = reverse(start); ListNode *it = coming; if (!pre) ans = coming; else pre->next = coming; while (it->next) it = it->next; it->next = upcoming; i = 1; start = upcoming; temp = upcoming; pre = it; } else { i++; temp = temp->next; } } return ans; } };
@RN-cj8up
@RN-cj8up 9 ай бұрын
using recursion it would be easy
@mayankshekhar9191
@mayankshekhar9191 10 ай бұрын
The last group of linked list(last part where we don't have kth node) is not getting reversed, tried with different approaches as well.
@mayankshekhar9191
@mayankshekhar9191 10 ай бұрын
Its working now, thanks class Solution { public static Node reverse(Node head, int k) { //Your code here Node temp = head; Node prevNode = null; while(temp != null) { Node kthNode = findKthNode(temp, k); if(kthNode == null) { temp = ReverseGroup(temp); if(prevNode != null) prevNode.next = temp; break; } Node nextNode = kthNode.next; kthNode.next = null; Node newNode = ReverseGroup(temp); if(temp == head) { head = newNode; } else { prevNode.next = kthNode; } prevNode = temp; temp = nextNode; } return head; } public static Node findKthNode(Node head, int k) { Node temp = head; if(temp == null || temp.next == null) return temp; while(temp != null && k > 1) { temp = temp.next; k--; } return temp; } public static Node ReverseGroup(Node head) { Node temp = head; if(temp == null || temp.next == null) return temp; Node last = null; Node temp1 = head.next; //reverse the linked list till n-1 while(head.next != null){ head.next = last; last = head; head = temp1; temp1 = temp1.next; } //last node pointer change head.next = last; last = head; return last; } }
@kabirkapoor9149
@kabirkapoor9149 8 ай бұрын
Striver Make Strings Playlist Please ......
@Harika_Ramesh
@Harika_Ramesh 9 ай бұрын
Why we used k-=1 while finding getkthnode method
@rushhour4379
@rushhour4379 9 ай бұрын
We start with k and decrement it at each step while traversing the list. It's like a count down to reach the Kth node
@ashwinmiyer6159
@ashwinmiyer6159 6 ай бұрын
@@rushhour4379 no but there is one k-=1 before the loop
@saidhanyasudhan3160
@saidhanyasudhan3160 11 ай бұрын
bro add this to playlist please
@SamyakSharma-oy1bv
@SamyakSharma-oy1bv 17 күн бұрын
respect++;
@ShubhamGupta-jy3wv
@ShubhamGupta-jy3wv 11 ай бұрын
Next strings plsss
@AkashKumarTiwary-u4b
@AkashKumarTiwary-u4b 6 ай бұрын
god
@sahilvaish_nav_
@sahilvaish_nav_ 24 күн бұрын
21:04
@supersuperhero2449
@supersuperhero2449 9 ай бұрын
Main while loop will not take any time sir ?
@pavankumarreddy8642
@pavankumarreddy8642 9 ай бұрын
That's what i didn't get. The TC is O(3*n), if the main while loop complexity is considered
@ummehanifatima2039
@ummehanifatima2039 11 ай бұрын
Please Striver provide iterative approach Pyhton code for this problem I have tried lot many times but none of my test cases are getting passed.
@harshitgarg2820
@harshitgarg2820 11 ай бұрын
My solution is not working, and the solution given in the sheet is different. For ex => head = [1,2,3,4,5], k = 2, I'm getting [2,1,5]. PLZ help!
@takeUforward
@takeUforward 11 ай бұрын
class Solution { public: ListNode* reverseLinkedList(ListNode *head) { ListNode* temp = head; ListNode* prev = NULL; while(temp != NULL) { ListNode* front = temp->next; temp->next = prev; prev = temp; temp = front; } return prev; } private: ListNode* getKthNode(ListNode* temp, int k) { k -= 1; while(temp != NULL && k > 0) { k--; temp = temp->next; } return temp; } public: ListNode* reverseKGroup(ListNode* head, int k) { ListNode* temp = head; ListNode* prevLast = NULL; while(temp != NULL) { ListNode* kThNode = getKthNode(temp, k); if(kThNode == NULL) break; ListNode* nextHead = kThNode->next; kThNode->next = NULL; ListNode* newHeadOfKGroup = reverseLinkedList(temp); if(temp == head) { head = newHeadOfKGroup; } else { prevLast->next = newHeadOfKGroup; } prevLast = temp; temp = nextHead; } if(prevLast != NULL) prevLast->next = temp; return head; } };
@iamnottech8918
@iamnottech8918 9 ай бұрын
My solution , I wrote it straightforward here second is start and temp will move ,Hope it helps class Solution { public: ListNode* reverseLL(ListNode* head) { if(head==NULL || head->next==NULL) return head; ListNode*prev=NULL; ListNode*temp=head; while(temp) { ListNode*store=temp->next; temp->next=prev; prev=temp; temp=store; } return prev; } ListNode* reverseKGroup(ListNode* head, int k) { if(head==NULL || head->next==NULL) return head; ListNode*temp=head; ListNode*second=head; ListNode*prev=NULL; ListNode*next=NULL; int count=0; while(temp!=NULL) { count++; if(count==k) { next= temp->next; temp->next=NULL; temp=reverseLL(second); if(second==head) { head=temp; } else { prev->next=temp; } prev=second; temp=next; second=next; count=0; continue; } temp=temp->next; } if(countnext=next; return head; } };
@DarkKight123
@DarkKight123 11 ай бұрын
The Sheet link is not working Please fix it.
@njquotes9478
@njquotes9478 7 ай бұрын
Please provide Java code. My code is giving TLE during submission.
@artikumari-es6ep
@artikumari-es6ep 4 ай бұрын
JAVA SOLUTION : public ListNode reverseKGroup(ListNode head, int k) { ListNode temp = head; ListNode previous = null; while(temp!=null){ ListNode kthNode= findKthNode(temp, k); if(kthNode==null){ if(previous!=null){ previous.next= temp; } break; } ListNode nextNode=kthNode.next; kthNode.next=null; // ListNode newHead=reverse(temp); reverse(temp); if(head==temp){ head= kthNode; //head = newHead; } else{ previous.next=kthNode; //previous.next = newHead; } //temp.next= nextNode; previous = temp; temp = nextNode; } return head; } private ListNode findKthNode(ListNode temp, int k){ k=k-1; while(temp!=null && k>0){ temp=temp.next; k--; } return temp; } private ListNode reverse(ListNode temp){ ListNode prev= null; ListNode cur=temp; while(cur!=null){ ListNode next = cur.next; cur.next=prev; prev=cur; cur=next; } return prev; }
@shikher4559
@shikher4559 5 ай бұрын
can't we do it with dummy? create the whole chain again simple
@ummehanifatima2039
@ummehanifatima2039 11 ай бұрын
Only one test case is still not passing def reverse_ll(head): prev = None curr = head next_node = None while curr: next_node = curr.next curr.next = prev prev = curr curr = next_node return prev def get_kth_node(temp, k): k -= 1 while temp and k > 0: k -= 1 temp = temp.next return temp def kReverse(head, k): temp = head prev_last = None next_node = None while temp: kth_node = get_kth_node(temp, k) if not kth_node: if prev_last: prev_last.next = temp break next_node = kth_node.next kth_node.next = None reverse_ll(temp) if temp == head: head = kth_node else: if prev_last: prev_last.next = kth_node prev_last = temp temp = next_node return head
@takeUforward
@takeUforward 11 ай бұрын
class Solution { public: ListNode* reverseLinkedList(ListNode *head) { ListNode* temp = head; ListNode* prev = NULL; while(temp != NULL) { ListNode* front = temp->next; temp->next = prev; prev = temp; temp = front; } return prev; } private: ListNode* getKthNode(ListNode* temp, int k) { k -= 1; while(temp != NULL && k > 0) { k--; temp = temp->next; } return temp; } public: ListNode* reverseKGroup(ListNode* head, int k) { ListNode* temp = head; ListNode* prevLast = NULL; while(temp != NULL) { ListNode* kThNode = getKthNode(temp, k); if(kThNode == NULL) break; ListNode* nextHead = kThNode->next; kThNode->next = NULL; ListNode* newHeadOfKGroup = reverseLinkedList(temp); if(temp == head) { head = newHeadOfKGroup; } else { prevLast->next = newHeadOfKGroup; } prevLast = temp; temp = nextHead; } if(prevLast != NULL) prevLast->next = temp; return head; } };
@cenacr007
@cenacr007 6 ай бұрын
us
@spartant_1212
@spartant_1212 6 ай бұрын
It is not correct about the TC. It is O(N**2) not O(N). You are wrong about that.
@codemeanslove
@codemeanslove 6 ай бұрын
He is correct 💯 O(2n) After normalisation On)
@SasankNasika
@SasankNasika 10 ай бұрын
recursive solution class Solution { public: int count(ListNode* head) { int bcount = 0; while (head != nullptr) { bcount++; head = head->next; } return bcount; } ListNode* reverseKGroup(ListNode* head, int k) { // basecase if (count(head) < k || head == nullptr || head->next == nullptr) { return head; } int cnt = 0; ListNode* prev = nullptr; ListNode* temp = head; ListNode* next = NULL; while (temp != nullptr && cnt < k) { next = temp->next; temp->next = prev; prev = temp; temp = next; cnt++; } // new head is prev head->next = reverseKGroup(next, k); return prev; } };
@artikumari-es6ep
@artikumari-es6ep 4 ай бұрын
JAVA Solution : public ListNode reverseKGroup(ListNode head, int k) { ListNode temp = head; ListNode previous = null; while(temp!=null){ ListNode kthNode= findKthNode(temp, k); if(kthNode==null){ if(previous!=null){ previous.next= temp; } break; } ListNode nextNode=kthNode.next; kthNode.next=null; // ListNode newHead=reverse(temp); reverse(temp); if(head==temp){ head= kthNode; //head = newHead; } else{ previous.next=kthNode; //previous.next = newHead; } //temp.next= nextNode; previous = temp; temp = nextNode; } return head; } private ListNode findKthNode(ListNode temp, int k){ k=k-1; while(temp!=null && k>0){ temp=temp.next; k--; } return temp; } private ListNode reverse(ListNode temp){ ListNode prev= null; ListNode cur=temp; while(cur!=null){ ListNode next = cur.next; cur.next=prev; prev=cur; cur=next; } return prev; }
@shamanthhegde2820
@shamanthhegde2820 3 ай бұрын
public ListNode reverse(ListNode head) { if(head == null || head.next == null) return head; ListNode curr = head; ListNode next = null; ListNode prev = null; while(curr!=null) { next = curr.next; curr.next = prev; prev = curr; curr = next; } return prev; } public ListNode reverseKGroup(ListNode head, int k) { if(head == null || head.next == null || k
@anshgupta2506
@anshgupta2506 11 ай бұрын
i have done this q by recursion Node* rev(Node* head){ if(head==NULL|| head->next==NULL)return head; Node* front=NULL; Node* prev=NULL; Node* temp=head; while(temp!=NULL){ front=temp->next; temp->next=prev; prev=temp; temp=front; } return prev; } Node* kReverse(Node* head, int k) { // Write your code here. if(k==1 || head==NULL)return head; int cnt=0; Node* temp=head; while(temp!=NULL){ cnt++; if(cnt==k)break; temp=temp->next; if(temp==NULL && cntnext,k); temp->next=NULL; Node* newhead=rev(head); Node* newtemp=newhead; while(newtemp->next!=NULL){ newtemp=newtemp->next; } newtemp->next=nextnewhead; return newhead; }
@Ayush37262
@Ayush37262 9 ай бұрын
Sorry to say, but this time you didn't explained well 😢
@dewanandkumar8589
@dewanandkumar8589 6 ай бұрын
Understood
@gauravtiwari6104
@gauravtiwari6104 3 ай бұрын
us
@abhishekprasad010
@abhishekprasad010 5 ай бұрын
Understood
@himanshidafouty347
@himanshidafouty347 5 ай бұрын
Understood
@Crazycaptain325
@Crazycaptain325 2 ай бұрын
Understood
@abhinavabhi3568
@abhinavabhi3568 Ай бұрын
Understood
L22. Rotate a LinkedList
12:10
take U forward
Рет қаралды 72 М.
The Ultimate Sausage Prank! Watch Their Reactions 😂🌭 #Unexpected
00:17
La La Life Shorts
Рет қаралды 8 МЛН
Симбу закрыли дома?! 🔒 #симба #симбочка #арти
00:41
Симбочка Пимпочка
Рет қаралды 5 МЛН
Bolt.new: $300 in 1 Click with AI SEO 🤯
6:31
Julian Goldie Clips
Рет қаралды 1,1 М.
Reverse Nodes in K-Group - Linked List - Leetcode 25
12:20
NeetCode
Рет қаралды 114 М.
L6. Odd Even Linked List | Multiple Approaches
24:05
take U forward
Рет қаралды 106 М.
The Last Algorithms Course You'll Need by ThePrimeagen | Preview
16:44
Frontend Masters
Рет қаралды 325 М.
L9. Reverse a LinkedList | Iterative and Recursive
32:42
take U forward
Рет қаралды 163 М.
L23. Merge two sorted Linked Lists
18:55
take U forward
Рет қаралды 72 М.
How I Mastered Data Structures and Algorithms
10:45
Ashish Pratap Singh
Рет қаралды 260 М.
L24. Flattening a LinkedList | Multiple Approaches with Dry Run
32:58
take U forward
Рет қаралды 65 М.
Reverse Nodes in k-Group | Among the toughest problems of LinkedList
20:05