Linked List Techniques · 15 min · free lesson

Reverse Nodes in K-Groups: When to Use It

Recognise the problem shape before choosing Reverse Nodes in K-Groups.

Core idea

A short suffix must remain in its original order. State the input preconditions before applying this invariant.

Algorithm Atlas · worked example

See the algorithm, step by step

On your device

Verify a complete group exists, reverse exactly that range, then reconnect both boundaries.

O(n) time · O(1) links135 execution steps
main · before line 61Initialize a local value

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

Data & variables

Changed Source index
Example input1->2->3->4->5->6->7

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

Call stack · 1 frame
  1. maincall 1

Rust source

Line 61
type Link = Option<Box<ListNode>>;
struct ListNode {
    value: i32,
    next: Link,
}
fn list(values: &[i32]) -> Link {
    values.iter().rev().fold(None, |next, &value| {
        Some(Box::new(ListNode { value, next }))
    })
}
fn list_values(head: &Link) -> Vec<i32> {
    let mut out = Vec::new();
    let mut p = head.as_deref();
    while let Some(n) = p {
        out.push(n.value);
        p = n.next.as_deref();
    }
    out
}
fn csv<T: std::fmt::Display>(a: impl IntoIterator<Item = T>) -> String {
    a.into_iter()
        .map(|x| x.to_string())
        .collect::<Vec<_>>()
        .join(",")
}
fn reverse_groups(mut head: Link, k: usize) -> Link {
    assert!(k > 0);
    let mut result = None;
    let mut tail = &mut result;
    loop {
        let mut scan = head.as_deref();
        let mut count = 0;
        while count < k {
            if let Some(n) = scan {
                scan = n.next.as_deref();
                count += 1;
            } else {
                break;
            }
        }
        if count < k {
            *tail = head;
            break;
        }
        let mut group = None;
        for _ in 0..k {
            let mut n = head.take().unwrap();
            head = n.next.take();
            n.next = group;
            group = Some(n);
        }
        *tail = group;
        for _ in 0..k {
            tail = &mut tail.as_mut().unwrap().next;
        }
    }
    result
}
 
fn main() {
    let result = csv(list_values(&reverse_groups(
        list(&[1, 2, 3, 4, 5, 6, 7]),
        3,
    )));
    println!("{result}");
}

Try your own version

Compare the visible input `1->2->3->4->5->6->7` with `1->2->3->4->5->6`. Predict why their results are `3,2,1,6,5,4,7` and `3,2,1,6,5,4`. Then change one legal value and explain whether the same invariant, a short suffix must remain in its original order, still applies.

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. Borrowed or moved values are hidden when they cannot be inspected safely.
Five-panel Linked List Techniques infographic; panel 5 illustrates Reverse K Group.
Reverse K Group: follow panel 5 to see the operation, then trace the lesson's own example.

Understand it

For 1→2→3→4→5→6→7 with k=3, reverse the first group to 3→2→1 and the second to 6→5→4. Only one node remains, so attach 7 unchanged. The result is 3,2,1,6,5,4,7.

The worked program is a complete executable for this pattern. Its core function uses typed input so the state transitions remain visible. The challenge input contract is: Reverse nodes in groups of three; leave a short suffix unchanged. The visible fixture is 1->2->3->4->5->6->7 and its example result is 3,2,1,6,5,4,7. The implementation and additional semantic fixtures were checked against an independent reference calculation. Those bounded tests establish these examples; they are not a proof for all inputs or a measurement on an iPhone.

Return a canonical String from solve: lowercase true/false for booleans; decimal integers without extra signs, leading zeros or whitespace; comma-separated sequence values and semicolon-separated groups. Whole-number medians have no decimal suffix; half medians use .5. Do not append a newline to the returned value. Preserve the explicitly named textual sentinels such as none or #. Input fixtures are bounded so the demonstrated arithmetic fits its named Rust types; satisfy the stated input preconditions before applying the algorithm.

String and character-grid fixtures use ASCII unless the lesson explicitly specifies Unicode scalar values.

A problem is a good match for Reverse Nodes in K-Groups when it asks for block-wise list transformations. Here the concrete task is: Reverse nodes in groups of three; leave a short suffix unchanged. The visible input 1->2->3->4->5->6->7 is an example, not a definition of the whole problem. Ask what operations the solution must support and what the input guarantees. Look for tasks where node identity or one-way traversal matters. An indexed vector solution can hide the pointer constraint rather than solve it. The right choice follows from those guarantees, not from a familiar noun in the prompt.

The decisive invariant is: Verify a complete group exists, reverse exactly that range, then reconnect both boundaries. Try to say why it applies to the task without quoting the implementation. Which fact becomes known after one update, and which possible answers remain? A list algorithm changes relationships between nodes, not just values. Draw the next pointers before and after each mutation. If that claim cannot be maintained on a legal input, the pattern is wrong or one of its preconditions is missing. A counterexample is more useful than a vague warning: change one property of the sample, trace the first two steps, and identify the exact claim that fails.

Compare costs before committing. The advertised bound is O(n) time · O(1) links; identify the operation responsible for it and the extra memory it needs. Then compare a straightforward alternative: a direct scan, full sort, or repeated recomputation may be easier but can pay for the same work many times. Do not choose the more elaborate method just because it has a famous name. For the sample, predict 3,2,1,6,5,4,7 and explain which part of the state lets the method reach that result.

