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.
@alessandrocamilleri123910 ай бұрын
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.
@suhasherle735017 күн бұрын
exactly, I found this solution better than the previous video
@venub88537 ай бұрын
What a fantastic explanation by breaking the problem into subparts!!!💥
@CrazyHunk147 ай бұрын
I was able to write almost the same code by myself thanks Striver!
@ayushidalal548818 күн бұрын
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😊
@ankitsharda113110 ай бұрын
Superb Explanation!! Didn't understood in the first watch but got it while watching for the second time!!
@CodeWithSeenu6 күн бұрын
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
@vasanthdamera58965 ай бұрын
just after listening once i had code the solution in one go and it executed perfectly.... great explanation by striver
@manishmahajan60943 ай бұрын
Marking my Day 31 of learning DSA. Thank you @striver for the best explanations !!!
@humanity7880Ай бұрын
Best video on this topic! watched 2 times and now the logic is crystal clear in my head
@DevilJim-p1sКүн бұрын
I found the solution of this problem before that video 💪 thanks striver you're best teacher ❤
@iayushsharma6 ай бұрын
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
@salonisharma97095 ай бұрын
thanku
@dhruvkushwaha92863 ай бұрын
jdbc
@akshaychavan55116 ай бұрын
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
@brokegod58713 ай бұрын
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
@prabhjeetsingh63052 ай бұрын
thanks. I got a headache looking at this question until I saw this approach.
@shashankarora29454 ай бұрын
You made it look so easy. Absolutely FAB!
@apmotivationakashparmar7222 ай бұрын
Great and clear explaination by striver. 🙏🙏
@Oldmonk33216 ай бұрын
DAY42:Got the intuition before starting this video 😅failled in edgecase
@ItsAbhiDestiny5 ай бұрын
understood bhaiya !! Amazing explaination
@RajatKumar-re2ql2 ай бұрын
Here to find previous solution.... Ik its same time comlexity. But idk i just love that solution.
@arnabkundu16485 ай бұрын
We can also use dummyNode and at last return dummyNode->next
@anddevsahil3 ай бұрын
superb explanation
@hashcodez7574 ай бұрын
Mza aagya bhaiya!! suoerb explanation
@rupendarkumar30037 ай бұрын
explained 100x times better than leetcode yt channel
Recursion se socho. It's not that difficult if solved recursively
@rajputadi012 ай бұрын
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.brajesh8 ай бұрын
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.
@ratulmanna29236 ай бұрын
If prevNode is NULL, then prevNode->next will be NULL->next,.... That will eventually throw NULL POINTER EXCEPTION
@subhankarkanrar94948 ай бұрын
Best explanation ❤
@pranjalnama24206 ай бұрын
amazing explanation
@jk-sj4nf Жыл бұрын
hey can we expect strings / bit manipulation as next plz
@assasingh83059 ай бұрын
Heaps also
@hat_awesome21 Жыл бұрын
Bro stack and queue next 😢
@tonylee186811 ай бұрын
Already hai bhai
@dayashankarlakhotia4943 Жыл бұрын
if(head==null) return head; Node prev=null,cur=head,next=null; int cnt=0; while(cur!=null&&cnt
@takeUforward Жыл бұрын
It’s not always about writing the shortest code. A readable and self explanatory code is always preferred. Cheers!
@rishabh_pant11 ай бұрын
@@takeUforward owned that laughing fella
@gautam640510 ай бұрын
ur solution is not space optimized as recursion has call stack which can consume memory
@Sam-gx9xl8 ай бұрын
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
@KingBS893 ай бұрын
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 ❤🔥
@aanishas19252 ай бұрын
Thank you sir😊
@abhaythakur25974 ай бұрын
well explained
@manojkumar-hr7tj7 ай бұрын
Amazing explanation.
@nooblancer5 ай бұрын
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; }
@saswatrath46467 ай бұрын
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_87077 ай бұрын
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-nj1je6 ай бұрын
@@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 ?
@shankysays9 ай бұрын
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.
@akshaychavan55116 ай бұрын
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-hr4qe3 ай бұрын
I tried it by myself , i got the initution like yours but then got confused how to write it in code
@gauravbairagi209 Жыл бұрын
great video
@az-zm4ji4 ай бұрын
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); } };
@DeadPoolx17122 ай бұрын
UNDERSTOOD;
@rajatshukla2605Ай бұрын
Understood!
@ashishpradhan62505 ай бұрын
superb
@himanshusekharnayak555811 ай бұрын
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-of1zy8 ай бұрын
your code not working
@TheSpiritualOne40111 ай бұрын
yes pleaseeee striver bhaiyaa we need bit manipulation and strings as next playlist pleasssse bhaiyaa
@abacas21759 ай бұрын
Okay spoonfeeder😂
@Learnprogramming-q7f8 ай бұрын
Thank you Bhaiya
@bishalkundu759211 ай бұрын
Understood ❤
@prathameshjadhav294210 ай бұрын
Thanku ji
@myyoutubeisthis6 ай бұрын
Thank you sir.
@YourCodeVerse9 ай бұрын
Understood✅🔥🔥
@hardikpatel3526 ай бұрын
Understood
@lucygaming97269 ай бұрын
Should have also added the recursive O(k) stack space solution here. That is a bit easier to come up with.
@naveenkumargembali34949 ай бұрын
In worst case it will be 0(n)
@maverick_87077 ай бұрын
UNDERSTOOOD
@NARUTOUZUMAKI-bk4nx10 ай бұрын
Understooood
@alessandrocamilleri123911 ай бұрын
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; }
can't we do it with dummy? create the whole chain again simple
@ummehanifatima203911 ай бұрын
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