Skip to content
CodeKruPro

Remove the nth node from the end of a linked list

Coding problemEasy-MediumAsked in: Adobe, Amazon, Apple, Google, Meta, Microsoft

You are given the head of a linked list and a whole number n. Remove the node that is n-th from the end of the list (n = 1 is the last node) and return the head of the changed list.

n is always between 1 and the number of nodes. Removing the only node leaves an empty list.

Examples

Example 1
Input: head = [1,2,3,4,5], n = 2
Output: [1,2,3,5]
Example 2
Input: head = [1], n = 1
Output: []
Example 3
Input: head = [1,2], n = 2
Output: [2]
The 2nd node from the end is the head itself.

Constraints

  • The list has between 1 and 100,000 nodes
  • 1 <= n <= number of nodes
  • Each value is a 32-bit integer

Run checks the 3 examples. Submit also runs the hidden tests: edge cases, large inputs and a time limit.

Run your code to see the results here.

This question is part of Pro+

Pro+ opens every question in Interview Prep and the mock interview. Every article and the first 2 questions of each topic stay free. Hands-on Selenium and API tasks follow their course lesson's own lock.

See Pro+

Already have Pro+? Sign in