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).
Example 1:
Input: head = [1,2,3,4,5], k = 2 Output: [1,4,3,2,5]
Example 2:
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]
Constraints:
n.1 <= k <= n <= 1050 <= Node.val <= 100This approach involves two passes through the linked list. In the first pass, we determine the kth node from the beginning. In the second pass, we find the kth node from the end. Once we have both nodes, we swap their values. This approach requires a complete traversal of the list during each pass, but is simple to implement.
The above C solution maintains three pointers: first, second, and current. It first iterates through the linked list to determine the node at position k from the start and counts the list to obtain the total length. Then, it calculates the position for the kth node from the end using this length. By traversing again, it locates the kth node from the end. Finally, it swaps the values of these two nodes.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n) due to two linear passes through the list. Space Complexity: O(1) since we use only pointers.
This approach optimizes the two-pass technique by using a single traversal with two pointers method. The idea is to leverage two pointers where one pointer reaches the kth node while the other starts marking the start from the head. Once the first pointer reaches the end, the second pointer will be at the correct kth position from the end. We then swap the values directly.
This C solution uses two pointers, fast and slow. Initially, fast moves k steps ahead. While it goes till the end, the slow pointer marks the kth position from the end. Thus, after the loop, we hold references to both kth from start and end, allowing us to swap their values.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n), as we make only one pass of the list. Space Complexity: O(1).
| Approach | Complexity |
|---|---|
| Approach 1: Two Pass Technique | Time Complexity: O(n) due to two linear passes through the list. Space Complexity: O(1) since we use only pointers. |
| Approach 2: Single Pass with Two Pointers | Time Complexity: O(n), as we make only one pass of the list. Space Complexity: O(1). |
Swap Nodes in Pairs - Apple Interview Question - Leetcode 24 • NeetCode • 73,215 views views
Watch 9 more video solutions →Practice Swapping Nodes in a Linked List with our built-in code editor and test cases.
Practice on FleetCode