Swapping Nodes in a Linked List

MediumLinked Listtwo pointers

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

You are given the head of a linked list with n nodes and an integer k with 1 <= k <= n. Swap the **values** of the k-th node from the beginning and the k-th node from the end (both 1-indexed), and return the head of the list. If both positions refer to the same node (the exact middle of an odd-length list), the list is unchanged. A single pass with two pointers finds both nodes in O(n) time.

Examples

Input: head = [1,2,3,4,5], k = 2
Output: [1,4,3,2,5]
The 2nd node from the front holds 2 and the 2nd from the back holds 4.
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]
The 5th from the front is 7 and the 5th from the back is 8.

Constraints

  • 1 <= n <= 10^5
  • 1 <= k <= n
  • 0 <= Node.val <= 100

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More two pointers problems