Move K Nodes to Front
Accenture coding challenges question, verified with a worked answer. Free to practise - no sign-up.
Given a Linked List head, move k nodes starting from index n (0-indexed) to the front of the given Linked List.
Input format
Three lines: first line contains the size of the linked list. Second line contains the linked list values. Third line contains n and k.
Output format
Space-separated values of the modified linked list.
Constraints
1 <= size <= 10^5
0 <= n < size
1 <= k <= size - n
Sample tests
Sample 1
Input
9
1 2 3 4 5 6 7 8 9
3 4
Expected
4 5 6 7 1 2 3 8 9Show a reference solution
Reference solution
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def solve_linked_list(values, n, k):
if not values or n == 0 or k == 0:
return values
start_sub = values[n:n+k]
remaining = values[:n] + values[n+k:]
return start_sub + remaining