19. Remove Nth Node From End of List

#linked-list

Problem

Intuition

Time Complexity

Space Complexity

Solution

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        // Time Complexity: O(n), n -> number of nodes in linked list
        // Space complexity: O(1), Auxillary space complexity

        // Adding sentinel node. Adding this helps in moving the
        // nodes using 0-index correctly

        // Create a dummy node
        ListNode dummy = new ListNode();
        dummy.next = head; // Link head to dummy.next

        // Create two pointers setting to dummy
        ListNode slow = dummy;
        ListNode fast = dummy;

        // Move fast pointer by "n" steps forward
        for(int i=0;i<=n;i++) {
            fast = fast.next;
        }

        // Traverse fast and slow pointers till end of fast ptr
        while(fast!=null) {
            slow = slow.next;
            fast = fast.next;
        }

        // Rearranging the nodes
        slow.next = slow.next.next;

        // As head is set to dummy.next, return dummy.next
        // Where the head ListNode is manipulated
        return dummy.next;
    }
}

Last updated

Was this helpful?