Linked List Techniques · 15 min · free lesson

Challenge: Gap Pointer Removal

Remove the second node from the end of a list with at least two nodes and return the remaining values.

Core idea

Open a gap of two links, then move both cursors until the lead reaches the last node. Remove the second node from the end of a list with at least two nodes and return the remaining values.

Algorithm Atlas · worked example

See the algorithm, step by step

On your device

Keep a fixed gap so the leading pointer reaching the end positions the trailing pointer before the target.

O(n) time · O(1) extra space over the arena22 execution steps
main · before line 56Initialize a local value

This call is starting. Local values appear as they are initialized.

Data & variables

Changed Source index
Example input1->2

Follow the code. Data appears here when it enters scope.

Call stack · 1 frame
  1. maincall 1

Rust source

Line 56
fn csv<T: std::fmt::Display>(a: impl IntoIterator<Item = T>) -> String {
    a.into_iter()
        .map(|x| x.to_string())
        .collect::<Vec<_>>()
        .join(",")
}
 
struct ListNode {
    value: i32,
    next: Option<usize>,
}
fn arena(values: &[i32]) -> Vec<ListNode> {
    values
        .iter()
        .enumerate()
        .map(|(i, &value)| ListNode {
            value,
            next: (i + 1 < values.len()).then_some(i + 1),
        })
        .collect()
}
// Rust rejects a shared lead reference and a mutable trail reference into one
// Box chain. Two indexes into an arena can move together without that conflict.
fn remove_from_end(nodes: &mut [ListNode], head: usize, n: usize) -> Option<usize> {
    // Open a gap of n links between the two cursors, without measuring the list.
    let mut lead = Some(head);
    for _ in 0..n {
        lead = nodes[lead.expect("n is at most the list length")].next;
    }
    // Lead fell off the end during the gap, so the target is the head itself.
    let Some(mut lead) = lead else {
        return nodes[head].next;
    };
    // Move both until lead is on the last node; trail then sits before the target.
    let mut trail = head;
    while let Some(next) = nodes[lead].next {
        lead = next;
        trail = nodes[trail].next.unwrap();
    }
    let target = nodes[trail].next.unwrap();
    nodes[trail].next = nodes[target].next;
    Some(head)
}
fn remaining_values(values: &[i32], n: usize) -> Vec<i32> {
    let mut nodes = arena(values);
    let mut cursor = remove_from_end(&mut nodes, 0, n);
    let mut out = Vec::new();
    while let Some(i) = cursor {
        out.push(nodes[i].value);
        cursor = nodes[i].next;
    }
    out
}
 
fn main() {
    let result = csv(remaining_values(&[1, 2], 2));
    println!("{result}");
}

Try your own version

Change the independent fixture `1->2` in a legal way, then compare the result with your prediction. Explain how the same invariant applies to the separate visible challenge `1->2->3->4->5`.

Open personal copy in Playground ↗

Start with this exact source and input, change a value, then use Run or Debug locally. This replay stays attached to the original example.

Recordings use a native Rust target. Playground runs on wasm32-wasip1; target-sized types such as usize can have different limits.

Recorded from this Rust example and checked against its original output. Playback runs locally in your browser. Values show the state before the highlighted line.
Five-panel Linked List Techniques infographic; panel 5 illustrates Remove Nth From End.
Remove Nth From End: follow panel 5 to see the operation, then trace the lesson's own example.

Understand it

Open a gap of two links, then move both cursors until the lead reaches the last node. The worked program demonstrates this invariant on an independent fixture, so you can study the implementation before predicting the challenge result.

For teaching input 1->2, the worked program returns 2. Its functions are complete and use only std. Adapt the same state transitions to the visible challenge input 1->2->3->4->5; predict that result before opening the answer reveal. The precise contract is: Remove the second node from the end of a list with at least two nodes and return the remaining values.

Return canonical output: lowercase booleans, decimal integers without leading zeros, comma-separated values and semicolon-separated groups, with no extra whitespace or final newline. Whole medians use integer form and half medians use .5. Textual sentinels such as none and # retain their stated meaning. String and character-grid fixtures use ASCII unless the lesson explicitly specifies Unicode scalar values.

Solve the exact task, not just the visible example: Remove the second node from the end of a list with at least two nodes and return the remaining values. On input 1->2->3->4->5, predict the output before opening the answer reveal. The revealed output is a test oracle for this case, while private checks exercise other legal cases. Start by stating the input grammar and output format in your own words. Parse the complete input, including surrounding whitespace, before relying on any convenient positions in the example.

Build the solution around one maintained claim: Keep a fixed gap so the leading pointer reaching the end positions the trailing pointer before the target. Decide what state represents that claim, how it is initialized, what a single update does, and when the algorithm stops. A list algorithm changes relationships between nodes, not just values. Draw the next pointers before and after each mutation. Trace the visible input by hand and record at least two intermediate states, not only the final answer. If the trace cannot justify your predicted output, there is a gap between the idea and the implementation.

Check both correctness and cost. The intended bound is O(n) time · O(1) extra space over the arena; explain which operation dominates it and how many times the input can trigger that operation. Check an empty list, one node, a head or tail change, and cycles when the problem allows them. Add one small case that should succeed, one boundary case, and one case chosen to challenge the invariant. Compare your hand result with the program's result, then use a failing case to fix the earliest incorrect state transition rather than patching the final output.

The pattern

Keep a fixed gap so the leading pointer reaching the end positions the trailing pointer before the target.

When to use it: nth from end without a length pass

Complexity: O(n) time · O(1) extra space over the arena

Input: 1->2->3->4->5

Read the code

fn csv<T: std::fmt::Display>(a: impl IntoIterator<Item = T>) -> String {
    a.into_iter()
        .map(|x| x.to_string())
        .collect::<Vec<_>>()
        .join(",")
}

struct ListNode {
    value: i32,
    next: Option<usize>,
}
fn arena(values: &[i32]) -> Vec<ListNode> {
    values
        .iter()
        .enumerate()
        .map(|(i, &value)| ListNode {
            value,
            next: (i + 1 < values.len()).then_some(i + 1),
        })
        .collect()
}
// Rust rejects a shared lead reference and a mutable trail reference into one
// Box chain. Two indexes into an arena can move together without that conflict.
fn remove_from_end(nodes: &mut [ListNode], head: usize, n: usize) -> Option<usize> {
    // Open a gap of n links between the two cursors, without measuring the list.
    let mut lead = Some(head);
    for _ in 0..n {
        lead = nodes[lead.expect("n is at most the list length")].next;
    }
    // Lead fell off the end during the gap, so the target is the head itself.
    let Some(mut lead) = lead else {
        return nodes[head].next;
    };
    // Move both until lead is on the last node; trail then sits before the target.
    let mut trail = head;
    while let Some(next) = nodes[lead].next {
        lead = next;
        trail = nodes[trail].next.unwrap();
    }
    let target = nodes[trail].next.unwrap();
    nodes[trail].next = nodes[target].next;
    Some(head)
}
fn remaining_values(values: &[i32], n: usize) -> Vec<i32> {
    let mut nodes = arena(values);
    let mut cursor = remove_from_end(&mut nodes, 0, n);
    let mut out = Vec::new();
    while let Some(i) = cursor {
        out.push(nodes[i].value);
        cursor = nodes[i].next;
    }
    out
}

fn main() {
    let result = csv(remaining_values(&[1, 2], 2));
    println!("{result}");
}

Complete std-only remove-nth-from-end program for its typed teaching fixture. Parsing and output construction are separate from the core algorithm.

Practice starter

pub fn solve(input: &str) -> String {
    // Remove the second node from the end of a list with at least two nodes and return the remaining values.
    // Trim surrounding whitespace; implement parsing and the algorithm.
    let _ = input;
    todo!("implement remove-nth-from-end")
}

Try it

Remove the second node from the end of a list with at least two nodes and return the remaining values.

What success looks like: The private harness prints PASS remove-nth-from-end. It checks at least five distinct semantic inputs plus surrounding-whitespace variants. Explain complexity separately; this harness does not time the algorithm.

Check your understanding

Boundary check for remove-nth-from-end: with input 5->5, what result should solve return?

Reveal the answer
  1. 5
  2. 6
  3. 4

For this input the result is 5. Open a gap of two links, then move both cursors until the lead reaches the last node. Compare this independent fixture with the worked trace: In 1→2→3→4→5, lead moves two links to 3 while trail stays on 1. Both then advance until lead is on 5, leaving trail on 3, just before the target 4. Point trail past the target. In a two-node list, lead falls off the end during the gap, so the target is the head.

Go deeper

Common misconception: “Remove the node with value 2”

Open a gap of two links, then move both cursors until the lead reaches the last node. The independent teaching fixture demonstrates this rule; predict the separate visible challenge before revealing its answer.

  1. Pattern-specific invariant: Open a gap of two links, then move both cursors until the lead reaches the last node. This is the property the named implementation maintains; explain which comparison, state update or recursive return in the worked program establishes it.
  2. Independent typed fixture: The worked call uses 1->2 and computes 2. Keep parsing separate, then identify the core state before and after this call.
  3. Different legal case: For 5->5, the independently calculated result is 5. The complexity discussion uses O(n) time · O(1) extra space over the arena. Verify the state invariant before reasoning about the operation count.

Transfer challenge: Change the independent fixture 1->2 in a legal way, then compare the result with your prediction. Explain how the same invariant applies to the separate visible challenge 1->2->3->4->5.

Connections

  • Gap Pointer Removal: When to Use It: nth from end without a length pass
  • Pointer-Switch Intersection: Mental Model: Switch each pointer to the other head so both traverse equal combined distance.
Reveal the Algorithm Atlas answer

1,2,3,5

Learn this lesson with AI

Paste this into Claude, Codex, Cursor or another agent connected to Crabrix Academy. It contains only this lesson’s public details.

I'm learning Rust with Crabrix Academy. Teach me this lesson with the Crabrix Academy tools.
Lesson: Challenge: Gap Pointer Removal (courseId "algorithms", lessonId "algorithm.remove-nth-from-end.challenge")
Link: https://crabrix.com/learn/algorithms/algorithm.remove-nth-from-end.challenge
Goal: Open a gap of two links, then move both cursors until the lead reaches the last node. Remove the second node from the end of a list with at least two nodes and return the remaining values.
Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=algorithms/algorithm.remove-nth-from-end.challenge) and I will write the code there.
Explain it step by step for my level, let me write the code myself, give hints before any solution, and do not mark anything as passed: only Crabrix checks do that.

In Claude Code, Codex or Cursor, paste it into a chat with Crabrix Academy connected. On a phone, the Claude and ChatGPT apps open the same links.