Swapping Nodes in a Linked List - Problem

Imagine you have a chain of connected nodes, and you need to perform a symmetric swap operation. You're given the head of a linked list and an integer k.

Your task is to swap the values of two specific nodes:

  • The kth node from the beginning (1-indexed)
  • The kth node from the end (1-indexed)

For example, in a list [1,2,3,4,5] with k=2, you would swap the 2nd node from start (value 2) with the 2nd node from end (value 4), resulting in [1,4,3,2,5].

Important: You only need to swap the values, not the actual node positions. Return the head of the modified linked list.

Input & Output

example_1.py โ€” Basic Case
$ Input: head = [1,2,3,4,5], k = 2
โ€บ Output: [1,4,3,2,5]
๐Ÿ’ก Note: Swap the 2nd node from beginning (value 2) with 2nd node from end (value 4). The result is [1,4,3,2,5].
example_2.py โ€” 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: Swap the 5th node from beginning (value 7) with 5th node from end (value 8). In a 10-node list, 5th from end is 6th from beginning.
example_3.py โ€” Single Node
$ Input: head = [1], k = 1
โ€บ Output: [1]
๐Ÿ’ก Note: With only one node, the 1st from beginning and 1st from end are the same node. Swapping it with itself results in no change.

Constraints

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

Visualization

Tap to expand
Two-Pointer Gap Technique VisualizationPhase 1: Create k-distance gap12345secondfirstk=2 steps moved, gap createdPhase 2: Move both pointers to end12345secondfirstBoth moved together maintaining gapResult: Swap values 2 โ†” 4โœ“ Found both target nodes in single passโœ“ Time: O(n), Space: O(1)
Understanding the Visualization
1
Initialize Pointers
Both pointers start at the head of the linked list
2
Create Gap
Move first pointer k steps ahead, creating a k-node gap
3
Save Reference
Store reference to the kth node from beginning
4
Move Together
Advance both pointers until first reaches the end
5
Swap Values
Second pointer is now at kth from end, swap the values
Key Takeaway
๐ŸŽฏ Key Insight: The gap technique automatically positions the second pointer at the kth node from the end when the first pointer reaches the end, eliminating the need for list length calculation.
Asked in
Amazon 45 Microsoft 32 Google 28 Meta 22 Apple 18
89.6K Views
Medium Frequency
~15 min Avg. Time
2.3K 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