Skip to main content

Command Palette

Search for a command to run...

Reverse Node With Kth Group Solution JavaScript LinkedList (Hard)

Published
•2 min read•View as Markdown
Reverse Node With Kth Group Solution JavaScript LinkedList (Hard)
S

Ex Full Stack Developer at @WiseBoxs | Vue React Node | MERN

In this article we will understand the approach of the reverse Node with Kth Group. This is a Linkedlist hard question. We will solve it through javascript and see the logic.

Code

var getKthNode = function(curr, k){
    while(curr && k>0){
        curr = curr.next
        k--
    }
    return curr
}

var reverse = function(head){  
    let curr = head
    let prev = null
    while(curr){
        let next = curr.next
        curr.next = prev
        prev = curr
        curr = next
    }
    return prev
}

var reverseKGroup = function(head, k) {
    let dummy = new ListNode() //null
    let groupPrev = dummy // pointing before head
    dummy.next = head // adding actual linkedlist with the dummy
    while(true){
        let kthNode = getKthNode(groupPrev, k) //getting kth node
        if(!kthNode) break  // if not enough node get out of the loop
        let next = kthNode.next; // pointing next to the after the kth node
        let temp = groupPrev.next //temp to reverse 
        kthNode.next = null  // cutting the linkedlist after kthnode
        let newHead = reverse(temp) //getting the new head of the reversed linkedlist

        groupPrev.next = newHead // pointing the pev next to the new head
        temp.next = next  // temp is lying at the end of the linkedList so it connecting with next nodes
        groupPrev = temp // previous is set to the last reversed node

    }
    return dummy.next   // returing the whole linkedlist first node

};

Complexity

Time Complexity: O(n)

Space Complexity: O(1)