Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com

Reverse List In K Groups

Hard
0/120
Average time to solve is 15m
profile
Contributed by
362 upvotes
Asked in companies
Paytm (One97 Communications Limited)SAP LabsSamsung

Problem statement

You are given a linked list of 'n' nodes and an integer 'k', where 'k' is less than or equal to 'n'.


Your task is to reverse the order of each group of 'k' consecutive nodes, if 'n' is not divisible by 'k', then the last group of nodes should remain unchanged.


For example, if the linked list is 1->2->3->4->5, and 'k' is 3, we have to reverse the first three elements, and leave the last two elements unchanged. Thus, the final linked list being 3->2->1->4->5.


Implement a function that performs this reversal, and returns the head of the modified linked list.


Example:
Input: 'list' = [1, 2, 3, 4], 'k' = 2

Output: 2 1 4 3

Explanation:
We have to reverse the given list 'k' at a time, which is 2 in this case. So we reverse the first 2 elements then the next 2 elements, giving us 2->1->4->3.


Note:
All the node values will be distinct.


Detailed explanation ( Input/output format, Notes, Images )
Input Format:
The first line of the input contains a single integer 'n', denoting the number of nodes in the linked list.

The second line contains 'n' space-separated integers, denoting the elements of the linked list.

The third line of input contains an integer 'k'.


Output Format:
Return the head of the modified linked list.


Note:
You don't need to print anything, just implement the given function. Contents of your returned linked list will be printed in a single line.


Sample Input 1:
6
5 4 3 7 9 2
4 


Sample Output 1:
7 3 4 5 9 2


Explanation of the Sample Input 1:
For the given test case, we reverse the nodes in groups of four. But for the last 2 elements, we cannot form a group of four, so leave them as they are. The linked list becomes 7->3->4->5->9->2. Hence the output is 7 3 4 5 9 2


Sample Input 2:
4
4 3 2 8
4 


Sample Output 2:
8 2 3 4


Expected Time Complexity:
Try to solve this in O(n). 


Expected Space Complexity:
Try to solve this using O(1) extra space.    


Constraints:
1 <= n <= 10^4
1 <= k <= n

Time Limit: 1 sec


Hint

Try the simplest possible way.

Approaches (2)
Recursive Approach
  • We can use recursion to solve this problem.
  • The main idea is to reverse the first ‘K’ nodes by ourselves and let the recursive function reverse the rest of the linked list.
  • Let reverseList() be the recursive function which takes the head of the linked list and ‘K’ as the parameters.
  • Now we can iteratively reverse the first ‘K’ nodes of the linked list.
  • And then if we still have some nodes left in the linked list, then we can call reverseList(), until the nodes are exhausted.
Time Complexity

O(N), where ‘N’ is the size of the Linked List.

Space Complexity

O(N), Stack space for recursive calls of ‘N’ nodes of the linked list.

Code Solution
(100% EXP penalty)
Reverse List In K Groups
All tags
Sort by
Search icon

Interview problems

EASY SOLUTION | RECURSION | BEATS 98%

Here, the getLength function is used to find the remaining nodes and is called each time for recursive. thus finds the remaining nodes whether they are to be reversed or not 

 

int getLength(Node *temp){

    

    int cnt=0;

    while(temp != NULL){

        temp = temp->next;

        cnt++;

    }

    return cnt;

 

}

 

Node* kReverse(Node* head, int k) {

 

    int n = getLength(head);   //to get remaining nodes

 

    //Base case

    if(head==NULL){

        return head;

    }

 

    Node *prev = NULL;

    Node *curr = head;

    Node *next = NULL;

    int cnt =0;

    while(curr != NULL && cnt<k){

        next = curr->next;

        curr->next = prev;

        prev = curr;

        curr = next;

        cnt++;

    }

//n-k≥ k is done to find whether remaining nodes are to reversed or not

    if(next !=NULL && n-k>=k){    

        head->next = kReverse(next,k);  //calls recursive function 

    }

    else{

        head->next= curr;

    }

    return prev;

    

}

66 views
0 replies
1 upvote

Interview problems

Reverse List In K Groups || easy c++ sollution

