DevPath

← All problems

Remove Nth Node From End

Medium linked-list · two-pointers

Description

Return the list with the n-th node from the end removed (n is 1-based).

Constraints

1 <= n <= length

Examples

Input: list = [1,2,3,4,5], n = 2

Output: [1,2,3,5]

Hints (1)
  • Advance a lead pointer n steps, then move both until the lead reaches the end.

Solutions

One pass with two pointers. · Time O(n) · Space O(1)

func removeNthFromEnd(list []int, n int) []int {
    idx := len(list) - n
    out := append([]int{}, list[:idx]...)
    out = append(out, list[idx+1:]...)
    return out
}

Create a free account to submit solutions, track progress and save problems.

Create account