Blind 75
22 / 75Free practice

Remove Nth Node From End of List

Medium · Linked lists

Jump to code

Remove the nth node counted from the end of a singly linked list and return the new head. Assume 1 ≤ n ≤ the list length.

Examples

Example 1

head = [1,2,3,4,5]
n = 2

Output: [1,2,3,5]

Example 2

head = [1]
n = 1

Output: []

Constraints

  • The number of nodes in the list is sz.
  • 1 <= sz <= 30
  • 0 <= Node.val <= 100
  • 1 <= n <= sz

Function contract

Linked lists are displayed as value arrays. Your code receives ListNode objects with val and next fields.

Need a hint?

Use two pointers separated by a fixed gap.

Real linked list interview questions

Questions on the same topic that candidates reported from real company interviews. Some company questions are locked and open with Premium or XP.

Browse all real coding interview questions

Accepted submissions mark this problem complete. Progress stays in this browser.

Run checks 5 examples. Submit checks all 7 cases. A free account runs this problem; no XP needed.
Language
Case 1
Input
[
  [
    1,
    2,
    3,
    4,
    5
  ],
  2
]
Expected
[
  1,
  2,
  3,
  5
]
Case 2
Input
[
  [
    1
  ],
  1
]
Expected
[]
Case 3
Input
[
  [
    1,
    2
  ],
  1
]
Expected
[
  1
]
Case 4
Input
[
  [
    1,
    2,
    3
  ],
  3
]
Expected
[
  2,
  3
]
Case 5
Input
[
  [
    1,
    2,
    3,
    4
  ],
  2
]
Expected
[
  1,
  2,
  4
]

Drafts are saved per language in this browser when storage is available.