Node* reverse(Node* head){
    if(head == NULL || head->next ==NULL){
        return head;
    }
    Node* back =NULL;
    Node* curr =head;
    Node* front =NULL;
    while(curr != NULL){
        front =curr->next;
        curr->next =back;
        back =curr;
        curr =front;
    }
    return back;
}

Node *kReverse(Node *head, int k) {
    Node *temp = head;
    Node* nextNode =NULL;
    Node* prevNode =NULL;
    while(temp != NULL){
        Node *kth = temp;
        for(int i=1;i<k && kth != NULL;i++){
            kth =kth->next;
        }
        if(kth == NULL){
            if(prevNode){
                prevNode->next =temp;
            }
            break;
        }
        nextNode =kth->next;
        kth->next =NULL;
        reverse(temp);
        if(head == temp){
            head =kth;
        }
        else{
            prevNode->next =kth;
        }
        prevNode =temp;
        temp =nextNode;
    }
    return head;
}
103 views
0 replies
0 upvotes

Interview problems

Best c++ working solution

Added the case where number of elements left ≥ k or else print otherwise.

Made a count function for finding number of elements left or number of forward elements in each recursion.

int count(Node* head){

    int cnt = 0;

    while(head != NULL){

        head = head -> next;

        cnt++;

    }

    return cnt;

}


 

Node* kReverse(Node* head, int k) {

    if(head == NULL) return head;

    

    Node* forward = NULL;

    Node* curr = head;

    Node* prev = NULL;

    int cnt = 0;

    while(curr != NULL && cnt < k){

        forward = curr -> next;

        curr -> next = prev;

        prev = curr;

        curr = forward;

        cnt++;

    }

    if(forward != NULL && count(forward)>=k) {

        head->next = kReverse(forward, k);

    }

    else{

        head -> next = forward;

    }

    return prev;

}

99 views
2 replies
2 upvotes

Interview problems

C++ solution to reverse a linked list in groups of k using recursion:

Node* kReverse(Node* head, int k) {

    //base case

    if(head == NULL){

        return NULL;

    }

 

    //step1: reverse the 1st k node

    Node* prev = NULL;

    Node* curr = head;

    Node* next = NULL;

    int count = 0;

 

    // Check if there are at least 'k' nodes to reverse

    Node* check = head;

    for (int i = 0; i < k; ++i) {

        if (!check)

          return head; // Less than 'k' nodes, return as it is

        check = check->next;

    }

    

    while(curr != NULL && count < k){

        next = curr->next;

        curr->next = prev;

        prev = curr;

        curr = next;

        count++;

    }

 

    //step2: recursion call for algorithm 

    if(next != NULL){

        head->next = kReverse(next, k);

    }

 

    //return haed of reverse call

    return prev;

}

86 views
0 replies
0 upvotes

Interview problems

Java recursion code

import java.util.* ;
import java.io.*; 
/****************************************************************
    Following is the Linked List node structure

    class Node
    {
    public:
        int data;
        Node next;
        Node(int data)
        {
            this.data = data;
            this.next = NULL;
        }
    };

*****************************************************************/



public class Solution {

	public static Node kReverse(Node head, int k) {
        Node prev=null;
        Node curr=head;
        Node forward=null;
        int count =0;

        while(curr!=null&&count<k)
        {
            forward=curr.next;
            curr.next=prev;
            prev=curr;
            curr=forward;
            
            count++;
        }
        if(count<k){
            return reverse(prev);
        }
         if(forward!=null)
        {
             head.next=kReverse(forward, k);
         }
        return prev;
	}
    private static Node reverse(Node head){
        Node prev=null;
        Node curr=head;
        Node forward=null;
        int count =0;

        while(curr!=null)
        {
            forward=curr.next;
            curr.next=prev;
            prev=curr;
            curr=forward;
        }
        return prev;
    }

}
38 views
0 replies
0 upvotes

Interview problems

Easy solution using single recursion

//count the remainig elements in linked list

int countnum(Node* head){

    int c=0;

    while (head != NULL) {

      head = head->next;

      c++;

    }

    return c;

}

