Leetcode 1721: Swapping Nodes in a Linked List

grid47
grid47
Exploring patterns and algorithms
May 18, 2024 6 min read

You are given a singly linked list and an integer k. The task is to swap the values of the kth node from the beginning of the list with the kth node from the end of the list. The list is 1-indexed.
Problem
Approach
Steps
Complexity
Input: You are given the head of a singly linked list and an integer k.
Example: Input: head = [1,2,3,4,5], k = 2
Constraints:
• 1 <= k <= n <= 10^5
• 0 <= Node.val <= 100
Output: Return the modified linked list after swapping the kth node from the beginning with the kth node from the end.
Example: Output: [1,4,3,2,5]
Constraints:
• The list will contain at least k nodes.
Goal: The goal is to swap the values of the kth node from the beginning and the kth node from the end using two pointers.
Steps:
• 1. Initialize two pointers: one starting from the head of the list and the other starting from the end of the list.
• 2. Traverse the list to locate the kth node from the beginning and the kth node from the end.
• 3. Swap the values of these two nodes.
• 4. Return the head of the modified list.
Goal: The input linked list will have at least `k` nodes, and the constraints will ensure that the solution can be computed efficiently for large lists.
Steps:
• 1 <= k <= n <= 10^5
• 0 <= Node.val <= 100
Assumptions:
• The input list is non-empty and contains at least `k` nodes.
Input: Input: head = [1, 2, 3, 4, 5], k = 2
Explanation: The kth node from the beginning is 2 and the kth node from the end is 4. Swapping their values results in the list [1, 4, 3, 2, 5].

Input: Input: head = [7, 9, 6, 6, 7, 8, 3, 0, 9, 5], k = 5
Explanation: The kth node from the beginning is 7 and the kth node from the end is also 7. Swapping their values does not change the list, so the output is [7, 9, 6, 6, 8, 7, 3, 0, 9, 5].

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus