Swapping Nodes in a Linked List
Swapping Nodes in a Linked List is a medium linked list problem solved with the dummy node pattern pattern.
The best approach, optimal (one pass, front/back pointers), runs in O(n) time and O(1) space.
Below are 2 approaches in Java, Python, C++ and JavaScript, from two passes (count first) up.
Problem
Swap the values of the k-th node from the beginning and the k-th node from the end of a linked list (1-indexed), and return the head.
Examples
Example 1
- Input
head = [7, 9, 6, 6, 8, 7, 3, 0, 9, 5], k = 5- Output
[7, 9, 6, 6, 7, 8, 3, 0, 9, 5]- Why
- The 5th from the front (8) and the 5th from the end (7) swap values.
Example 2
- Input
head = [1, 2, 3], k = 2- Output
[1, 2, 3]- Why
- The middle node is both, so nothing changes.
Constraints
1 <= k <= n <= 10^5- Swapping the values is allowed.
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (2 examples, or your own). Submit also runs 11 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| Two passes (count first) | O(n) | O(1) |
| Optimal (one pass, front/back pointers) | O(n) | O(1) |
1Two passes (count first)
O(n)O(1)Count n, then walk to node k and node n - k + 1 and swap their values.
- Count n.
- Find the k-th and (n - k + 1)-th nodes; swap values.
class Solution {
public ListNode swapNodes(ListNode head, int k) {
int n = 0;
for (ListNode p = head; p != null; p = p.next) n++;
ListNode a = head, b = head;
for (int i = 1; i < k; i++) a = a.next;
for (int i = 1; i < n - k + 1; i++) b = b.next;
int t = a.val; a.val = b.val; b.val = t;
return head;
}
}class Solution:
def swapNodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
n = 0
p = head
while p:
n += 1
p = p.next
a, b = head, head
for _ in range(1, k):
a = a.next
for _ in range(1, n - k + 1):
b = b.next
a.val, b.val = b.val, a.val
return headclass Solution {
public:
ListNode* swapNodes(ListNode* head, int k) {
int n = 0;
for (ListNode* p = head; p != nullptr; p = p->next) n++;
ListNode* a = head;
ListNode* b = head;
for (int i = 1; i < k; i++) a = a->next;
for (int i = 1; i < n - k + 1; i++) b = b->next;
int t = a->val; a->val = b->val; b->val = t;
return head;
}
};function swapNodes(head, k) {
let n = 0;
for (let p = head; p !== null; p = p.next) n++;
let a = head, b = head;
for (let i = 1; i < k; i++) a = a.next;
for (let i = 1; i < n - k + 1; i++) b = b.next;
const t = a.val; a.val = b.val; b.val = t;
return head;
}2Optimal (one pass, front/back pointers)
O(n)O(1)Walk first to the k-th node. Start second at the head and move both until first reaches the last node; second is then k-th from the end. Swap the values.
- first = k-th node; keep a reference to it.
- fast = first, second = head; while fast.next != null, move both.
- Swap values of the saved k-th node and second.
class Solution {
public ListNode swapNodes(ListNode head, int k) {
ListNode first = head;
for (int i = 1; i < k; i++) first = first.next;
ListNode fast = first, second = head;
while (fast.next != null) { fast = fast.next; second = second.next; }
int t = first.val; first.val = second.val; second.val = t;
return head;
}
}class Solution:
def swapNodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
first = head
for _ in range(1, k):
first = first.next
fast, second = first, head
while fast.next:
fast = fast.next
second = second.next
first.val, second.val = second.val, first.val
return headclass Solution {
public:
ListNode* swapNodes(ListNode* head, int k) {
ListNode* first = head;
for (int i = 1; i < k; i++) first = first->next;
ListNode* fast = first;
ListNode* second = head;
while (fast->next != nullptr) { fast = fast->next; second = second->next; }
int t = first->val; first->val = second->val; second->val = t;
return head;
}
};function swapNodes(head, k) {
let first = head;
for (let i = 1; i < k; i++) first = first.next;
let fast = first, second = head;
while (fast.next !== null) { fast = fast.next; second = second.next; }
const t = first.val; first.val = second.val; second.val = t;
return head;
}Edge cases to test
- k points at the same node from both ends
- k = 1 (swap head and tail)
Hints
Hint 1
Once a pointer is k steps ahead, move a second pointer from the head in lockstep until the first reaches the end.
FAQ
What is the best time complexity for Swapping Nodes in a Linked List?
Optimal (one pass, front/back pointers) runs in O(n) time and O(1) extra space.
Which pattern does Swapping Nodes in a Linked List use?
It is a linked list problem that uses the dummy node pattern pattern. Other problems with the same pattern: Remove Linked List Elements, Delete Nodes From Linked List Present in Array, Merge Two Sorted Lists.
Is there a brute force solution for Swapping Nodes in a Linked List?
Yes. Two passes (count first) takes O(n) time and O(1) space. Count n, then walk to node k and node n - k + 1 and swap their values.
Which edge cases should I test for Swapping Nodes in a Linked List?
k points at the same node from both ends; k = 1 (swap head and tail).