MEDIUM NC#38 Blind #44 Linked List

19. Remove Nth Node From End of List

📖 Problem

Given the head of a linked list, remove the nth node from the end of the list and return its head.

🧠 Visual Learning Aid

1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases

JS/TS Refreshers

  • Array methods (`push`, `pop`, `shift`, `slice`)
  • Object/Map/Set usage patterns
  • Function parameter and return typing
  • In-place array updates
  • Sorted array traversal
  • Boundary condition checks

Logical Thinking Concepts

  • Define invariants before coding
  • Check edge cases first (`[]`, single element, duplicates)
  • Estimate time/space before implementation
  • Apply Two Pointers reasoning pattern

💡 Approach

  • Use two pointers with gap of n
  • Move fast pointer n+1 steps ahead
  • When fast reaches end, slow is at the node before target
  • Use dummy node to handle edge case of removing head
  • Time: O(n), Space: O(1)

🛠️ Hints & Pitfalls

Hints

  • Use two pointers with gap of n
  • Move fast pointer n+1 steps ahead
  • When fast reaches end, slow is at the node before target

Common Pitfalls

  • Use dummy node to handle edge case of removing head
  • Time: O(n), Space: O(1)

🧪 Test Cases

Hidden tests on submit: 1

Test Case 1
Not run
Input:
removeNthFromEnd(arrayToList([1,2,3,4,5]), 2);
Expected:
{"val":1,"next":{"val":2,"next":{"val":3,"next":{"val":5,"next":null}}}}
Test Case 2
Not run
Input:
removeNthFromEnd(arrayToList([1]), 1);
Expected:
null
Test Case 3
Not run
Input:
removeNthFromEnd(arrayToList([1,2]), 1);
Expected:
{"val":1,"next":null}

📝 Code Editor

📚 Reference Solution

⌘K Search ⌘↩ Run ⌘S Submit