educative.io

How this logic works

Is it possible to explain in details how this logic work.


Course: Grokking Coding Interview Patterns in Java - Learn Interactively
Lesson: Solution: Remove nth Node from End of List

Hello @Vinod_L_P,

Sure, let me explain the provided code:

  1. Initialize two pointers:

    • right and left are set to the head of the linked list.
  2. Move right pointer:

    • right moves n steps ahead, creating a gap of n nodes between left and right.
  3. Check if right reaches the end:

    • Two possibilities:
      a. If right doesn’t reach the end during n steps, the code proceeds.
      b. If right becomes null, the linked list is too short, and it returns a modified list starting from the second node (head.next).

    • In the second case, the code returns a modified list starting from the second node (head.next). This is because, in this scenario, the head needs to be removed, so the new head of the list becomes the node after the original head (head.next).

  4. Move both pointers until right reaches the end:

    • If right is not at the end, move both pointers until right reaches the end.
  5. Remove N-th node from the end:

    • left is now exactly n nodes away from the end. It updates left.next to skip the next node, effectively removing the n-th node.
  6. Return the modified list:

    • Finally, it returns the modified linked list.

I hope this is clarifies your confusion regarding the code. Feel free to share more feedbacks and suggestions, we’d be happy to help!

Happy learning!