When the prompt is ambiguous, ask about input size, ordering, duplicates, and required output format. Check an empty list, one node, a head or tail change, and cycles when the problem allows them. Rust ownership makes linked structures explicit: use the provided node type, take links carefully, and preserve access to the remaining chain. The Rust sketch can show a useful primitive without proving that the whole task is solved; connect each primitive to the requested output. You should be able to name a fitting case, a near miss, and the assumption separating them before writing the first line.

The pattern

Verify a complete group exists, reverse exactly that range, then reconnect both boundaries.

When to use it: block-wise list transformations

Complexity: O(n) time · O(1) links

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

Read the code

type Link = Option<Box<ListNode>>;
struct ListNode {
    value: i32,
    next: Link,
}
fn list(values: &[i32]) -> Link {
    values.iter().rev().fold(None, |next, &value| {
        Some(Box::new(ListNode { value, next }))
    })
}
fn list_values(head: &Link) -> Vec<i32> {
    let mut out = Vec::new();
    let mut p = head.as_deref();
    while let Some(n) = p {
        out.push(n.value);
        p = n.next.as_deref();
    }
    out
}
fn csv<T: std::fmt::Display>(a: impl IntoIterator<Item = T>) -> String {
    a.into_iter()
        .map(|x| x.to_string())
        .collect::<Vec<_>>()
        .join(",")
}
fn reverse_groups(mut head: Link, k: usize) -> Link {
    assert!(k > 0);
    let mut result = None;
    let mut tail = &mut result;
    loop {
        let mut scan = head.as_deref();
        let mut count = 0;
        while count < k {
            if let Some(n) = scan {
                scan = n.next.as_deref();
                count += 1;
            } else {
                break;
            }
        }
        if count < k {
            *tail = head;
            break;
        }
        let mut group = None;
        for _ in 0..k {
            let mut n = head.take().unwrap();
            head = n.next.take();
            n.next = group;
            group = Some(n);
        }
        *tail = group;
        for _ in 0..k {
            tail = &mut tail.as_mut().unwrap().next;
        }
    }
    result
}

fn main() {
    let result = csv(list_values(&reverse_groups(
        list(&[1, 2, 3, 4, 5, 6, 7]),
        3,
    )));
    println!("{result}");
}

Complete std-only reverse-k-group program for its typed teaching fixture. Parsing and output construction are separate from the core algorithm.

Try it

Compare the visible and independent fixtures. Explain the input assumption that makes this algorithm applicable, then identify a change that would invalidate it.

What success looks like: You can justify the choice from constraints rather than from a remembered problem title.

Check your understanding

Trace Reverse Nodes in K-Groups on input 9->1->7. Which result follows from the documented contract?

Reveal the answer
  1. 1,9
  2. 7,1,9
  3. 8,1,9

For this input the result is 7,1,9. A short suffix must remain in its original order. Compare this independent fixture with the worked trace: For 1→2→3→4→5→6→7 with k=3, reverse the first group to 3→2→1 and the second to 6→5→4. Only one node remains, so attach 7 unchanged. The result is 3,2,1,6,5,4,7.

Go deeper

Common misconception: “Every suffix must be reversed regardless of length”

A short suffix must remain in its original order. For 1→2→3→4→5→6→7 with k=3, reverse the first group to 3→2→1 and the second to 6→5→4. Only one node remains, so attach 7 unchanged. The result is 3,2,1,6,5,4,7.

  1. Concrete transition: For 1→2→3→4→5→6→7 with k=3, reverse the first group to 3→2→1 and the second to 6→5→4. Only one node remains, so attach 7 unchanged. The result is 3,2,1,6,5,4,7.
  2. Independent second fixture: Input 9->1->7 produces 7,1,9. Execute the named function in the worked program with these typed arguments, then compare its actual result with this independently computed expectation.
  3. Boundary and contract: Input 3->3->1->4 produces 1,3,3,4. A short suffix must remain in its original order. The stated work bound is O(n) time · O(1) links. Count actual state changes; a successful output test alone does not prove that bound.

Transfer challenge: Compare the visible input 1->2->3->4->5->6->7 with 1->2->3->4->5->6. Predict why their results are 3,2,1,6,5,4,7 and 3,2,1,6,5,4. Then change one legal value and explain whether the same invariant, a short suffix must remain in its original order, still applies.

Connections

  • Reverse Nodes in K-Groups: Mental Model: Verify a complete group exists, reverse exactly that range, then reconnect both boundaries.
  • Challenge: Reverse Nodes in K-Groups: Reverse nodes in groups of three; leave a short suffix unchanged.
Reveal the Algorithm Atlas answer

3,2,1,6,5,4,7

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: Reverse Nodes in K-Groups: When to Use It (courseId "algorithms", lessonId "algorithm.reverse-k-group.recognize")
Link: https://crabrix.com/learn/algorithms/algorithm.reverse-k-group.recognize
Goal: A short suffix must remain in its original order. State the input preconditions before applying this invariant.
Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=algorithms/algorithm.reverse-k-group.recognize) 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.