Node* kReverse(Node* head, int k) {

    // Write your code here.

    //if head 

    if(head==NULL)

      {

        return NULL;

      }

    Node* prev=NULL;

    Node* curr= head;

    Node* forward = NULL;

    int count=0;

 

    while(curr != NULL && count<k)

    {

        forward=curr->next;

        curr->next = prev;

        prev=curr;

        curr=forward; 

        count++;

    }

    int c=countnum(forward);

    if(forward != NULL&& k<=c)

    {

        head->next = kReverse(forward,k);

    }

    else{

       head->next=forward;   

    }

    return prev;

    }

102 views
0 replies
0 upvotes

Interview problems

most easy and optimal solution beats 99% of solution in c++

int length(Node *head){

    int i=0;

    while(head!=nullptr){

      head=head->next;

      ++i;

    }

    return i;

}

Node* kReverse(Node* head, int k) {

    if(head==nullptr){

        return head;

    }

   Node *pre=nullptr;

   Node *post=nullptr;

   Node *curr=head;

   int i=0;

  int c=length(head);

  if(c<k){

      return head;

  }

   while(curr!=nullptr && i<k){

       post=curr->next;

       curr->next=pre;

       pre=curr;

       curr=post;

       i++;

   }

   Node *temp=pre;

   while (temp->next != nullptr) {

       temp = temp->next;

   }

   if(curr!=nullptr){

      temp->next=kReverse(curr,k);

   }

   head=pre;

   return head;

 

}

145 views
0 replies
0 upvotes

Interview problems

every condition satisfied

/**

* Definition for singly-linked list.

* class Node {

* public:

* int data;

* Node *next;

* Node() : data(0), next(nullptr) {}

* Node(int x) : data(x), next(nullptr) {}

* Node(int x, Node *next) : data(x), next(next) {}

* };

*/

 

Node* kReverse(Node* head, int k) {

// Write your code here.

if(head == NULL || k==0 ){

return head;

}

Node* next = NULL;

Node* curr = head;

Node* prev = NULL;

int i = 0;

//first iteration

int count = 0;

Node*temp = head;

while(temp != NULL){

count++;

temp = temp->next;

}

if(count >= k){

while(curr != NULL && i<k){

next = curr->next;

curr -> next = prev;

prev = curr;

curr = next;

i++;

}

 

if (next != NULL) {

head->next = kReverse(next, k);

}

 

return prev;

}else{

return head;

}

}

44 views
0 replies
0 upvotes

Interview problems

best optimal solution

Node* kReverse(Node* head, int k) {

    // Write your code here.

    if(head == NULL){

        return head;

    }

    Node* ptr=head;

    Node* prev=NULL;

    Node* next=NULL;

    int cnt=0;

    while(ptr!=NULL && cnt < k){

         next=ptr->next;

         ptr->next=prev;

         prev=ptr;

         ptr=next;

         cnt++;

    }

    if(cnt < k){

       ptr=prev;

       prev=NULL;

       next=NULL;

       int cnt=0;

       while(ptr!=NULL && cnt < k){

         next=ptr->next;

         ptr->next=prev;

         prev=ptr;

         ptr=next;

         cnt++;

       }

    }

    if(next != NULL){

        head->next=kReverse(next,k);

    }

    return prev;  

}

112 views
0 replies
0 upvotes

Interview problems

easy cpp code

int length(Node * head){
    int count=1;
    Node *temp=head;
    while(temp->next!=NULL){
        count++;
        temp=temp->next;
    }
    return count;
}

Node* reversed(Node* &head,int k,int len){
    // Base case
    if (head == NULL || k <= 0) {
        return NULL;
    }
    if(len<k){
        return head;
    }
    
    // Step 1: Reverse first k nodes
    Node* next = NULL;
    Node* curr = head;
    Node* prev = NULL;
    int count = 0;
    
    while (curr != NULL && count < k) {
        next = curr->next;
        curr->next = prev;
        prev = curr;
        curr = next;
        count++;
    }
    
    // Step 2: Recursion will handle the rest
    if (next != NULL) {
        head->next = reversed(next, k,len-k);
    }
    
    // Step 3: Return head of reversed list
    return prev;
}

Node* kReverse(Node* head, int k) {
    int len = length(head);
    return reversed(head,k,len);
}
106 views
0 replies
0 upvotes
Full screen
Console