Swapping Nodes in a Linked List
Problem Statement
You are given the head of a linked list and a number k. Positions are counted from 1.
Swap the values of two nodes: the k-th node from the start and the k-th node from the end. Return the head of the list.
The head of a linked list with n nodes, and an integer k with 1 ≤ k ≤ n.
The head of the same list after the two values are swapped.
2nd from the start is 2, 2nd from the end is 4. Swap them.
5th from the start is 7 (position 5), 5th from the end is 8 (position 6). Swap them.
In a list of odd length, the middle node is k-th from both ends, so it swaps with itself and nothing changes.
- • The list has n nodes, 1 ≤ k ≤ n ≤ 10^5
- • 0 ≤ Node.val ≤ 100
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
Copy to a vector, swap two indices, write the values back
Count n; walk k − 1 steps for one node and n − k steps for the other
first = k-th from start; then fast from first and second from head until fast is last
Copy all values into a vector. In an array, the k-th from the start is index k − 1 and the k-th from the end is index n − k. Swap those two, then walk the list again and write the values back.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Linked List — Fast & Slow translate into production architectures and low-level memory mechanics.
Foundations: Object-Oriented Principles in C++23
Class invariants, pure virtual interfaces, and RAII smart pointers.
Food Delivery System (Zomato Architecture)
Real-world machine coding application of algorithms and design patterns.
Pointers vs References Deep Dive
Pointer arithmetic and memory layout under the hood.
Virtual Method Table (vtable) & Memory Layout
Polymorphism, vptr overhead, and multiple inheritance in memory.