Swapping Nodes in a Linked List - Problem

You are given the head of a linked list, and an integer k.

Return the head of the linked list after swapping the values of the kth node from the beginning and the kth node from the end (the list is 1-indexed).

Note: You need to swap the values, not the nodes themselves.

Input & Output

Example 1 — Basic Case
$ Input: head = [1,2,3,4,5], k = 2
Output: [1,4,3,2,5]
💡 Note: The 2nd node from beginning has value 2, the 2nd node from end has value 4. After swapping, the list becomes [1,4,3,2,5]
Example 2 — Middle Element
$ Input: head = [7,9,6,6,7,8,3,0,9,5], k = 5
Output: [7,9,6,6,8,7,3,0,9,5]
💡 Note: The 5th node from beginning has value 7, the 5th node from end has value 8. After swapping values, we get [7,9,6,6,8,7,3,0,9,5]
Example 3 — Same Node
$ Input: head = [1], k = 1
Output: [1]
💡 Note: Only one node in the list, so the 1st from beginning and 1st from end is the same node. No change needed.

Constraints

  • The number of nodes in the list is n.
  • 1 ≤ k ≤ n ≤ 105
  • 0 ≤ Node.val ≤ 100

Visualization

Tap to expand
Swapping Nodes: k=2 in List [1,2,3,4,5]Original List123452nd from start2nd from endSwap valuesResult List14325
Understanding the Visualization
1
Input
Linked list [1,2,3,4,5] with k=2
2
Identify
Find 2nd from start (value 2) and 2nd from end (value 4)
3
Swap
Exchange values to get [1,4,3,2,5]
Key Takeaway
🎯 Key Insight: Use two pointers - when first pointer moves k steps ahead, moving both together finds the symmetric positions efficiently
Asked in
Amazon 45 Microsoft 32 Facebook 28 Google 25
67.5K Views
Medium Frequency
~15 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen