KatInterview

Exchange the Front Element with the k-th From the Back

Linked ListsAuto-graded · 18 test cases
EasyAuto-gradedLinked Listslinked-listtwo-pointersswap

Last updated

Tests index arithmetic and edge-case handling by swapping the first element of a sequence with its k-th element counted from the end, including the case where both are the same element.

You are given a sequence of integers values, which represents a singly linked list read from front to back, and an integer k. Counting from the back of the sequence, the last element is the 1st from the end, the one before it is the 2nd from the end, and so on.

Produce a new sequence in which the first element and the k-th element from the end have exchanged positions. All other elements stay exactly where they were.

Rules:

  • Exchange positions, not "values by equality": if the sequence contains duplicates, the swap still concerns the first position and the position that is k-th from the end.
  • If the k-th element from the end is itself the first element (that happens exactly when k equals the length of the sequence), the sequence is returned unchanged.
  • Do not modify the input list; return a new list.

In a linked-list setting, you would do this by relinking nodes in O(1) extra memory rather than copying values. Here the function receives and returns plain Python lists, and the result must be the same as that relinking would produce.

Constraints

  • 1 <= k <= len(values)
  • values contains at least one element
  • Elements are integers (duplicates are allowed)
  • The returned list must have the same length as values

Examples

Example 1

Input: swap_front_with_kth_from_back([1, 2, 3, 4, 5, 6], 1)

Output: [6, 2, 3, 4, 5, 1]

Example 2

Input: swap_front_with_kth_from_back([1, 2, 3, 4, 5, 6], 2)

Output: [5, 2, 3, 4, 1, 6]

Example 3

Input: swap_front_with_kth_from_back([1, 2, 3, 4, 5, 6], 5)

Output: [2, 1, 3, 4, 5, 6]

Hints

Hint 1

Convert 'k-th from the end' into a zero-based index from the front. For a sequence of length n, what index is it?

Hint 2

The first element sits at index 0. If the target index is also 0, there is nothing to do; otherwise exactly two positions change.

Hint 3

Copy the input before swapping so the caller's list is not mutated. For the pointer version, a pointer running k steps ahead of another finds the target in one pass, and the case where the target directly follows the head needs separate handling.